diff --git a/dist/index.js b/dist/index.js index 286f673..8423056 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,14 +1,18 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 87351: +/***/ 44914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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]; @@ -21,14 +25,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__(22037)); -const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(70857)); +const utils_1 = __nccwpck_require__(30302); /** * Commands * @@ -83,13 +87,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') @@ -100,14 +104,18 @@ function escapeProperty(s) { /***/ }), -/***/ 42186: +/***/ 37484: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; 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]; @@ -120,7 +128,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; }; @@ -134,13 +142,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__(87351); -const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(98041); +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__(44914); +const file_command_1 = __nccwpck_require__(24753); +const utils_1 = __nccwpck_require__(30302); +const os = __importStar(__nccwpck_require__(70857)); +const path = __importStar(__nccwpck_require__(16928)); +const oidc_utils_1 = __nccwpck_require__(35306); /** * The code to exit an action */ @@ -154,7 +162,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 //----------------------------------------------------------------------- @@ -165,17 +173,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) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -183,7 +187,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; /** @@ -193,10 +197,10 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('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']}`; } @@ -233,7 +237,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -266,8 +273,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** @@ -276,7 +287,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; //----------------------------------------------------------------------- @@ -307,7 +318,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; /** @@ -316,7 +327,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; /** @@ -325,7 +336,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; /** @@ -334,7 +345,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; /** @@ -353,14 +364,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; /** @@ -396,7 +407,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** @@ -415,11 +430,32 @@ function getIDToken(aud) { }); } exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(71847); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(71847); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(31976); +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__(18968)); //# sourceMappingURL=core.js.map /***/ }), -/***/ 717: +/***/ 24753: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -427,7 +463,11 @@ exports.getIDToken = getIDToken; // 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]; @@ -440,18 +480,19 @@ 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.issueCommand = void 0; +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__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { +const crypto = __importStar(__nccwpck_require__(76982)); +const fs = __importStar(__nccwpck_require__(79896)); +const os = __importStar(__nccwpck_require__(70857)); +const utils_1 = __nccwpck_require__(30302); +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -459,16 +500,31 @@ function issueCommand(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.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, 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. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), -/***/ 98041: +/***/ 35306: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -484,9 +540,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__(39925); -const auth_1 = __nccwpck_require__(23702); -const core_1 = __nccwpck_require__(42186); +const http_client_1 = __nccwpck_require__(54844); +const auth_1 = __nccwpck_require__(44552); +const core_1 = __nccwpck_require__(37484); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -518,7 +574,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) { @@ -536,9 +592,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) { @@ -552,7 +608,467 @@ exports.OidcClient = OidcClient; /***/ }), -/***/ 5278: +/***/ 31976: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +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; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(16928)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map + +/***/ }), + +/***/ 18968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +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__(70857)); +const exec = __importStar(__nccwpck_require__(95236)); +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 + +/***/ }), + +/***/ 71847: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +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.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(70857); +const fs_1 = __nccwpck_require__(79896); +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'; +class Summary { + constructor() { + this._buffer = ''; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map + +/***/ }), + +/***/ 30302: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -599,208 +1115,1015 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 23702: -/***/ ((__unused_webpack_module, exports) => { +/***/ 95236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +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()); + }); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -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) { - options.headers['Authorization'] = 'Bearer ' + this.token; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(13193); +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) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } +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; - +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 39925: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +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()); + }); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const http = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const pm = __nccwpck_require__(16443); -let tunnel; -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__(70857)); +const events = __importStar(__nccwpck_require__(24434)); +const child = __importStar(__nccwpck_require__(35317)); +const path = __importStar(__nccwpck_require__(16928)); +const io = __importStar(__nccwpck_require__(94994)); +const ioUtil = __importStar(__nccwpck_require__(75207)); +const timers_1 = __nccwpck_require__(53557); +/* 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) { - let 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 new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let 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; +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}`; + } } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + 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}`; } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + 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* () { + // 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); + }); + 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.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; + } + else { + append(c); + } + continue; + } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); + } + return args; +} +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}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + 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); + } + 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(); + } +} +//# sourceMappingURL=toolrunner.js.map + +/***/ }), + +/***/ 44552: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + +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; + } + 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.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 + +/***/ }), + +/***/ 54844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* 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__(58611)); +const https = __importStar(__nccwpck_require__(65692)); +const pm = __importStar(__nccwpck_require__(54988)); +const tunnel = __importStar(__nccwpck_require__(20770)); +const undici_1 = __nccwpck_require__(46752); +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; @@ -808,141 +2131,169 @@ class HttpClient { } } options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); } head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); } sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(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 */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let 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); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); + 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* () { + 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.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(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.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; } } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying return response; } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; + } while (numTries < maxTries); + return response; + }); } /** * Needs to be called if keepAlive is set to true in request options. @@ -959,14 +2310,22 @@ class HttpClient { * @param data */ requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); + this.requestRawWithCallback(info, data, callbackForResult); + }); }); } /** @@ -976,21 +2335,24 @@ class HttpClient { * @param onResult */ requestRawWithCallback(info, data, onResult) { - let socket; if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; - let handleResult = (err, res) => { + function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); }); + let socket; req.on('socket', sock => { socket = sock; }); @@ -999,12 +2361,12 @@ class HttpClient { if (socket) { socket.end(); } - handleResult(new Error('Request timeout: ' + info.options.path), null); + handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers - handleResult(err, null); + handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); @@ -1025,9 +2387,18 @@ class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); + const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -1049,21 +2420,19 @@ class HttpClient { info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { - this.handlers.forEach(handler => { + for (const handler of this.handlers) { handler.prepareRequest(info.options); - }); + } } return info; } _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; @@ -1072,38 +2441,31 @@ class HttpClient { } _getAgent(parsedUrl) { let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. - if (!!agent) { + if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; - if (!!this.requestOptions) { + if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __nccwpck_require__(74294); - } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { const agentOptions = { - maxSockets: maxSockets, + maxSockets, keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; @@ -1116,16 +2478,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) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; + // 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 @@ -1136,110 +2494,152 @@ class HttpClient { } return agent; } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - return value; + // 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; } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } } - else { - obj = JSON.parse(contents); + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; } - response.result = obj; + response.headers = res.message.headers; } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; + catch (err) { + // Invalid resource (contents not json); leaving result obj null } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); } else { - msg = 'Failed request: (' + statusCode + ')'; + resolve(response); } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } + })); }); } } exports.HttpClient = HttpClient; - +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 16443: +/***/ 54988: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; + const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { - return proxyUrl; + return undefined; } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } } else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); + return undefined; } - return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } @@ -1255,28 +2655,548 @@ function checkBypass(reqUrl) { reqPort = 443; } // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy - for (let upperNoProxyItem of noProxy + for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; - +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} +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 /***/ }), -/***/ 97174: -/***/ ((__unused_webpack_module, exports) => { +/***/ 75207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +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__(79896)); +const path = __importStar(__nccwpck_require__(16928)); +_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; + }); +} +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(); + }); +} +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 (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + 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 + +/***/ }), + +/***/ 94994: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +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()); + }); +}; +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__(42613); +const path = __importStar(__nccwpck_require__(16928)); +const ioUtil = __importStar(__nccwpck_require__(75207)); +/** + * 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 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 { + 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 { + throw new Error('Destination already exists'); + } + } + } + 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 { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } + } + return result; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); +} +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); + } + } + } + // 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]; + } + 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); + } + } + } + // 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); + } + } + return matches; + }); +} +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 { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// 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 if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 55664: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1370,165 +3290,331 @@ exports.safeParse = function (text, reviver) { /***/ }), -/***/ 47541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 84317: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var authOauthApp = __nccwpck_require__(58459); -var deprecation = __nccwpck_require__(58932); -var universalGithubAppJwt = __nccwpck_require__(84419); -var LRU = _interopDefault(__nccwpck_require__(7129)); -var authOauthUser = __nccwpck_require__(11591); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; +exports.getKeyIndexes = exports.hasFlag = exports.exists = exports.list = void 0; +const commands_json_1 = __importDefault(__nccwpck_require__(7613)); +/** + * Redis command list + * + * All commands are lowercased. + */ +exports.list = Object.keys(commands_json_1.default); +const flags = {}; +exports.list.forEach((commandName) => { + flags[commandName] = commands_json_1.default[commandName].flags.reduce(function (flags, flag) { + flags[flag] = true; + return flags; + }, {}); +}); +/** + * Check if the command exists + */ +function exists(commandName) { + return Boolean(commands_json_1.default[commandName]); } - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); +exports.exists = exists; +/** + * Check if the command has the flag + * + * Some of possible flags: readonly, noscript, loading + */ +function hasFlag(commandName, flag) { + if (!flags[commandName]) { + throw new Error("Unknown command " + commandName); } - } - - return target; + return Boolean(flags[commandName][flag]); } - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; +exports.hasFlag = hasFlag; +/** + * Get indexes of keys in the command arguments + * + * @example + * ```javascript + * getKeyIndexes('set', ['key', 'value']) // [0] + * getKeyIndexes('mget', ['key1', 'key2']) // [0, 1] + * ``` + */ +function getKeyIndexes(commandName, args, options) { + const command = commands_json_1.default[commandName]; + if (!command) { + throw new Error("Unknown command " + commandName); + } + if (!Array.isArray(args)) { + throw new Error("Expect args to be an array"); + } + const keys = []; + const parseExternalKey = Boolean(options && options.parseExternalKey); + const takeDynamicKeys = (args, startIndex) => { + const keys = []; + const keyStop = Number(args[startIndex]); + for (let i = 0; i < keyStop; i++) { + keys.push(i + startIndex + 1); + } + return keys; + }; + const takeKeyAfterToken = (args, startIndex, token) => { + for (let i = startIndex; i < args.length - 1; i += 1) { + if (String(args[i]).toLowerCase() === token.toLowerCase()) { + return i + 1; + } + } + return null; + }; + switch (commandName) { + case "zunionstore": + case "zinterstore": + case "zdiffstore": + keys.push(0, ...takeDynamicKeys(args, 1)); + break; + case "eval": + case "evalsha": + case "eval_ro": + case "evalsha_ro": + case "fcall": + case "fcall_ro": + case "blmpop": + case "bzmpop": + keys.push(...takeDynamicKeys(args, 1)); + break; + case "sintercard": + case "lmpop": + case "zunion": + case "zinter": + case "zmpop": + case "zintercard": + case "zdiff": { + keys.push(...takeDynamicKeys(args, 0)); + break; + } + case "georadius": { + keys.push(0); + const storeKey = takeKeyAfterToken(args, 5, "STORE"); + if (storeKey) + keys.push(storeKey); + const distKey = takeKeyAfterToken(args, 5, "STOREDIST"); + if (distKey) + keys.push(distKey); + break; + } + case "georadiusbymember": { + keys.push(0); + const storeKey = takeKeyAfterToken(args, 4, "STORE"); + if (storeKey) + keys.push(storeKey); + const distKey = takeKeyAfterToken(args, 4, "STOREDIST"); + if (distKey) + keys.push(distKey); + break; + } + case "sort": + case "sort_ro": + keys.push(0); + for (let i = 1; i < args.length - 1; i++) { + let arg = args[i]; + if (typeof arg !== "string") { + continue; + } + const directive = arg.toUpperCase(); + if (directive === "GET") { + i += 1; + arg = args[i]; + if (arg !== "#") { + if (parseExternalKey) { + keys.push([i, getExternalKeyNameLength(arg)]); + } + else { + keys.push(i); + } + } + } + else if (directive === "BY") { + i += 1; + if (parseExternalKey) { + keys.push([i, getExternalKeyNameLength(args[i])]); + } + else { + keys.push(i); + } + } + else if (directive === "STORE") { + i += 1; + keys.push(i); + } + } + break; + case "migrate": + if (args[2] === "") { + for (let i = 5; i < args.length - 1; i++) { + const arg = args[i]; + if (typeof arg === "string" && arg.toUpperCase() === "KEYS") { + for (let j = i + 1; j < args.length; j++) { + keys.push(j); + } + break; + } + } + } + else { + keys.push(2); + } + break; + case "xreadgroup": + case "xread": + // Keys are 1st half of the args after STREAMS argument. + for (let i = commandName === "xread" ? 0 : 3; i < args.length - 1; i++) { + if (String(args[i]).toUpperCase() === "STREAMS") { + for (let j = i + 1; j <= i + (args.length - 1 - i) / 2; j++) { + keys.push(j); + } + break; + } + } + break; + default: + // Step has to be at least one in this case, otherwise the command does + // not contain a key. + if (command.step > 0) { + const keyStart = command.keyStart - 1; + const keyStop = command.keyStop > 0 + ? command.keyStop + : args.length + command.keyStop + 1; + for (let i = keyStart; i < keyStop; i += command.step) { + keys.push(i); + } + } + break; + } + return keys; } - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; +exports.getKeyIndexes = getKeyIndexes; +function getExternalKeyNameLength(key) { + if (typeof key !== "string") { + key = String(key); + } + const hashPos = key.indexOf("->"); + return hashPos === -1 ? key.length : hashPos; } -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - var target = _objectWithoutPropertiesLoose(source, excluded); +/***/ }), - var key, i; +/***/ 98594: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); +"use strict"; - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createAppAuth: () => createAppAuth, + createOAuthUserAuth: () => import_auth_oauth_user2.createOAuthUserAuth +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_request = __nccwpck_require__(66255); +var import_auth_oauth_app = __nccwpck_require__(80260); - return target; -} +// pkg/dist-src/auth.js +var import_deprecation = __nccwpck_require__(14150); +var OAuthAppAuth = __toESM(__nccwpck_require__(80260)); +// pkg/dist-src/get-app-authentication.js +var import_universal_github_app_jwt = __nccwpck_require__(97413); async function getAppAuthentication({ appId, privateKey, timeDifference }) { try { - const appAuthentication = await universalGithubAppJwt.githubAppJwt({ + const appAuthentication = await (0, import_universal_github_app_jwt.githubAppJwt)({ id: +appId, privateKey, - now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference + now: timeDifference && Math.floor(Date.now() / 1e3) + timeDifference }); return { type: "app", token: appAuthentication.token, appId: appAuthentication.appId, - expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() + expiresAt: new Date(appAuthentication.expiration * 1e3).toISOString() }; } catch (error) { if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { - throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"); + throw new Error( + "The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'" + ); } else { throw error; } } } -// https://github.com/isaacs/node-lru-cache#readme +// pkg/dist-src/cache.js +var import_lru_cache = __nccwpck_require__(32477); function getCache() { - return new LRU({ + return new import_lru_cache.LRUCache({ // cache max. 15000 tokens, that will use less than 10mb memory - max: 15000, + max: 15e3, // Cache for 1 minute less than GitHub expiry - maxAge: 1000 * 60 * 59 + ttl: 1e3 * 60 * 59 }); } async function get(cache, options) { const cacheKey = optionsToCacheKey(options); const result = await cache.get(cacheKey); - if (!result) { return; } - - const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); - const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { + const [ + token, + createdAt, + expiresAt, + repositorySelection, + permissionsString, + singleFileName + ] = result.split("|"); + const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions2, string) => { if (/!$/.test(string)) { - permissions[string.slice(0, -1)] = "write"; + permissions2[string.slice(0, -1)] = "write"; } else { - permissions[string] = "read"; + permissions2[string] = "read"; } - - return permissions; + return permissions2; }, {}); return { token, @@ -1538,28 +3624,42 @@ async function get(cache, options) { repositoryIds: options.repositoryIds, repositoryNames: options.repositoryNames, singleFileName, - repositorySelection: repositorySelection + repositorySelection }; } async function set(cache, options, data) { const key = optionsToCacheKey(options); - const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); - const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); + const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map( + (name) => `${name}${data.permissions[name] === "write" ? "!" : ""}` + ).join(","); + const value = [ + data.token, + data.createdAt, + data.expiresAt, + data.repositorySelection, + permissionsString, + data.singleFileName + ].join("|"); await cache.set(key, value); } - function optionsToCacheKey({ installationId, permissions = {}, repositoryIds = [], repositoryNames = [] }) { - const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); + const permissionsString = Object.keys(permissions).sort().map((name) => permissions[name] === "read" ? name : `${name}!`).join(","); const repositoryIdsString = repositoryIds.sort().join(","); const repositoryNamesString = repositoryNames.join(","); - return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|"); + return [ + installationId, + repositoryIdsString, + repositoryNamesString, + permissionsString + ].filter(Boolean).join("|"); } +// pkg/dist-src/to-token-authentication.js function toTokenAuthentication({ installationId, token, @@ -1571,77 +3671,71 @@ function toTokenAuthentication({ repositoryNames, singleFileName }) { - return Object.assign({ - type: "token", - tokenType: "installation", - token, - installationId, - permissions, - createdAt, - expiresAt, - repositorySelection - }, repositoryIds ? { - repositoryIds - } : null, repositoryNames ? { - repositoryNames - } : null, singleFileName ? { - singleFileName - } : null); + return Object.assign( + { + type: "token", + tokenType: "installation", + token, + installationId, + permissions, + createdAt, + expiresAt, + repositorySelection + }, + repositoryIds ? { repositoryIds } : null, + repositoryNames ? { repositoryNames } : null, + singleFileName ? { singleFileName } : null + ); } -const _excluded = ["type", "factory", "oauthApp"]; +// pkg/dist-src/get-installation-authentication.js async function getInstallationAuthentication(state, options, customRequest) { const installationId = Number(options.installationId || state.installationId); - if (!installationId) { - throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); + throw new Error( + "[@octokit/auth-app] installationId option is required for installation authentication." + ); } - if (options.factory) { - const _state$options = _objectSpread2(_objectSpread2({}, state), options), - { - type, - factory, - oauthApp - } = _state$options, - factoryAuthOptions = _objectWithoutProperties(_state$options, _excluded); // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>` - - + const { type, factory, oauthApp, ...factoryAuthOptions } = { + ...state, + ...options + }; return factory(factoryAuthOptions); } - - const optionsWithInstallationTokenFromState = Object.assign({ - installationId - }, options); - + const optionsWithInstallationTokenFromState = Object.assign( + { installationId }, + options + ); if (!options.refresh) { - const result = await get(state.cache, optionsWithInstallationTokenFromState); - + const result = await get( + state.cache, + optionsWithInstallationTokenFromState + ); if (result) { const { - token, - createdAt, - expiresAt, - permissions, - repositoryIds, - repositoryNames, - singleFileName, - repositorySelection + token: token2, + createdAt: createdAt2, + expiresAt: expiresAt2, + permissions: permissions2, + repositoryIds: repositoryIds2, + repositoryNames: repositoryNames2, + singleFileName: singleFileName2, + repositorySelection: repositorySelection2 } = result; return toTokenAuthentication({ installationId, - token, - createdAt, - expiresAt, - permissions, - repositorySelection, - repositoryIds, - repositoryNames, - singleFileName + token: token2, + createdAt: createdAt2, + expiresAt: expiresAt2, + permissions: permissions2, + repositorySelection: repositorySelection2, + repositoryIds: repositoryIds2, + repositoryNames: repositoryNames2, + singleFileName: singleFileName2 }); } } - const appAuthentication = await getAppAuthentication(state); const request = customRequest || state.request; const { @@ -1665,15 +3759,11 @@ async function getInstallationAuthentication(state, options, customRequest) { authorization: `bearer ${appAuthentication.token}` } }); - /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */ - const permissions = permissionsOptional || {}; - /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */ - const repositorySelection = repositorySelectionOptional || "all"; - const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; - const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0; - const createdAt = new Date().toISOString(); + const repositoryIds = repositories ? repositories.map((r) => r.id) : void 0; + const repositoryNames = repositories ? repositories.map((repo) => repo.name) : void 0; + const createdAt = (/* @__PURE__ */ new Date()).toISOString(); await set(state.cache, optionsWithInstallationTokenFromState, { token, createdAt, @@ -1697,872 +3787,670 @@ async function getInstallationAuthentication(state, options, customRequest) { }); } +// pkg/dist-src/auth.js async function auth(state, authOptions) { switch (authOptions.type) { case "app": return getAppAuthentication(state); - // @ts-expect-error "oauth" is not supperted in types - case "oauth": - state.log.warn( // @ts-expect-error `log.warn()` expects string - new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`)); - + state.log.warn( + // @ts-expect-error `log.warn()` expects string + new import_deprecation.Deprecation( + `[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead` + ) + ); case "oauth-app": - return state.oauthApp({ - type: "oauth-app" - }); - + return state.oauthApp({ type: "oauth-app" }); case "installation": - return getInstallationAuthentication(state, _objectSpread2(_objectSpread2({}, authOptions), {}, { + authOptions; + return getInstallationAuthentication(state, { + ...authOptions, type: "installation" - })); - + }); case "oauth-user": - // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions" return state.oauthApp(authOptions); - default: - // @ts-expect-error type is "never" at this point throw new Error(`Invalid auth type: ${authOptions.type}`); } } -const PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) -// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js - +// pkg/dist-src/hook.js +var import_auth_oauth_user = __nccwpck_require__(7030); +var import_request_error = __nccwpck_require__(93708); + +// pkg/dist-src/requires-app-auth.js +var PATHS = [ + "/app", + "/app/hook/config", + "/app/hook/deliveries", + "/app/hook/deliveries/{delivery_id}", + "/app/hook/deliveries/{delivery_id}/attempts", + "/app/installations", + "/app/installations/{installation_id}", + "/app/installations/{installation_id}/access_tokens", + "/app/installations/{installation_id}/suspended", + "/app/installation-requests", + "/marketplace_listing/accounts/{account_id}", + "/marketplace_listing/plan", + "/marketplace_listing/plans", + "/marketplace_listing/plans/{plan_id}/accounts", + "/marketplace_listing/stubbed/accounts/{account_id}", + "/marketplace_listing/stubbed/plan", + "/marketplace_listing/stubbed/plans", + "/marketplace_listing/stubbed/plans/{plan_id}/accounts", + "/orgs/{org}/installation", + "/repos/{owner}/{repo}/installation", + "/users/{username}/installation" +]; function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/{org}/invitations", - "/repos/{owner}/{repo}/collaborators/{username}" - ] */ - const regexes = paths.map(p => p.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - + const regexes = paths.map( + (p) => p.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") + ); + const regex = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})$`; return new RegExp(regex, "i"); } - -const REGEX = routeMatcher(PATHS); +var REGEX = routeMatcher(PATHS); function requiresAppAuth(url) { - return !!url && REGEX.test(url); + return !!url && REGEX.test(url.split("?")[0]); } -const FIVE_SECONDS_IN_MS = 5 * 1000; - +// pkg/dist-src/hook.js +var FIVE_SECONDS_IN_MS = 5 * 1e3; function isNotTimeSkewError(error) { - return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); + return !(error.message.match( + /'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/ + ) || error.message.match( + /'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/ + )); } - async function hook(state, request, route, parameters) { const endpoint = request.endpoint.merge(route, parameters); - const url = endpoint.url; // Do not intercept request to retrieve a new token - + const url = endpoint.url; if (/\/login\/oauth\/access_token$/.test(url)) { return request(endpoint); } - if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { - const { - token - } = await getAppAuthentication(state); - endpoint.headers.authorization = `bearer ${token}`; + const { token: token2 } = await getAppAuthentication(state); + endpoint.headers.authorization = `bearer ${token2}`; let response; - try { response = await request(endpoint); } catch (error) { - // If there's an issue with the expiration, regenerate the token and try again. - // Otherwise rethrow the error for upstream handling. if (isNotTimeSkewError(error)) { throw error; - } // If the date header is missing, we can't correct the system time skew. - // Throw the error to be handled upstream. - - + } if (typeof error.response.headers.date === "undefined") { throw error; } - - const diff = Math.floor((Date.parse(error.response.headers.date) - Date.parse(new Date().toString())) / 1000); + const diff = Math.floor( + (Date.parse(error.response.headers.date) - Date.parse((/* @__PURE__ */ new Date()).toString())) / 1e3 + ); state.log.warn(error.message); - state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); - const { - token - } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { + state.log.warn( + `[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.` + ); + const { token: token3 } = await getAppAuthentication({ + ...state, timeDifference: diff - })); - endpoint.headers.authorization = `bearer ${token}`; + }); + endpoint.headers.authorization = `bearer ${token3}`; return request(endpoint); } - return response; } - - if (authOauthUser.requiresBasicAuth(url)) { - const authentication = await state.oauthApp({ - type: "oauth-app" - }); + if ((0, import_auth_oauth_user.requiresBasicAuth)(url)) { + const authentication = await state.oauthApp({ type: "oauth-app" }); endpoint.headers.authorization = authentication.headers.authorization; return request(endpoint); } - - const { - token, - createdAt - } = await getInstallationAuthentication(state, // @ts-expect-error TBD - {}, request); + const { token, createdAt } = await getInstallationAuthentication( + state, + // @ts-expect-error TBD + {}, + request.defaults({ baseUrl: endpoint.baseUrl }) + ); endpoint.headers.authorization = `token ${token}`; - return sendRequestWithRetries(state, request, endpoint, createdAt); + return sendRequestWithRetries( + state, + request, + endpoint, + createdAt + ); } -/** - * Newly created tokens might not be accessible immediately after creation. - * In case of a 401 response, we retry with an exponential delay until more - * than five seconds pass since the creation of the token. - * - * @see https://github.com/octokit/auth-app.js/issues/65 - */ - async function sendRequestWithRetries(state, request, options, createdAt, retries = 0) { - const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); - + const timeSinceTokenCreationInMs = +/* @__PURE__ */ new Date() - +new Date(createdAt); try { return await request(options); } catch (error) { if (error.status !== 401) { throw error; } - if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { if (retries > 0) { - error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; + error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1e3}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; } - throw error; } - ++retries; - const awaitTime = retries * 1000; - state.log.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); - await new Promise(resolve => setTimeout(resolve, awaitTime)); + const awaitTime = retries * 1e3; + state.log.warn( + `[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1e3}s)` + ); + await new Promise((resolve) => setTimeout(resolve, awaitTime)); return sendRequestWithRetries(state, request, options, createdAt, retries); } } -const VERSION = "3.6.1"; +// pkg/dist-src/version.js +var VERSION = "6.1.3"; +// pkg/dist-src/index.js +var import_auth_oauth_user2 = __nccwpck_require__(7030); function createAppAuth(options) { if (!options.appId) { throw new Error("[@octokit/auth-app] appId option is required"); } - + if (!Number.isFinite(+options.appId)) { + throw new Error( + "[@octokit/auth-app] appId option must be a number or numeric string" + ); + } if (!options.privateKey) { throw new Error("[@octokit/auth-app] privateKey option is required"); } - if ("installationId" in options && !options.installationId) { - throw new Error("[@octokit/auth-app] installationId is set to a falsy value"); + throw new Error( + "[@octokit/auth-app] installationId is set to a falsy value" + ); } - - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); - const request$1 = options.request || request.request.defaults({ + const log = Object.assign( + { + warn: console.warn.bind(console) + }, + options.log + ); + const request = options.request || import_request.request.defaults({ headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-auth-app.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); - const state = Object.assign({ - request: request$1, - cache: getCache() - }, options, options.installationId ? { - installationId: Number(options.installationId) - } : {}, { - log, - oauthApp: authOauthApp.createOAuthAppAuth({ - clientType: "github-app", - clientId: options.clientId || "", - clientSecret: options.clientSecret || "", - request: request$1 - }) - }); // @ts-expect-error not worth the extra code to appease TS - + const state = Object.assign( + { + request, + cache: getCache() + }, + options, + options.installationId ? { installationId: Number(options.installationId) } : {}, + { + log, + oauthApp: (0, import_auth_oauth_app.createOAuthAppAuth)({ + clientType: "github-app", + clientId: options.clientId || "", + clientSecret: options.clientSecret || "", + request + }) + } + ); return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) }); } - -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; - } -})); -exports.createAppAuth = createAppAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 58459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 80260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createOAuthAppAuth: () => createOAuthAppAuth, + createOAuthUserAuth: () => import_auth_oauth_user3.createOAuthUserAuth +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_request = __nccwpck_require__(66255); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var btoa = _interopDefault(__nccwpck_require__(72358)); -var authOauthUser = __nccwpck_require__(11591); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); +// pkg/dist-src/auth.js +var import_btoa_lite = __toESM(__nccwpck_require__(39516)); +var import_auth_oauth_user = __nccwpck_require__(7030); +async function auth(state, authOptions) { + if (authOptions.type === "oauth-app") { + return { + type: "oauth-app", + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType, + headers: { + authorization: `basic ${(0, import_btoa_lite.default)( + `${state.clientId}:${state.clientSecret}` + )}` + } + }; } - - return keys; + if ("factory" in authOptions) { + const { type, ...options } = { + ...authOptions, + ...state + }; + return authOptions.factory(options); + } + const common = { + clientId: state.clientId, + clientSecret: state.clientSecret, + request: state.request, + ...authOptions + }; + const userAuth = state.clientType === "oauth-app" ? await (0, import_auth_oauth_user.createOAuthUserAuth)({ + ...common, + clientType: state.clientType + }) : await (0, import_auth_oauth_user.createOAuthUserAuth)({ + ...common, + clientType: state.clientType + }); + return userAuth(); } -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const _excluded = ["type"]; -async function auth(state, authOptions) { - if (authOptions.type === "oauth-app") { - return { - type: "oauth-app", - clientId: state.clientId, - clientSecret: state.clientSecret, - clientType: state.clientType, - headers: { - authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` - } - }; - } - - if ("factory" in authOptions) { - const _authOptions$state = _objectSpread2(_objectSpread2({}, authOptions), state), - options = _objectWithoutProperties(_authOptions$state, _excluded); // @ts-expect-error TODO: `option` cannot be never, is this a bug? - - - return authOptions.factory(options); - } - - const common = _objectSpread2({ - clientId: state.clientId, - clientSecret: state.clientSecret, - request: state.request - }, authOptions); // TS: Look what you made me do - - - const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })) : await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { - clientType: state.clientType - })); - return userAuth(); -} - -async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - +// pkg/dist-src/hook.js +var import_btoa_lite2 = __toESM(__nccwpck_require__(39516)); +var import_auth_oauth_user2 = __nccwpck_require__(7030); +async function hook(state, request2, route, parameters) { + let endpoint = request2.endpoint.merge( + route, + parameters + ); if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { - return request(endpoint); + return request2(endpoint); } - - if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) { - throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`); + if (state.clientType === "github-app" && !(0, import_auth_oauth_user2.requiresBasicAuth)(endpoint.url)) { + throw new Error( + `[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.` + ); } - - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + const credentials = (0, import_btoa_lite2.default)(`${state.clientId}:${state.clientSecret}`); endpoint.headers.authorization = `basic ${credentials}`; - try { - return await request(endpoint); + return await request2(endpoint); } catch (error) { - /* istanbul ignore if */ - if (error.status !== 401) throw error; + if (error.status !== 401) + throw error; error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`; throw error; } } -const VERSION = "4.3.0"; +// pkg/dist-src/version.js +var VERSION = "7.1.0"; +// pkg/dist-src/index.js +var import_auth_oauth_user3 = __nccwpck_require__(7030); function createOAuthAppAuth(options) { - const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), - clientType: "oauth-app" - }, options); // @ts-expect-error not worth the extra code to appease TS - + const state = Object.assign( + { + request: import_request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }), + clientType: "oauth-app" + }, + options + ); return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) }); } - -Object.defineProperty(exports, "createOAuthUserAuth", ({ - enumerable: true, - get: function () { - return authOauthUser.createOAuthUserAuth; - } -})); -exports.createOAuthAppAuth = createOAuthAppAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 44344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87895: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var oauthMethods = __nccwpck_require__(88445); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - return target; -} +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createOAuthDeviceAuth: () => createOAuthDeviceAuth +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_request = __nccwpck_require__(66255); +// pkg/dist-src/get-oauth-access-token.js +var import_oauth_methods = __nccwpck_require__(87042); async function getOAuthAccessToken(state, options) { const cachedAuthentication = getCachedAuthentication(state, options.auth); - if (cachedAuthentication) return cachedAuthentication; // Step 1: Request device and user codes - // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github - - const { - data: verification - } = await oauthMethods.createDeviceCode({ + if (cachedAuthentication) + return cachedAuthentication; + const { data: verification } = await (0, import_oauth_methods.createDeviceCode)({ clientType: state.clientType, clientId: state.clientId, request: options.request || state.request, // @ts-expect-error the extra code to make TS happy is not worth it scopes: options.auth.scopes || state.scopes - }); // Step 2: User must enter the user code on https://github.com/login/device - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser - - await state.onVerification(verification); // Step 3: Exchange device code for access token - // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device - - const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification); + }); + await state.onVerification(verification); + const authentication = await waitForAccessToken( + options.request || state.request, + state.clientId, + state.clientType, + verification + ); state.authentication = authentication; return authentication; } - -function getCachedAuthentication(state, auth) { - if (auth.refresh === true) return false; - if (!state.authentication) return false; - +function getCachedAuthentication(state, auth2) { + if (auth2.refresh === true) + return false; + if (!state.authentication) + return false; if (state.clientType === "github-app") { return state.authentication; } - const authentication = state.authentication; - const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" "); + const newScope = ("scopes" in auth2 && auth2.scopes || state.scopes).join( + " " + ); const currentScope = authentication.scopes.join(" "); return newScope === currentScope ? authentication : false; } - async function wait(seconds) { - await new Promise(resolve => setTimeout(resolve, seconds * 1000)); + await new Promise((resolve) => setTimeout(resolve, seconds * 1e3)); } - async function waitForAccessToken(request, clientId, clientType, verification) { try { const options = { clientId, request, code: verification.device_code - }; // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME - - const { - authentication - } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + }; + const { authentication } = clientType === "oauth-app" ? await (0, import_oauth_methods.exchangeDeviceCode)({ + ...options, clientType: "oauth-app" - })) : await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + }) : await (0, import_oauth_methods.exchangeDeviceCode)({ + ...options, clientType: "github-app" - })); - return _objectSpread2({ + }); + return { type: "token", - tokenType: "oauth" - }, authentication); + tokenType: "oauth", + ...authentication + }; } catch (error) { - // istanbul ignore if - if (!error.response) throw error; + if (!error.response) + throw error; const errorType = error.response.data.error; - if (errorType === "authorization_pending") { await wait(verification.interval); return waitForAccessToken(request, clientId, clientType, verification); } - if (errorType === "slow_down") { await wait(verification.interval + 5); return waitForAccessToken(request, clientId, clientType, verification); } - throw error; } } +// pkg/dist-src/auth.js async function auth(state, authOptions) { return getOAuthAccessToken(state, { auth: authOptions }); } +// pkg/dist-src/hook.js async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); // Do not intercept request to retrieve codes or token - + let endpoint = request.endpoint.merge( + route, + parameters + ); if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { return request(endpoint); } - - const { - token - } = await getOAuthAccessToken(state, { + const { token } = await getOAuthAccessToken(state, { request, - auth: { - type: "oauth" - } + auth: { type: "oauth" } }); endpoint.headers.authorization = `token ${token}`; return request(endpoint); } -const VERSION = "3.1.2"; +// pkg/dist-src/version.js +var VERSION = "6.1.0"; +// pkg/dist-src/index.js function createOAuthDeviceAuth(options) { - const requestWithDefaults = options.request || request.request.defaults({ + const requestWithDefaults = options.request || import_request.request.defaults({ headers: { - "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); - - const { - request: request$1 = requestWithDefaults - } = options, - otherOptions = _objectWithoutProperties(options, ["request"]); - - const state = options.clientType === "github-app" ? _objectSpread2(_objectSpread2({}, otherOptions), {}, { + const { request = requestWithDefaults, ...otherOptions } = options; + const state = options.clientType === "github-app" ? { + ...otherOptions, clientType: "github-app", - request: request$1 - }) : _objectSpread2(_objectSpread2({}, otherOptions), {}, { + request + } : { + ...otherOptions, clientType: "oauth-app", - request: request$1, + request, scopes: options.scopes || [] - }); - + }; if (!options.clientId) { - throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'); + throw new Error( + '[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)' + ); } - if (!options.onVerification) { - throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'); - } // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯ - - + throw new Error( + '[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)' + ); + } return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) }); } - -exports.createOAuthDeviceAuth = createOAuthDeviceAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 11591: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7030: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createOAuthUserAuth: () => createOAuthUserAuth, + requiresBasicAuth: () => requiresBasicAuth +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_request = __nccwpck_require__(66255); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var universalUserAgent = __nccwpck_require__(45030); -var request = __nccwpck_require__(36234); -var authOauthDevice = __nccwpck_require__(44344); -var oauthMethods = __nccwpck_require__(88445); -var btoa = _interopDefault(__nccwpck_require__(72358)); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const VERSION = "1.3.0"; +// pkg/dist-src/version.js +var VERSION = "4.1.0"; +// pkg/dist-src/get-authentication.js +var import_auth_oauth_device = __nccwpck_require__(87895); +var import_oauth_methods = __nccwpck_require__(87042); async function getAuthentication(state) { - // handle code exchange form OAuth Web Flow if ("code" in state.strategyOptions) { - const { - authentication - } = await oauthMethods.exchangeWebFlowCode(_objectSpread2(_objectSpread2({ + const { authentication } = await (0, import_oauth_methods.exchangeWebFlowCode)({ clientId: state.clientId, clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions), {}, { + clientType: state.clientType, + onTokenCreated: state.onTokenCreated, + ...state.strategyOptions, request: state.request - })); - return _objectSpread2({ + }); + return { type: "token", - tokenType: "oauth" - }, authentication); - } // handle OAuth device flow - - + tokenType: "oauth", + ...authentication + }; + } if ("onVerification" in state.strategyOptions) { - const deviceAuth = authOauthDevice.createOAuthDeviceAuth(_objectSpread2(_objectSpread2({ + const deviceAuth = (0, import_auth_oauth_device.createOAuthDeviceAuth)({ clientType: state.clientType, - clientId: state.clientId - }, state.strategyOptions), {}, { + clientId: state.clientId, + onTokenCreated: state.onTokenCreated, + ...state.strategyOptions, request: state.request - })); + }); const authentication = await deviceAuth({ type: "oauth" }); - return _objectSpread2({ - clientSecret: state.clientSecret - }, authentication); - } // use existing authentication - - + return { + clientSecret: state.clientSecret, + ...authentication + }; + } if ("token" in state.strategyOptions) { - return _objectSpread2({ + return { type: "token", tokenType: "oauth", clientId: state.clientId, clientSecret: state.clientSecret, - clientType: state.clientType - }, state.strategyOptions); + clientType: state.clientType, + onTokenCreated: state.onTokenCreated, + ...state.strategyOptions + }; } - throw new Error("[@octokit/auth-oauth-user] Invalid strategy options"); } +// pkg/dist-src/auth.js +var import_oauth_methods2 = __nccwpck_require__(87042); async function auth(state, options = {}) { + var _a, _b; if (!state.authentication) { - // This is what TS makes us do ¯\_(ツ)_/¯ state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state); } - if (state.authentication.invalid) { throw new Error("[@octokit/auth-oauth-user] Token is invalid"); } - - const currentAuthentication = state.authentication; // (auto) refresh for user-to-server tokens - + const currentAuthentication = state.authentication; if ("expiresAt" in currentAuthentication) { - if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) { - const { - authentication - } = await oauthMethods.refreshToken({ + if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < /* @__PURE__ */ new Date()) { + const { authentication } = await (0, import_oauth_methods2.refreshToken)({ clientType: "github-app", clientId: state.clientId, clientSecret: state.clientSecret, refreshToken: currentAuthentication.refreshToken, request: state.request }); - state.authentication = _objectSpread2({ + state.authentication = { tokenType: "oauth", - type: "token" - }, authentication); + type: "token", + ...authentication + }; } - } // throw error for invalid refresh call - - + } if (options.type === "refresh") { if (state.clientType === "oauth-app") { - throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"); + throw new Error( + "[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens" + ); } - if (!currentAuthentication.hasOwnProperty("expiresAt")) { throw new Error("[@octokit/auth-oauth-user] Refresh token missing"); } - } // check or reset token - - + await ((_a = state.onTokenCreated) == null ? void 0 : _a.call(state, state.authentication, { + type: options.type + })); + } if (options.type === "check" || options.type === "reset") { - const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken; - + const method = options.type === "check" ? import_oauth_methods2.checkToken : import_oauth_methods2.resetToken; try { - const { - authentication - } = await method({ + const { authentication } = await method({ // @ts-expect-error making TS happy would require unnecessary code so no clientType: state.clientType, clientId: state.clientId, @@ -2570,27 +4458,28 @@ async function auth(state, options = {}) { token: state.authentication.token, request: state.request }); - state.authentication = _objectSpread2({ + state.authentication = { tokenType: "oauth", - type: "token" - }, authentication); + type: "token", + // @ts-expect-error TBD + ...authentication + }; + if (options.type === "reset") { + await ((_b = state.onTokenCreated) == null ? void 0 : _b.call(state, state.authentication, { + type: options.type + })); + } return state.authentication; } catch (error) { - // istanbul ignore else if (error.status === 404) { - error.message = "[@octokit/auth-oauth-user] Token is invalid"; // @ts-expect-error TBD - + error.message = "[@octokit/auth-oauth-user] Token is invalid"; state.authentication.invalid = true; } - throw error; } - } // invalidate - - + } if (options.type === "delete" || options.type === "deleteAuthorization") { - const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization; - + const method = options.type === "delete" ? import_oauth_methods2.deleteToken : import_oauth_methods2.deleteAuthorization; try { await method({ // @ts-expect-error making TS happy would require unnecessary code so no @@ -2601,110 +4490,110 @@ async function auth(state, options = {}) { request: state.request }); } catch (error) { - // istanbul ignore if - if (error.status !== 404) throw error; + if (error.status !== 404) + throw error; } - state.authentication.invalid = true; return state.authentication; } - return state.authentication; } -/** - * The following endpoints require an OAuth App to authenticate using its client_id and client_secret. - * - * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token - * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token - * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token - * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token - * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization - * - * deprecated: - * - * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization - * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization - * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application - * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application - */ -const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; +// pkg/dist-src/hook.js +var import_btoa_lite = __toESM(__nccwpck_require__(39516)); + +// pkg/dist-src/requires-basic-auth.js +var ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; function requiresBasicAuth(url) { return url && ROUTES_REQUIRING_BASIC_AUTH.test(url); } +// pkg/dist-src/hook.js async function hook(state, request, route, parameters = {}) { - const endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - + const endpoint = request.endpoint.merge( + route, + parameters + ); if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { return request(endpoint); } - if (requiresBasicAuth(endpoint.url)) { - const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + const credentials = (0, import_btoa_lite.default)(`${state.clientId}:${state.clientSecret}`); endpoint.headers.authorization = `basic ${credentials}`; return request(endpoint); - } // TS makes us do this ¯\_(ツ)_/¯ - - - const { - token - } = state.clientType === "oauth-app" ? await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })) : await auth(_objectSpread2(_objectSpread2({}, state), {}, { - request - })); + } + const { token } = state.clientType === "oauth-app" ? await auth({ ...state, request }) : await auth({ ...state, request }); endpoint.headers.authorization = "token " + token; return request(endpoint); } -const _excluded = ["clientId", "clientSecret", "clientType", "request"]; -function createOAuthUserAuth(_ref) { - let { - clientId, - clientSecret, - clientType = "oauth-app", - request: request$1 = request.request.defaults({ - headers: { - "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }) - } = _ref, - strategyOptions = _objectWithoutProperties(_ref, _excluded); - +// pkg/dist-src/index.js +function createOAuthUserAuth({ + clientId, + clientSecret, + clientType = "oauth-app", + request = import_request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } + }), + onTokenCreated, + ...strategyOptions +}) { const state = Object.assign({ clientType, clientId, clientSecret, + onTokenCreated, strategyOptions, - request: request$1 - }); // @ts-expect-error not worth the extra code needed to appease TS - + request + }); return Object.assign(auth.bind(null, state), { // @ts-expect-error not worth the extra code needed to appease TS hook: hook.bind(null, state) }); } createOAuthUserAuth.VERSION = VERSION; - -exports.createOAuthUserAuth = createOAuthUserAuth; -exports.requiresBasicAuth = requiresBasicAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 40334: -/***/ ((__unused_webpack_module, exports) => { +/***/ 77864: +/***/ ((module) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); -const REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -const REGEX_IS_INSTALLATION = /^ghs_/; -const REGEX_IS_USER_TO_SERVER = /^ghu_/; +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; async function auth(token) { const isApp = token.split(/\./).length === 3; const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); @@ -2712,59 +4601,81 @@ async function auth(token) { const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; return { type: "token", - token: token, + token, tokenType }; } -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ +// pkg/dist-src/with-authorization-prefix.js function withAuthorizationPrefix(token) { if (token.split(/\./).length === 3) { return `bearer ${token}`; } - return `token ${token}`; } +// pkg/dist-src/hook.js async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); + const endpoint = request.endpoint.merge( + route, + parameters + ); endpoint.headers.authorization = withAuthorizationPrefix(token); return request(endpoint); } -const createTokenAuth = function createTokenAuth(token) { +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { if (!token) { throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } - if (typeof token !== "string") { - throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); } - token = token.replace(/^(token|bearer) +/i, ""); return Object.assign(auth.bind(null, token), { hook: hook.bind(null, token) }); }; - -exports.createTokenAuth = createTokenAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 79567: -/***/ ((__unused_webpack_module, exports) => { +/***/ 88355: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createUnauthenticatedAuth: () => createUnauthenticatedAuth +}); +module.exports = __toCommonJS(dist_src_exports); +// pkg/dist-src/auth.js async function auth(reason) { return { type: "unauthenticated", @@ -2772,77 +4683,79 @@ async function auth(reason) { }; } +// pkg/dist-src/is-rate-limit-error.js +var import_request_error = __nccwpck_require__(79491); function isRateLimitError(error) { if (error.status !== 403) { return false; } - /* istanbul ignore if */ - - if (!error.response) { return false; } - return error.response.headers["x-ratelimit-remaining"] === "0"; } -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; +// pkg/dist-src/is-abuse-limit-error.js +var import_request_error2 = __nccwpck_require__(79491); +var REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; function isAbuseLimitError(error) { if (error.status !== 403) { return false; } - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); } +// pkg/dist-src/hook.js async function hook(reason, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - return request(endpoint).catch(error => { + const endpoint = request.endpoint.merge( + route, + parameters + ); + return request(endpoint).catch((error) => { if (error.status === 404) { error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; throw error; } - if (isRateLimitError(error)) { error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; throw error; } - if (isAbuseLimitError(error)) { error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; throw error; } - if (error.status === 401) { error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; throw error; } - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); + error.message = error.message.replace( + /\.?$/, + `. May be caused by lack of authentication (${reason}).` + ); } - throw error; }); } -const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { +// pkg/dist-src/index.js +var createUnauthenticatedAuth = function createUnauthenticatedAuth2(options) { if (!options || !options.reason) { - throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); + throw new Error( + "[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth" + ); } - return Object.assign(auth.bind(null, options.reason), { hook: hook.bind(null, options.reason) }); }; - -exports.createUnauthenticatedAuth = createUnauthenticatedAuth; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 76762: +/***/ 79491: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -2850,56 +4763,165 @@ exports.createUnauthenticatedAuth = createUnauthenticatedAuth; Object.defineProperty(exports, "__esModule", ({ value: true })); -var universalUserAgent = __nccwpck_require__(45030); -var beforeAfterHook = __nccwpck_require__(83682); -var request = __nccwpck_require__(36234); -var graphql = __nccwpck_require__(88467); -var authToken = __nccwpck_require__(40334); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; +var deprecation = __nccwpck_require__(14150); +var once = _interopDefault(__nccwpck_require__(55560)); - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; +const logOnceCode = once(deprecation => console.warn(deprecation)); +const logOnceHeaders = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); + // Maintains proper stack trace (only available on V8) + /* istanbul ignore next */ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + // redact request credentials without mutating original request options + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + requestCopy.url = requestCopy.url + // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") + // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + // deprecations + Object.defineProperty(this, "code", { + get() { + logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + }); + Object.defineProperty(this, "headers", { + get() { + logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); + return headers || {}; + } + }); } - - return target; } -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map - var key, i; - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); +/***/ }), - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } +/***/ 61897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return target; -} +"use strict"; -const VERSION = "3.6.0"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -const _excluded = ["authStrategy"]; -class Octokit { +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_before_after_hook = __nccwpck_require__(52732); +var import_request = __nccwpck_require__(66255); +var import_graphql = __nccwpck_require__(70007); +var import_auth_token = __nccwpck_require__(77864); + +// pkg/dist-src/version.js +var VERSION = "5.2.0"; + +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var Octokit = class { + static { + this.VERSION = VERSION; + } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + } + }; + return NewOctokit; + } constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); + const hook = new import_before_after_hook.Collection(); const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, headers: {}, request: Object.assign({}, options.request, { // @ts-ignore internal usage only, no need to type @@ -2909,321 +4931,283 @@ class Octokit { previews: [], format: "" } - }; // prepend default user agent with `options.userAgent` if set - - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; if (options.baseUrl) { requestDefaults.baseUrl = options.baseUrl; } - if (options.previews) { requestDefaults.mediaType.previews = options.previews; } - if (options.timeZone) { requestDefaults.headers["time-zone"] = options.timeZone; } - - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. - + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: noop, + info: noop, + warn: consoleWarn, + error: consoleError + }, + options.log + ); + this.hook = hook; if (!options.authStrategy) { if (!options.auth) { - // (1) this.auth = async () => ({ type: "unauthenticated" }); } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - + const auth = (0, import_auth_token.createTokenAuth)(options.auth); hook.wrap("request", auth.hook); this.auth = auth; } } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, _excluded); - - const auth = authStrategy(Object.assign({ - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ - + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); hook.wrap("request", auth.hook); this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 - - + } const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } +/***/ }), - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } +/***/ 54471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - }; - return OctokitWithDefaults; +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - static plugin(...newPlugins) { - var _a; +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(33843); - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; - } - -} -Octokit.VERSION = VERSION; -Octokit.plugins = []; - -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 59440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/version.js +var VERSION = "9.0.5"; -var isPlainObject = __nccwpck_require__(63287); -var universalUserAgent = __nccwpck_require__(45030); +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; +// pkg/dist-src/util/lowercase-keys.js function lowercaseKeys(object) { if (!object) { return {}; } - return Object.keys(object).reduce((newObj, key) => { newObj[key.toLowerCase()] = object[key]; return newObj; }, {}); } +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/util/merge-deep.js function mergeDeep(defaults, options) { const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { - [key]: options[key] - });else result[key] = mergeDeep(defaults[key], options[key]); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); } else { - Object.assign(result, { - [key]: options[key] - }); + Object.assign(result, { [key]: options[key] }); } }); return result; } +// pkg/dist-src/util/remove-undefined-properties.js function removeUndefinedProperties(obj) { for (const key in obj) { - if (obj[key] === undefined) { + if (obj[key] === void 0) { delete obj[key]; } } - return obj; } +// pkg/dist-src/merge.js function merge(defaults, route, options) { if (typeof route === "string") { let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); + options = Object.assign(url ? { method, url } : { url: method }, options); } else { options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - - - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - + } + options.headers = lowercaseKeys(options.headers); removeUndefinedProperties(options); removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); } - - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); return mergedOptions; } +// pkg/dist-src/util/add-query-parameters.js function addQueryParameters(url, parameters) { const separator = /\?/.test(url) ? "&" : "?"; const names = Object.keys(parameters); - if (names.length === 0) { return url; } - - return url + separator + names.map(name => { + return url + separator + names.map((name) => { if (name === "q") { return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - return `${name}=${encodeURIComponent(parameters[name])}`; }).join("&"); } -const urlVariableRegex = /\{[^}]+\}/g; - +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^}]+\}/g; function removeNonChars(variableName) { return variableName.replace(/^\W+|\W+$/g, "").split(/,/); } - function extractUrlVariableNames(url) { const matches = url.match(urlVariableRegex); - if (!matches) { return []; } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); } +// pkg/dist-src/util/omit.js function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; } -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* istanbul ignore file */ +// pkg/dist-src/util/url-template.js function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } - return part; }).join(""); } - function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } - function encodeValue(operator, value, key) { value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { return encodeUnreserved(key) + "=" + value; } else { return value; } } - function isDefined(value) { - return value !== undefined && value !== null; + return value !== void 0 && value !== null; } - function isKeyOperator(operator) { return operator === ";" || operator === "&" || operator === "?"; } - function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; - + var value = context[key], result = []; if (isDefined(value) && value !== "") { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { value = value.toString(); - if (modifier && modifier !== "*") { value = value.substring(0, parseInt(modifier, 10)); } - - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); } else { if (modifier === "*") { if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); }); } else { - Object.keys(value).forEach(function (k) { + Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } @@ -3231,20 +5215,18 @@ function getValues(context, operator, key, modifier) { } } else { const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); }); } else { - Object.keys(value).forEach(function (k) { + Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { tmp.push(encodeUnreserved(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } - if (isKeyOperator(operator)) { result.push(encodeUnreserved(key) + "=" + tmp.join(",")); } else if (tmp.length !== 0) { @@ -3263,89 +5245,93 @@ function getValues(context, operator, key, modifier) { result.push(""); } } - return result; } - function parseUrl(template) { return { expand: expand.bind(null, template) }; } - function expand(template, context) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - - if (operator && operator !== "+") { - var separator = ","; - - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); } - - return (values.length !== 0 ? operator : "") + values.join(separator); } else { - return values.join(","); + return encodeReserved(literal); } - } else { - return encodeReserved(literal); } - }); + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } } +// pkg/dist-src/parse.js function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - + let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers = Object.assign({}, options.headers); let body; - let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); const urlVariableNames = extractUrlVariableNames(url); url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { url = options.baseUrl + url; } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); const remainingParameters = omit(parameters, omittedParameters); const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - + } if (["GET", "HEAD"].includes(method)) { url = addQueryParameters(url, remainingParameters); } else { @@ -3354,183 +5340,189 @@ function parse(options) { } else { if (Object.keys(remainingParameters).length) { body = remainingParameters; - } else { - headers["content-length"] = 0; } } - } // default content-type for JSON if body is set - - + } if (!headers["content-type"] && typeof body !== "undefined") { headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - + } if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); } +// pkg/dist-src/endpoint-with-defaults.js function endpointWithDefaults(defaults, route, options) { return parse(merge(defaults, route, options)); } +// pkg/dist-src/with-defaults.js function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), parse }); } -const VERSION = "6.0.12"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; - -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 88467: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 70007: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(dist_src_exports); +var import_request3 = __nccwpck_require__(66255); +var import_universal_user_agent = __nccwpck_require__(33843); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/version.js +var VERSION = "7.1.0"; -var request = __nccwpck_require__(36234); -var universalUserAgent = __nccwpck_require__(45030); +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(66255); -const VERSION = "4.8.0"; +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(66255); +// pkg/dist-src/error.js function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n"); + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } - -class GraphqlResponseError extends Error { - constructor(request, headers, response) { +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { super(_buildMessageForResponseErrors(response)); - this.request = request; + this.request = request2; this.headers = headers; this.response = response; - this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties. - + this.name = "GraphqlResponseError"; this.errors = response.errors; - this.data = response.data; // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - + this.data = response.data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } +}; -} - -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { if (options) { if (typeof query === "string" && "query" in options) { - return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) + continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); } } - - const parsedOptions = typeof query === "string" ? Object.assign({ - query - }, options) : query; - const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { if (NON_VARIABLE_OPTIONS.includes(key)) { result[key] = parsedOptions[key]; return result; } - if (!result.variables) { result.variables = {}; } - result.variables[key] = parsedOptions[key]; return result; - }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix - // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 - - const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } - - return request(requestOptions).then(response => { + return request2(requestOptions).then((response) => { if (response.data.errors) { const headers = {}; - for (const key of Object.keys(response.headers)) { headers[key] = response.headers[key]; } - - throw new GraphqlResponseError(requestOptions, headers, response.data); + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); } - return response.data.data; }); } -function withDefaults(request$1, newDefaults) { - const newRequest = request$1.defaults(newDefaults); - +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); const newApi = (query, options) => { return graphql(newRequest, query, options); }; - return Object.assign(newApi, { defaults: withDefaults.bind(null, newRequest), - endpoint: request.request.endpoint + endpoint: newRequest.endpoint }); } -const graphql$1 = withDefaults(request.request, { +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` }, method: "POST", url: "/graphql" @@ -3541,23 +5533,41 @@ function withCustomRequest(customRequest) { url: "/graphql" }); } - -exports.GraphqlResponseError = GraphqlResponseError; -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 51017: -/***/ ((__unused_webpack_module, exports) => { +/***/ 67957: +/***/ ((module) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); - +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + oauthAuthorizationUrl: () => oauthAuthorizationUrl +}); +module.exports = __toCommonJS(dist_src_exports); function oauthAuthorizationUrl(options) { const clientType = options.clientType || "oauth-app"; const baseUrl = options.baseUrl || "https://github.com"; @@ -3570,16 +5580,13 @@ function oauthAuthorizationUrl(options) { state: options.state || Math.random().toString(36).substr(2), url: "" }; - if (clientType === "oauth-app") { const scopes = "scopes" in options ? options.scopes : []; result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes; } - result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result); return result; } - function urlBuilderAuthorize(base, options) { const map = { allowSignup: "allow_signup", @@ -3590,185 +5597,141 @@ function urlBuilderAuthorize(base, options) { state: "state" }; let url = base; - Object.keys(map) // Filter out keys that are null and remove the url key - .filter(k => options[k] !== null) // Filter out empty scopes array - .filter(k => { - if (k !== "scopes") return true; - if (options.clientType === "github-app") return false; + Object.keys(map).filter((k) => options[k] !== null).filter((k) => { + if (k !== "scopes") + return true; + if (options.clientType === "github-app") + return false; return !Array.isArray(options[k]) || options[k].length > 0; - }) // Map Array with the proper URL parameter names and change the value to a string using template strings - // @ts-ignore - .map(key => [map[key], `${options[key]}`]) // Finally, build the URL - .forEach(([key, value], index) => { + }).map((key) => [map[key], `${options[key]}`]).forEach(([key, value], index) => { url += index === 0 ? `?` : "&"; url += `${key}=${encodeURIComponent(value)}`; }); return url; } - -exports.oauthAuthorizationUrl = oauthAuthorizationUrl; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 88445: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87042: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + VERSION: () => VERSION, + checkToken: () => checkToken, + createDeviceCode: () => createDeviceCode, + deleteAuthorization: () => deleteAuthorization, + deleteToken: () => deleteToken, + exchangeDeviceCode: () => exchangeDeviceCode, + exchangeWebFlowCode: () => exchangeWebFlowCode, + getWebFlowAuthorizationUrl: () => getWebFlowAuthorizationUrl, + refreshToken: () => refreshToken, + resetToken: () => resetToken, + scopeToken: () => scopeToken +}); +module.exports = __toCommonJS(dist_src_exports); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var oauthAuthorizationUrl = __nccwpck_require__(51017); -var request = __nccwpck_require__(36234); -var requestError = __nccwpck_require__(10537); -var btoa = _interopDefault(__nccwpck_require__(72358)); - -const VERSION = "1.2.6"; - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } +// pkg/dist-src/version.js +var VERSION = "4.1.0"; - return target; -} +// pkg/dist-src/get-web-flow-authorization-url.js +var import_oauth_authorization_url = __nccwpck_require__(67957); +var import_request = __nccwpck_require__(66255); +// pkg/dist-src/utils.js +var import_request_error = __nccwpck_require__(93708); function requestToOAuthBaseUrl(request) { const endpointDefaults = request.endpoint.DEFAULTS; return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); } async function oauthRequest(request, route, parameters) { - const withOAuthParameters = _objectSpread2({ + const withOAuthParameters = { baseUrl: requestToOAuthBaseUrl(request), headers: { accept: "application/json" - } - }, parameters); - + }, + ...parameters + }; const response = await request(route, withOAuthParameters); - if ("error" in response.data) { - const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { - request: request.endpoint.merge(route, withOAuthParameters), - headers: response.headers - }); // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved - + const error = new import_request_error.RequestError( + `${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, + 400, + { + request: request.endpoint.merge( + route, + withOAuthParameters + ), + headers: response.headers + } + ); error.response = response; throw error; } - return response; } -const _excluded = ["request"]; -function getWebFlowAuthorizationUrl(_ref) { - let { - request: request$1 = request.request - } = _ref, - options = _objectWithoutProperties(_ref, _excluded); - - const baseUrl = requestToOAuthBaseUrl(request$1); // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯ - - return oauthAuthorizationUrl.oauthAuthorizationUrl(_objectSpread2(_objectSpread2({}, options), {}, { +// pkg/dist-src/get-web-flow-authorization-url.js +function getWebFlowAuthorizationUrl({ + request = import_request.request, + ...options +}) { + const baseUrl = requestToOAuthBaseUrl(request); + return (0, import_oauth_authorization_url.oauthAuthorizationUrl)({ + ...options, baseUrl - })); + }); } +// pkg/dist-src/exchange-web-flow-code.js +var import_request2 = __nccwpck_require__(66255); async function exchangeWebFlowCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - code: options.code, - redirect_uri: options.redirectUrl - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request2.request; + const response = await oauthRequest( + request, + "POST /login/oauth/access_token", + { + client_id: options.clientId, + client_secret: options.clientSecret, + code: options.code, + redirect_uri: options.redirectUrl + } + ); const authentication = { clientType: options.clientType, clientId: options.clientId, @@ -3776,85 +5739,92 @@ async function exchangeWebFlowCode(options) { token: response.data.access_token, scopes: response.data.scope.split(/\s+/).filter(Boolean) }; - if (options.clientType === "github-app") { if ("refresh_token" in response.data) { const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp( + apiTimeInMs, + response.data.expires_in + ), authentication.refreshTokenExpiresAt = toTimestamp( + apiTimeInMs, + response.data.refresh_token_expires_in + ); } - delete authentication.scopes; } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return { ...response, authentication }; } - function toTimestamp(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); + return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } +// pkg/dist-src/create-device-code.js +var import_request3 = __nccwpck_require__(66255); async function createDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request3.request; const parameters = { client_id: options.clientId }; - if ("scopes" in options && Array.isArray(options.scopes)) { parameters.scope = options.scopes.join(" "); } - - return oauthRequest(request$1, "POST /login/device/code", parameters); + return oauthRequest(request, "POST /login/device/code", parameters); } +// pkg/dist-src/exchange-device-code.js +var import_request4 = __nccwpck_require__(66255); async function exchangeDeviceCode(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - device_code: options.code, - grant_type: "urn:ietf:params:oauth:grant-type:device_code" - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request4.request; + const response = await oauthRequest( + request, + "POST /login/oauth/access_token", + { + client_id: options.clientId, + device_code: options.code, + grant_type: "urn:ietf:params:oauth:grant-type:device_code" + } + ); const authentication = { clientType: options.clientType, clientId: options.clientId, token: response.data.access_token, scopes: response.data.scope.split(/\s+/).filter(Boolean) }; - if ("clientSecret" in options) { authentication.clientSecret = options.clientSecret; } - if (options.clientType === "github-app") { if ("refresh_token" in response.data) { const apiTimeInMs = new Date(response.headers.date).getTime(); - authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp2( + apiTimeInMs, + response.data.expires_in + ), authentication.refreshTokenExpiresAt = toTimestamp2( + apiTimeInMs, + response.data.refresh_token_expires_in + ); } - delete authentication.scopes; } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return { ...response, authentication }; } - -function toTimestamp$1(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +function toTimestamp2(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } +// pkg/dist-src/check-token.js +var import_request5 = __nccwpck_require__(66255); +var import_btoa_lite = __toESM(__nccwpck_require__(39516)); async function checkToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await request$1("POST /applications/{client_id}/token", { + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request5.request; + const response = await request("POST /applications/{client_id}/token", { headers: { - authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` + authorization: `basic ${(0, import_btoa_lite.default)( + `${options.clientId}:${options.clientSecret}` + )}` }, client_id: options.clientId, access_token: options.token @@ -3866,27 +5836,29 @@ async function checkToken(options) { token: options.token, scopes: response.data.scopes }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; - + if (response.data.expires_at) + authentication.expiresAt = response.data.expires_at; if (options.clientType === "github-app") { delete authentication.scopes; } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return { ...response, authentication }; } +// pkg/dist-src/refresh-token.js +var import_request6 = __nccwpck_require__(66255); async function refreshToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { - client_id: options.clientId, - client_secret: options.clientSecret, - grant_type: "refresh_token", - refresh_token: options.refreshToken - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request6.request; + const response = await oauthRequest( + request, + "POST /login/oauth/access_token", + { + client_id: options.clientId, + client_secret: options.clientSecret, + grant_type: "refresh_token", + refresh_token: options.refreshToken + } + ); const apiTimeInMs = new Date(response.headers.date).getTime(); const authentication = { clientType: "github-app", @@ -3894,63 +5866,72 @@ async function refreshToken(options) { clientSecret: options.clientSecret, token: response.data.access_token, refreshToken: response.data.refresh_token, - expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in), - refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in) + expiresAt: toTimestamp3(apiTimeInMs, response.data.expires_in), + refreshTokenExpiresAt: toTimestamp3( + apiTimeInMs, + response.data.refresh_token_expires_in + ) }; - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return { ...response, authentication }; } - -function toTimestamp$2(apiTimeInMs, expirationInSeconds) { - return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +function toTimestamp3(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1e3).toISOString(); } -const _excluded$1 = ["request", "clientType", "clientId", "clientSecret", "token"]; +// pkg/dist-src/scope-token.js +var import_request7 = __nccwpck_require__(66255); +var import_btoa_lite2 = __toESM(__nccwpck_require__(39516)); async function scopeToken(options) { const { - request: request$1, + request: optionsRequest, clientType, clientId, clientSecret, - token - } = options, - requestOptions = _objectWithoutProperties(options, _excluded$1); - - const response = await (request$1 || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request)("POST /applications/{client_id}/token/scoped", _objectSpread2({ - headers: { - authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}` + token, + ...requestOptions + } = options; + const request = optionsRequest || /* istanbul ignore next: we always pass a custom request in tests */ + import_request7.request; + const response = await request( + "POST /applications/{client_id}/token/scoped", + { + headers: { + authorization: `basic ${(0, import_btoa_lite2.default)(`${clientId}:${clientSecret}`)}` + }, + client_id: clientId, + access_token: token, + ...requestOptions + } + ); + const authentication = Object.assign( + { + clientType, + clientId, + clientSecret, + token: response.data.token }, - client_id: clientId, - access_token: token - }, requestOptions)); - const authentication = Object.assign({ - clientType, - clientId, - clientSecret, - token: response.data.token - }, response.data.expires_at ? { - expiresAt: response.data.expires_at - } : {}); - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + response.data.expires_at ? { expiresAt: response.data.expires_at } : {} + ); + return { ...response, authentication }; } +// pkg/dist-src/reset-token.js +var import_request8 = __nccwpck_require__(66255); +var import_btoa_lite3 = __toESM(__nccwpck_require__(39516)); async function resetToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - const response = await request$1("PATCH /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request8.request; + const auth = (0, import_btoa_lite3.default)(`${options.clientId}:${options.clientSecret}`); + const response = await request( + "PATCH /applications/{client_id}/token", + { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + } + ); const authentication = { clientType: options.clientType, clientId: options.clientId, @@ -3958,77 +5939,94 @@ async function resetToken(options) { token: response.data.token, scopes: response.data.scopes }; - if (response.data.expires_at) authentication.expiresAt = response.data.expires_at; - + if (response.data.expires_at) + authentication.expiresAt = response.data.expires_at; if (options.clientType === "github-app") { delete authentication.scopes; } - - return _objectSpread2(_objectSpread2({}, response), {}, { - authentication - }); + return { ...response, authentication }; } +// pkg/dist-src/delete-token.js +var import_request9 = __nccwpck_require__(66255); +var import_btoa_lite4 = __toESM(__nccwpck_require__(39516)); async function deleteToken(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/token", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request9.request; + const auth = (0, import_btoa_lite4.default)(`${options.clientId}:${options.clientSecret}`); + return request( + "DELETE /applications/{client_id}/token", + { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + } + ); } +// pkg/dist-src/delete-authorization.js +var import_request10 = __nccwpck_require__(66255); +var import_btoa_lite5 = __toESM(__nccwpck_require__(39516)); async function deleteAuthorization(options) { - const request$1 = options.request || - /* istanbul ignore next: we always pass a custom request in tests */ - request.request; - const auth = btoa(`${options.clientId}:${options.clientSecret}`); - return request$1("DELETE /applications/{client_id}/grant", { - headers: { - authorization: `basic ${auth}` - }, - client_id: options.clientId, - access_token: options.token - }); + const request = options.request || /* istanbul ignore next: we always pass a custom request in tests */ + import_request10.request; + const auth = (0, import_btoa_lite5.default)(`${options.clientId}:${options.clientSecret}`); + return request( + "DELETE /applications/{client_id}/grant", + { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + } + ); } - -exports.VERSION = VERSION; -exports.checkToken = checkToken; -exports.createDeviceCode = createDeviceCode; -exports.deleteAuthorization = deleteAuthorization; -exports.deleteToken = deleteToken; -exports.exchangeDeviceCode = exchangeDeviceCode; -exports.exchangeWebFlowCode = exchangeWebFlowCode; -exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl; -exports.refreshToken = refreshToken; -exports.resetToken = resetToken; -exports.scopeToken = scopeToken; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 25823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 79102: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var requestError = __nccwpck_require__(10537); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + enterpriseCompatibility: () => enterpriseCompatibility +}); +module.exports = __toCommonJS(dist_src_exports); +var import_request_error = __nccwpck_require__(93708); -const VERSION = "1.3.0"; +// pkg/dist-src/version.js +var VERSION = "4.1.0"; +// pkg/dist-src/index.js function enterpriseCompatibility(octokit) { octokit.hook.wrap("request", async (request, options) => { - // TODO: implement fix for #62 here - // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 if (/\/orgs\/[^/]+\/teams/.test(options.url)) { try { return await request(options); @@ -4036,120 +6034,79 @@ function enterpriseCompatibility(octokit) { if (error.status !== 404) { throw error; } - if (!error.response || !error.response.headers["x-github-enterprise-version"]) { throw error; } - - const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}"); - throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, { - request: options - }); + const deprecatedUrl = options.url.replace( + /\/orgs\/[^/]+\/teams\/[^/]+/, + "/teams/{team_id}" + ); + throw new import_request_error.RequestError( + `"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, + 404, + { + request: options + } + ); } } - return request(options); }); } enterpriseCompatibility.VERSION = VERSION; - -exports.enterpriseCompatibility = enterpriseCompatibility; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 64193: -/***/ ((__unused_webpack_module, exports) => { +/***/ 38082: +/***/ ((module) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -const VERSION = "2.17.0"; - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} +// pkg/dist-src/version.js +var VERSION = "9.2.1"; -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ +// pkg/dist-src/normalize-paginated-list-response.js function normalizePaginatedListResponse(response) { - // endpoints can respond with 204 if repository is empty if (!response.data) { - return _objectSpread2(_objectSpread2({}, response), {}, { + return { + ...response, data: [] - }); + }; } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - + if (!responseNeedsNormalization) + return response; const incompleteResults = response.data.incomplete_results; const repositorySelection = response.data.repository_selection; const totalCount = response.data.total_count; @@ -4159,19 +6116,17 @@ function normalizePaginatedListResponse(response) { const namespaceKey = Object.keys(response.data)[0]; const data = response.data[namespaceKey]; response.data = data; - if (typeof incompleteResults !== "undefined") { response.data.incomplete_results = incompleteResults; } - if (typeof repositorySelection !== "undefined") { response.data.repository_selection = repositorySelection; } - response.data.total_count = totalCount; return response; } +// pkg/dist-src/iterator.js function iterator(octokit, route, parameters) { const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); const requestMethod = typeof route === "function" ? route : octokit.request; @@ -4181,26 +6136,18 @@ function iterator(octokit, route, parameters) { return { [Symbol.asyncIterator]: () => ({ async next() { - if (!url) return { - done: true - }; - + if (!url) + return { done: true }; try { - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; } catch (error) { - if (error.status !== 409) throw error; + if (error.status !== 409) + throw error; url = ""; return { value: { @@ -4211,48 +6158,286 @@ function iterator(octokit, route, parameters) { }; } } - }) }; } +// pkg/dist-src/paginate.js function paginate(octokit, route, parameters, mapFn) { if (typeof parameters === "function") { mapFn = parameters; - parameters = undefined; + parameters = void 0; } - - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); } - -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { if (result.done) { return results; } - let earlyExit = false; - function done() { earlyExit = true; } - - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); if (earlyExit) { return results; } - - return gather(octokit, results, iterator, mapFn); + return gather(octokit, results, iterator2, mapFn); }); } -const composePaginateRest = Object.assign(paginate, { +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { iterator }); -const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/packages", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; +// pkg/dist-src/paginating-endpoints.js function isPaginatingEndpoint(arg) { if (typeof arg === "string") { return paginatingEndpoints.includes(arg); @@ -4261,11 +6446,7 @@ function isPaginatingEndpoint(arg) { } } -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - +// pkg/dist-src/index.js function paginateRest(octokit) { return { paginate: Object.assign(paginate.bind(null, octokit), { @@ -4274,174 +6455,390 @@ function paginateRest(octokit) { }; } paginateRest.VERSION = VERSION; - -exports.composePaginateRest = composePaginateRest; -exports.isPaginatingEndpoint = isPaginatingEndpoint; -exports.paginateRest = paginateRest; -exports.paginatingEndpoints = paginatingEndpoints; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 83044: -/***/ ((__unused_webpack_module, exports) => { +/***/ 84935: +/***/ ((module) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} +// pkg/dist-src/version.js +var VERSION = "10.4.1"; -const Endpoints = { +// pkg/dist-src/generated/endpoints.js +var Endpoints = { actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], - createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], - disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], - downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], - downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], - downloadWorkflowRunAttemptLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"], - downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], - enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], - getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], - getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], - getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], - getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { - renamed: ["actions", "getGithubActionsPermissionsRepository"] - }], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"], - getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], - getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], - listJobsForWorkflowRunAttempt: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], - listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], - listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], - listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], - setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], - setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], - setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], - setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] }, activity: { checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], getFeeds: ["GET /feeds"], getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], listEventsForAuthenticatedUser: ["GET /users/{username}/events"], listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], listPublicEvents: ["GET /events"], listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], listPublicEventsForUser: ["GET /users/{username}/events/public"], listPublicOrgEvents: ["GET /orgs/{org}/events"], listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], listReposStarredByAuthenticatedUser: ["GET /user/starred"], listReposStarredByUser: ["GET /users/{username}/starred"], listReposWatchedByUser: ["GET /users/{username}/subscriptions"], @@ -4450,30 +6847,29 @@ const Endpoints = { listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], markNotificationsAsRead: ["PUT /notifications"], markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] }, apps: { - addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", {}, { - renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] - }], - addRepoToInstallationForAuthenticatedUser: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], checkToken: ["POST /applications/{client_id}/token"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], deleteAuthorization: ["DELETE /applications/{client_id}/grant"], deleteInstallation: ["DELETE /app/installations/{installation_id}"], deleteToken: ["DELETE /applications/{client_id}/token"], @@ -4482,91 +6878,323 @@ const Endpoints = { getInstallation: ["GET /app/installations/{installation_id}"], getOrgInstallation: ["GET /orgs/{org}/installation"], getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], - getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], getUserInstallation: ["GET /users/{username}/installation"], getWebhookConfigForApp: ["GET /app/hook/config"], getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], - listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], listInstallations: ["GET /app/installations"], listInstallationsForAuthenticatedUser: ["GET /user/installations"], listPlans: ["GET /marketplace_listing/plans"], listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], listReposAccessibleToInstallation: ["GET /installation/repositories"], listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", {}, { - renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] - }], - removeRepoFromInstallationForAuthenticatedUser: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], resetToken: ["PATCH /applications/{client_id}/token"], revokeInstallationAccessToken: ["DELETE /installation/token"], scopeToken: ["POST /applications/{client_id}/token/scoped"], suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], updateWebhookConfigForApp: ["PATCH /app/hook/config"] }, billing: { getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], - getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], - getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] }, checks: { create: ["POST /repos/{owner}/{repo}/check-runs"], createSuite: ["POST /repos/{owner}/{repo}/check-suites"], get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: ["POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] }, codeScanning: { - deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"], - getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { - renamedParameters: { - alert_id: "alert_number" - } - }], - getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { - renamed: ["codeScanning", "listAlertInstances"] - }], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] }, codesOfConduct: { getAllCodesOfConduct: ["GET /codes_of_conduct"], getConductCode: ["GET /codes_of_conduct/{key}"] }, - emojis: { - get: ["GET /emojis"] + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] }, - enterpriseAdmin: { - disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], - getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], - listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], - setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], - setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], - setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] }, + emojis: { get: ["GET /emojis"] }, gists: { checkIsStarred: ["GET /gists/{gist_id}/star"], create: ["POST /gists"], @@ -4612,33 +7240,52 @@ const Endpoints = { getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, { - renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] - }], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], - removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, { - renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] - }], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, { - renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] - }] + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] }, issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], create: ["POST /repos/{owner}/{repo}/issues"], - createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], createLabel: ["POST /repos/{owner}/{repo}/labels"], createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], @@ -4650,24 +7297,38 @@ const Endpoints = { listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], listForAuthenticatedUser: ["GET /user/issues"], listForOrg: ["GET /orgs/{org}/issues"], listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], listMilestones: ["GET /repos/{owner}/{repo}/milestones"], lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], - removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] }, licenses: { get: ["GET /licenses/{license}"], @@ -4676,120 +7337,340 @@ const Endpoints = { }, markdown: { render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" - } - }] + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] }, meta: { get: ["GET /meta"], + getAllVersions: ["GET /versions"], getOctocat: ["GET /octocat"], getZen: ["GET /zen"], root: ["GET /"] }, migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive"], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive"], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive"], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive"], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], listForAuthenticatedUser: ["GET /user/migrations"], listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: ["GET /user/migrations/{migration_id}/repositories"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: ["GET /user/migrations/{migration_id}/repositories", {}, { - renamed: ["migrations", "listReposForAuthenticatedUser"] - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], startForAuthenticatedUser: ["POST /user/migrations"], startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] }, orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], blockUser: ["PUT /orgs/{org}/blocks/{username}"], cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], listMembers: ["GET /orgs/{org}/members"], listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], listPendingInvitations: ["GET /orgs/{org}/invitations"], listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], removeMember: ["DELETE /orgs/{org}/members/{username}"], removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] }, packages: { - deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], - deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], - deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"], - deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] - }], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] - }], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], - getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], - getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], - getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], - getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], listPackagesForAuthenticatedUser: ["GET /user/packages"], listPackagesForOrganization: ["GET /orgs/{org}/packages"], listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] }, projects: { addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], @@ -4804,7 +7685,9 @@ const Endpoints = { get: ["GET /projects/{project_id}"], getCard: ["GET /projects/columns/cards/{card_id}"], getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], listCards: ["GET /projects/columns/{column_id}/cards"], listCollaborators: ["GET /projects/{project_id}/collaborators"], listColumns: ["GET /projects/{project_id}/columns"], @@ -4813,7 +7696,9 @@ const Endpoints = { listForUser: ["GET /users/{username}/projects"], moveCard: ["POST /projects/columns/cards/{card_id}/moves"], moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], update: ["PATCH /projects/{project_id}"], updateCard: ["PATCH /projects/columns/cards/{card_id}"], updateColumn: ["PATCH /projects/columns/{column_id}"] @@ -4821,190 +7706,420 @@ const Endpoints = { pulls: { checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"], - updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] - }, - rateLimit: { - get: ["GET /rate_limit"] + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] }, + rateLimit: { get: ["GET /rate_limit"] }, reactions: { - createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], - createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions"], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"], + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"] + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] }, repos: { - acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}", {}, { - renamed: ["repos", "acceptInvitationForAuthenticatedUser"] - }], - acceptInvitationForAuthenticatedUser: ["PATCH /user/repository_invitations/{invitation_id}"], - addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], createDeployKey: ["POST /repos/{owner}/{repo}/keys"], createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], createForAuthenticatedUser: ["POST /user/repos"], createFork: ["POST /repos/{owner}/{repo}/forks"], createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], createPagesSite: ["POST /repos/{owner}/{repo}/pages"], createRelease: ["POST /repos/{owner}/{repo}/releases"], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}", {}, { - renamed: ["repos", "declineInvitationForAuthenticatedUser"] - }], - declineInvitationForAuthenticatedUser: ["DELETE /user/repository_invitations/{invitation_id}"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes"], - disableLfsForRepo: ["DELETE /repos/{owner}/{repo}/lfs"], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts"], - downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { - renamed: ["repos", "downloadZipballArchive"] - }], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes"], - enableLfsForRepo: ["PUT /repos/{owner}/{repo}/lfs"], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts"], - generateReleaseNotes: ["POST /repos/{owner}/{repo}/releases/generate-notes"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], - getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], getPages: ["GET /repos/{owner}/{repo}/pages"], getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], getReadme: ["GET /repos/{owner}/{repo}/readme"], getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], getViews: ["GET /repos/{owner}/{repo}/traffic/views"], getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], listCommits: ["GET /repos/{owner}/{repo}/commits"], listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], listDeployments: ["GET /repos/{owner}/{repo}/deployments"], listForAuthenticatedUser: ["GET /user/repos"], listForOrg: ["GET /orgs/{org}/repos"], @@ -5015,70 +8130,117 @@ const Endpoints = { listLanguages: ["GET /repos/{owner}/{repo}/languages"], listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], listTags: ["GET /repos/{owner}/{repo}/tags"], listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], merge: ["POST /repos/{owner}/{repo}/merges"], mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], transfer: ["POST /repos/{owner}/{repo}/transfer"], update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusCheckProtection"] - }], - updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], - uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { - baseUrl: "https://uploads.github.com" - }] + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] }, search: { code: ["GET /search/code"], @@ -5086,306 +8248,498 @@ const Endpoints = { issuesAndPullRequests: ["GET /search/issues"], labels: ["GET /search/labels"], repos: ["GET /search/repositories"], - topics: ["GET /search/topics", { - mediaType: { - previews: ["mercy"] - } - }], + topics: ["GET /search/topics"], users: ["GET /search/users"] }, secretScanning: { - getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] }, teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], list: ["GET /orgs/{org}/teams"], listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], listForAuthenticatedUser: ["GET /user/teams"], listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] }, users: { - addEmailForAuthenticated: ["POST /user/emails", {}, { - renamed: ["users", "addEmailForAuthenticatedUser"] - }], + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], block: ["PUT /user/blocks/{username}"], checkBlocked: ["GET /user/blocks/{username}"], checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys", {}, { - renamed: ["users", "createGpgKeyForAuthenticatedUser"] - }], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: ["POST /user/keys", {}, { - renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] - }], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails", {}, { - renamed: ["users", "deleteEmailForAuthenticatedUser"] - }], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] - }], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}", {}, { - renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] - }], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], follow: ["PUT /user/following/{username}"], getAuthenticated: ["GET /user"], getByUsername: ["GET /users/{username}"], getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}", {}, { - renamed: ["users", "getGpgKeyForAuthenticatedUser"] - }], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}", {}, { - renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] - }], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], list: ["GET /users"], - listBlockedByAuthenticated: ["GET /user/blocks", {}, { - renamed: ["users", "listBlockedByAuthenticatedUser"] - }], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: ["GET /user/emails", {}, { - renamed: ["users", "listEmailsForAuthenticatedUser"] - }], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following", {}, { - renamed: ["users", "listFollowedByAuthenticatedUser"] - }], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], listFollowedByAuthenticatedUser: ["GET /user/following"], listFollowersForAuthenticatedUser: ["GET /user/followers"], listFollowersForUser: ["GET /users/{username}/followers"], listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys", {}, { - renamed: ["users", "listGpgKeysForAuthenticatedUser"] - }], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: ["GET /user/public_emails", {}, { - renamed: ["users", "listPublicEmailsForAuthenticatedUser"] - }], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys", {}, { - renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] - }], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility", {}, { - renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] - }], - setPrimaryEmailVisibilityForAuthenticatedUser: ["PATCH /user/email/visibility"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], unblock: ["DELETE /user/blocks/{username}"], unfollow: ["DELETE /user/following/{username}"], updateAuthenticated: ["PATCH /user"] } }; +var endpoints_default = Endpoints; -const VERSION = "5.13.0"; - -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign({ +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { method, url - }, defaults); - - if (!newMethods[scope]) { - newMethods[scope] = {}; - } - - const scopeMethods = newMethods[scope]; - - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } - - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } - return newMethods; } - function decorate(octokit, scope, methodName, defaults, decorations) { const requestWithDefaults = octokit.request.defaults(defaults); - /* istanbul ignore next */ - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - + let options = requestWithDefaults.endpoint.merge(...args); if (decorations.mapToData) { options = Object.assign({}, options, { data: options[decorations.mapToData], - [decorations.mapToData]: undefined + [decorations.mapToData]: void 0 }); return requestWithDefaults(options); } - if (decorations.renamed) { const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); } - if (decorations.deprecated) { octokit.log.warn(decorations.deprecated); } - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); - - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); - - if (!(alias in options)) { - options[alias] = options[name]; + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; } - - delete options[name]; + delete options2[name]; } } - - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - - + return requestWithDefaults(options2); + } return requestWithDefaults(...args); } - return Object.assign(withDecorations, requestWithDefaults); } +// pkg/dist-src/index.js function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); + const api = endpointsToMethods(octokit); return { rest: api }; } restEndpointMethods.VERSION = VERSION; function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return _objectSpread2(_objectSpread2({}, api), {}, { + const api = endpointsToMethods(octokit); + return { + ...api, rest: api - }); + }; } legacyRestEndpointMethods.VERSION = VERSION; - -exports.legacyRestEndpointMethods = legacyRestEndpointMethods; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 86298: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 33450: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + VERSION: () => VERSION, + retry: () => retry +}); +module.exports = __toCommonJS(dist_src_exports); +var import_core = __nccwpck_require__(61897); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Bottleneck = _interopDefault(__nccwpck_require__(11174)); - -// @ts-ignore -async function errorRequest(octokit, state, error, options) { +// pkg/dist-src/error-request.js +async function errorRequest(state, octokit, error, options) { if (!error.request || !error.request.request) { - // address https://github.com/octokit/plugin-retry.js/issues/8 throw error; - } // retry all >= 400 && not doNotRetry - - + } if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { const retries = options.request.retries != null ? options.request.retries : state.retries; const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); throw octokit.retry.retryRequest(error, retries, retryAfter); - } // Maybe eventually there will be more cases here - - + } throw error; } -// @ts-ignore - -async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); // @ts-ignore - - limiter.on("failed", function (error, info) { +// pkg/dist-src/wrap-request.js +var import_light = __toESM(__nccwpck_require__(63251)); +var import_request_error = __nccwpck_require__(93708); +async function wrapRequest(state, octokit, request, options) { + const limiter = new import_light.default(); + limiter.on("failed", function(error, info) { const maxRetries = ~~error.request.request.retries; const after = ~~error.request.request.retryAfter; options.request.retryCount = info.retryCount + 1; - if (maxRetries > info.retryCount) { - // Returning a number instructs the limiter to retry - // the request after that number of milliseconds have passed return after * state.retryAfterBaseValue; } }); - return limiter.schedule(request, options); + return limiter.schedule( + requestWithGraphqlErrorHandling.bind(null, state, octokit, request), + options + ); +} +async function requestWithGraphqlErrorHandling(state, octokit, request, options) { + const response = await request(request, options); + if (response.data && response.data.errors && response.data.errors.length > 0 && /Something went wrong while executing your query/.test( + response.data.errors[0].message + )) { + const error = new import_request_error.RequestError(response.data.errors[0].message, 500, { + request: options, + response + }); + return errorRequest(state, octokit, error, options); + } + return response; } -const VERSION = "3.0.9"; +// pkg/dist-src/index.js +var VERSION = "6.1.0"; function retry(octokit, octokitOptions) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1000, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - + const state = Object.assign( + { + enabled: true, + retryAfterBaseValue: 1e3, + doNotRetry: [400, 401, 403, 404, 422, 451], + retries: 3 + }, + octokitOptions.retry + ); if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); + octokit.hook.error("request", errorRequest.bind(null, state, octokit)); + octokit.hook.wrap("request", wrapRequest.bind(null, state, octokit)); } - return { retry: { retryRequest: (error, retries, retryAfter) => { error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter + retries, + retryAfter }); return error; } @@ -5393,131 +8747,85 @@ function retry(octokit, octokitOptions) { }; } retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 9968: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 74759: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + throttling: () => throttling +}); +module.exports = __toCommonJS(dist_src_exports); +var import_light = __toESM(__nccwpck_require__(63251)); +var import_core = __nccwpck_require__(61897); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var BottleneckLight = _interopDefault(__nccwpck_require__(11174)); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } +// pkg/dist-src/version.js +var VERSION = "8.2.0"; - return keys; +// pkg/dist-src/wrap-request.js +var noop = () => Promise.resolve(); +function wrapRequest(state, request, options) { + return state.retryLimiter.schedule(doRequest, state, request, options); } - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const VERSION = "3.6.2"; - -const noop = () => Promise.resolve(); // @ts-expect-error - - -function wrapRequest(state, request, options) { - return state.retryLimiter.schedule(doRequest, state, request, options); -} // @ts-expect-error - async function doRequest(state, request, options) { const isWrite = options.method !== "GET" && options.method !== "HEAD"; - const { - pathname - } = new URL(options.url, "http://github.test"); + const { pathname } = new URL(options.url, "http://github.test"); const isSearch = options.method === "GET" && pathname.startsWith("/search/"); const isGraphQL = pathname.startsWith("/graphql"); - const retryCount = ~~options.request.retryCount; - const jobOptions = retryCount > 0 ? { - priority: 0, - weight: 0 - } : {}; - + const retryCount = ~~request.retryCount; + const jobOptions = retryCount > 0 ? { priority: 0, weight: 0 } : {}; if (state.clustering) { - // Remove a job from Redis if it has not completed or failed within 60s - // Examples: Node process terminated, client disconnected, etc. - // @ts-expect-error - jobOptions.expiration = 1000 * 60; - } // Guarantee at least 1000ms between writes - // GraphQL can also trigger writes - - + jobOptions.expiration = 1e3 * 60; + } if (isWrite || isGraphQL) { await state.write.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 3000ms between requests that trigger notifications - - + } if (isWrite && state.triggersNotification(pathname)) { await state.notifications.key(state.id).schedule(jobOptions, noop); - } // Guarantee at least 2000ms between search requests - - + } if (isSearch) { await state.search.key(state.id).schedule(jobOptions, noop); } - const req = state.global.key(state.id).schedule(jobOptions, request, options); - if (isGraphQL) { const res = await req; - - if (res.data.errors != null && // @ts-expect-error - res.data.errors.some(error => error.type === "RATE_LIMITED")) { + if (res.data.errors != null && res.data.errors.some((error) => error.type === "RATE_LIMITED")) { const error = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { response: res, data: res.data @@ -5525,100 +8833,100 @@ async function doRequest(state, request, options) { throw error; } } - return req; } -var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/invitations/{invitation_id}", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"]; +// pkg/dist-src/generated/triggers-notification-paths.js +var triggers_notification_paths_default = [ + "/orgs/{org}/invitations", + "/orgs/{org}/invitations/{invitation_id}", + "/orgs/{org}/teams/{team_slug}/discussions", + "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "/repos/{owner}/{repo}/collaborators/{username}", + "/repos/{owner}/{repo}/commits/{commit_sha}/comments", + "/repos/{owner}/{repo}/issues", + "/repos/{owner}/{repo}/issues/{issue_number}/comments", + "/repos/{owner}/{repo}/pulls", + "/repos/{owner}/{repo}/pulls/{pull_number}/comments", + "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", + "/repos/{owner}/{repo}/pulls/{pull_number}/merge", + "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", + "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "/repos/{owner}/{repo}/releases", + "/teams/{team_id}/discussions", + "/teams/{team_id}/discussions/{discussion_number}/comments" +]; +// pkg/dist-src/route-matcher.js function routeMatcher(paths) { - // EXAMPLE. For the following paths: - - /* [ - "/orgs/{org}/invitations", - "/repos/{owner}/{repo}/collaborators/{username}" - ] */ - const regexes = paths.map(path => path.split("/").map(c => c.startsWith("{") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - - /* [ - '/orgs/(?:.+?)/invitations', - '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' - ] */ - - const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: - - /* - ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ - It may look scary, but paste it into https://www.debuggex.com/ - and it will make a lot more sense! - */ - - return new RegExp(regex, "i"); + const regexes = paths.map( + (path) => path.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") + ); + const regex2 = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})[^/]*$`; + return new RegExp(regex2, "i"); } -const regex = routeMatcher(triggersNotificationPaths); -const triggersNotification = regex.test.bind(regex); -const groups = {}; // @ts-expect-error - -const createGroups = function (Bottleneck, common) { - groups.global = new Bottleneck.Group(_objectSpread2({ +// pkg/dist-src/index.js +var regex = routeMatcher(triggers_notification_paths_default); +var triggersNotification = regex.test.bind(regex); +var groups = {}; +var createGroups = function(Bottleneck, common) { + groups.global = new Bottleneck.Group({ id: "octokit-global", - maxConcurrent: 10 - }, common)); - groups.search = new Bottleneck.Group(_objectSpread2({ + maxConcurrent: 10, + ...common + }); + groups.search = new Bottleneck.Group({ id: "octokit-search", maxConcurrent: 1, - minTime: 2000 - }, common)); - groups.write = new Bottleneck.Group(_objectSpread2({ + minTime: 2e3, + ...common + }); + groups.write = new Bottleneck.Group({ id: "octokit-write", maxConcurrent: 1, - minTime: 1000 - }, common)); - groups.notifications = new Bottleneck.Group(_objectSpread2({ + minTime: 1e3, + ...common + }); + groups.notifications = new Bottleneck.Group({ id: "octokit-notifications", maxConcurrent: 1, - minTime: 3000 - }, common)); + minTime: 3e3, + ...common + }); }; - function throttling(octokit, octokitOptions) { const { enabled = true, - Bottleneck = BottleneckLight, + Bottleneck = import_light.default, id = "no-id", - timeout = 1000 * 60 * 2, + timeout = 1e3 * 60 * 2, // Redis TTL: 2 minutes connection } = octokitOptions.throttle || {}; - if (!enabled) { return {}; } - - const common = { - connection, - timeout - }; - + const common = { connection, timeout }; if (groups.global == null) { createGroups(Bottleneck, common); } - - const state = Object.assign(_objectSpread2({ - clustering: connection != null, - triggersNotification, - minimumSecondaryRateRetryAfter: 5, - retryAfterBaseValue: 1000, - retryLimiter: new Bottleneck(), - id - }, groups), octokitOptions.throttle); - const isUsingDeprecatedOnAbuseLimitHandler = typeof state.onAbuseLimit === "function" && state.onAbuseLimit; - - if (typeof (isUsingDeprecatedOnAbuseLimitHandler ? state.onAbuseLimit : state.onSecondaryRateLimit) !== "function" || typeof state.onRateLimit !== "function") { + const state = Object.assign( + { + clustering: connection != null, + triggersNotification, + fallbackSecondaryRateRetryAfter: 60, + retryAfterBaseValue: 1e3, + retryLimiter: new Bottleneck(), + id, + ...groups + }, + octokitOptions.throttle + ); + if (typeof state.onSecondaryRateLimit !== "function" || typeof state.onRateLimit !== "function") { throw new Error(`octokit/plugin-throttling error: You must pass the onSecondaryRateLimit and onRateLimit error handlers. - See https://github.com/octokit/rest.js#throttling + See https://octokit.github.io/rest.js/#throttling const octokit = new Octokit({ throttle: { @@ -5628,68 +8936,62 @@ function throttling(octokit, octokitOptions) { }) `); } - const events = {}; - const emitter = new Bottleneck.Events(events); // @ts-expect-error - - events.on("secondary-limit", isUsingDeprecatedOnAbuseLimitHandler ? function (...args) { - octokit.log.warn("[@octokit/plugin-throttling] `onAbuseLimit()` is deprecated and will be removed in a future release of `@octokit/plugin-throttling`, please use the `onSecondaryRateLimit` handler instead"); - return state.onAbuseLimit(...args); - } : state.onSecondaryRateLimit); // @ts-expect-error - - events.on("rate-limit", state.onRateLimit); // @ts-expect-error - - events.on("error", e => octokit.log.warn("Error in throttling-plugin limit handler", e)); // @ts-expect-error - - state.retryLimiter.on("failed", async function (error, info) { - const options = info.args[info.args.length - 1]; - const { - pathname - } = new URL(options.url, "http://github.test"); + const emitter = new Bottleneck.Events(events); + events.on("secondary-limit", state.onSecondaryRateLimit); + events.on("rate-limit", state.onRateLimit); + events.on( + "error", + (e) => octokit.log.warn("Error in throttling-plugin limit handler", e) + ); + state.retryLimiter.on("failed", async function(error, info) { + const [state2, request, options] = info.args; + const { pathname } = new URL(options.url, "http://github.test"); const shouldRetryGraphQL = pathname.startsWith("/graphql") && error.status !== 401; - if (!(shouldRetryGraphQL || error.status === 403)) { return; } - - const retryCount = ~~options.request.retryCount; + const retryCount = ~~request.retryCount; + request.retryCount = retryCount; options.request.retryCount = retryCount; - const { - wantRetry, - retryAfter = 0 - } = await async function () { + const { wantRetry, retryAfter = 0 } = await async function() { if (/\bsecondary rate\b/i.test(error.message)) { - // The user has hit the secondary rate limit. (REST and GraphQL) - // https://docs.github.com/en/rest/overview/resources-in-the-rest-api#secondary-rate-limits - // The Retry-After header can sometimes be blank when hitting a secondary rate limit, - // but is always present after 2-3s, so make sure to set `retryAfter` to at least 5s by default. - const retryAfter = Math.max(~~error.response.headers["retry-after"], state.minimumSecondaryRateRetryAfter); - const wantRetry = await emitter.trigger("secondary-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; - } - - if (error.response.headers != null && error.response.headers["x-ratelimit-remaining"] === "0") { - // The user has used all their allowed calls for the current time period (REST and GraphQL) - // https://docs.github.com/en/rest/reference/rate-limit (REST) - // https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit (GraphQL) - const rateLimitReset = new Date(~~error.response.headers["x-ratelimit-reset"] * 1000).getTime(); - const retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); - const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); - return { - wantRetry, - retryAfter - }; + const retryAfter2 = Number(error.response.headers["retry-after"]) || state2.fallbackSecondaryRateRetryAfter; + const wantRetry2 = await emitter.trigger( + "secondary-limit", + retryAfter2, + options, + octokit, + retryCount + ); + return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; + } + if (error.response.headers != null && error.response.headers["x-ratelimit-remaining"] === "0" || (error.response.data?.errors ?? []).some( + (error2) => error2.type === "RATE_LIMITED" + )) { + const rateLimitReset = new Date( + ~~error.response.headers["x-ratelimit-reset"] * 1e3 + ).getTime(); + const retryAfter2 = Math.max( + // Add one second so we retry _after_ the reset time + // https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#exceeding-the-rate-limit + Math.ceil((rateLimitReset - Date.now()) / 1e3) + 1, + 0 + ); + const wantRetry2 = await emitter.trigger( + "rate-limit", + retryAfter2, + options, + octokit, + retryCount + ); + return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; } - return {}; }(); - if (wantRetry) { - options.request.retryCount++; - return retryAfter * state.retryAfterBaseValue; + request.retryCount++; + return retryAfter * state2.retryAfterBaseValue; } }); octokit.hook.wrap("request", wrapRequest.bind(null, state)); @@ -5697,172 +8999,227 @@ function throttling(octokit, octokitOptions) { } throttling.VERSION = VERSION; throttling.triggersNotification = triggersNotification; - -exports.throttling = throttling; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 10537: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 93708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __nccwpck_require__(58932); -var once = _interopDefault(__nccwpck_require__(1223)); - -const logOnceCode = once(deprecation => console.warn(deprecation)); -const logOnceHeaders = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + RequestError: () => RequestError +}); +module.exports = __toCommonJS(dist_src_exports); +var import_deprecation = __nccwpck_require__(14150); +var import_once = __toESM(__nccwpck_require__(55560)); +var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var RequestError = class extends Error { constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - + super(message); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } - this.name = "HttpError"; this.status = statusCode; let headers; - if ("headers" in options && typeof options.headers !== "undefined") { headers = options.headers; } - if ("response" in options) { this.response = options.response; headers = options.response.headers; - } // redact request credentials without mutating original request options - - + } const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + authorization: options.request.headers.authorization.replace( + / .*$/, + " [REDACTED]" + ) }); } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; // deprecations - + requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; Object.defineProperty(this, "code", { get() { - logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + logOnceCode( + new import_deprecation.Deprecation( + "[@octokit/request-error] `error.code` is deprecated, use `error.status`." + ) + ); return statusCode; } - }); Object.defineProperty(this, "headers", { get() { - logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); + logOnceHeaders( + new import_deprecation.Deprecation( + "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`." + ) + ); return headers || {}; } - }); } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 36234: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 66255: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Object.defineProperty(exports, "__esModule", ({ value: true })); +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + request: () => request +}); +module.exports = __toCommonJS(dist_src_exports); +var import_endpoint = __nccwpck_require__(54471); +var import_universal_user_agent = __nccwpck_require__(33843); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } +// pkg/dist-src/version.js +var VERSION = "8.4.0"; -var endpoint = __nccwpck_require__(59440); -var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(63287); -var nodeFetch = _interopDefault(__nccwpck_require__(80467)); -var requestError = __nccwpck_require__(10537); +// pkg/dist-src/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} -const VERSION = "5.6.3"; +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(93708); +// pkg/dist-src/get-buffer-response.js function getBufferResponse(response) { return response.arrayBuffer(); } +// pkg/dist-src/fetch-wrapper.js function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - - if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } - let headers = {}; let status; let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + return fetch(requestOptions.url, { method: requestOptions.method, body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, headers: requestOptions.headers, - redirect: requestOptions.redirect - }, // `requestOptions.request.agent` type is incompatible - // see https://github.com/octokit/types.ts/pull/264 - requestOptions.request)).then(async response => { + signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }).then(async (response) => { url = response.url; status = response.status; - for (const keyAndValue of response.headers) { headers[keyAndValue[0]] = keyAndValue[1]; } - if ("deprecation" in headers) { const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); const deprecationLink = matches && matches.pop(); - log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); } - if (status === 204 || status === 205) { return; - } // GitHub API returns 200 for HEAD requests - - + } if (requestOptions.method === "HEAD") { if (status < 400) { return; } - - throw new requestError.RequestError(response.statusText, status, { + throw new import_request_error.RequestError(response.statusText, status, { response: { url, status, headers, - data: undefined + data: void 0 }, request: requestOptions }); } - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { + throw new import_request_error.RequestError("Not modified", status, { response: { url, status, @@ -5872,10 +9229,9 @@ function fetchWrapper(requestOptions) { request: requestOptions }); } - if (status >= 400) { const data = await getResponseData(response); - const error = new requestError.RequestError(toErrorMessage(data), status, { + const error = new import_request_error.RequestError(toErrorMessage(data), status, { response: { url, status, @@ -5886,270 +9242,579 @@ function fetchWrapper(requestOptions) { }); throw error; } - - return getResponseData(response); - }).then(data => { + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { return { status, url, headers, data }; - }).catch(error => { - if (error instanceof requestError.RequestError) throw error; - throw new requestError.RequestError(error.message, 500, { + }).catch((error) => { + if (error instanceof import_request_error.RequestError) + throw error; + else if (error.name === "AbortError") + throw error; + let message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + throw new import_request_error.RequestError(message, 500, { request: requestOptions }); }); } - async function getResponseData(response) { const contentType = response.headers.get("content-type"); - if (/application\/json/.test(contentType)) { - return response.json(); + return response.json().catch(() => response.text()).catch(() => ""); } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { return response.text(); } - return getBufferResponse(response); } - function toErrorMessage(data) { - if (typeof data === "string") return data; // istanbul ignore else - just in case - + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } if ("message" in data) { if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; } - - return data.message; - } // istanbul ignore next - just in case - - + return `${data.message}${suffix}`; + } return `Unknown error: ${JSON.stringify(data)}`; } +// pkg/dist-src/with-defaults.js function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); + return fetchWrapper(endpoint2.parse(endpointOptions)); } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) }); - return endpointOptions.request.hook(request, endpointOptions); + return endpointOptions.request.hook(request2, endpointOptions); }; - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) }); } -const request = withDefaults(endpoint.endpoint, { +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } }); - -exports.request = request; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 49768: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 75511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + sign: () => sign, + verify: () => verify, + verifyWithFallback: () => verifyWithFallback +}); +module.exports = __toCommonJS(dist_src_exports); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var crypto = __nccwpck_require__(6113); -var buffer = __nccwpck_require__(14300); - -const VERSION = "2.0.0"; +// pkg/dist-src/node/sign.js +var import_node_crypto = __nccwpck_require__(77598); -var Algorithm; +// pkg/dist-src/types.js +var Algorithm = /* @__PURE__ */ ((Algorithm2) => { + Algorithm2["SHA1"] = "sha1"; + Algorithm2["SHA256"] = "sha256"; + return Algorithm2; +})(Algorithm || {}); -(function (Algorithm) { - Algorithm["SHA1"] = "sha1"; - Algorithm["SHA256"] = "sha256"; -})(Algorithm || (Algorithm = {})); +// pkg/dist-src/version.js +var VERSION = "4.1.0"; +// pkg/dist-src/node/sign.js async function sign(options, payload) { - const { - secret, - algorithm - } = typeof options === "object" ? { + const { secret, algorithm } = typeof options === "object" ? { secret: options.secret, algorithm: options.algorithm || Algorithm.SHA256 - } : { - secret: options, - algorithm: Algorithm.SHA256 - }; - + } : { secret: options, algorithm: Algorithm.SHA256 }; if (!secret || !payload) { - throw new TypeError("[@octokit/webhooks-methods] secret & payload required for sign()"); + throw new TypeError( + "[@octokit/webhooks-methods] secret & payload required for sign()" + ); + } + if (typeof payload !== "string") { + throw new TypeError("[@octokit/webhooks-methods] payload must be a string"); } - if (!Object.values(Algorithm).includes(algorithm)) { - throw new TypeError(`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`); + throw new TypeError( + `[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'` + ); } - - return `${algorithm}=${crypto.createHmac(algorithm, secret).update(payload).digest("hex")}`; + return `${algorithm}=${(0, import_node_crypto.createHmac)(algorithm, secret).update(payload).digest("hex")}`; } sign.VERSION = VERSION; -const getAlgorithm = signature => { +// pkg/dist-src/node/verify.js +var import_node_crypto2 = __nccwpck_require__(77598); +var import_node_buffer = __nccwpck_require__(4573); + +// pkg/dist-src/utils.js +var getAlgorithm = (signature) => { return signature.startsWith("sha256=") ? "sha256" : "sha1"; }; +// pkg/dist-src/node/verify.js async function verify(secret, eventPayload, signature) { if (!secret || !eventPayload || !signature) { - throw new TypeError("[@octokit/webhooks-methods] secret, eventPayload & signature required"); + throw new TypeError( + "[@octokit/webhooks-methods] secret, eventPayload & signature required" + ); } - - const signatureBuffer = buffer.Buffer.from(signature); + if (typeof eventPayload !== "string") { + throw new TypeError( + "[@octokit/webhooks-methods] eventPayload must be a string" + ); + } + const signatureBuffer = import_node_buffer.Buffer.from(signature); const algorithm = getAlgorithm(signature); - const verificationBuffer = buffer.Buffer.from(await sign({ - secret, - algorithm - }, eventPayload)); - + const verificationBuffer = import_node_buffer.Buffer.from( + await sign({ secret, algorithm }, eventPayload) + ); if (signatureBuffer.length !== verificationBuffer.length) { return false; - } // constant time comparison to prevent timing attachs - // https://stackoverflow.com/a/31096242/206879 - // https://en.wikipedia.org/wiki/Timing_attack - - - return crypto.timingSafeEqual(signatureBuffer, verificationBuffer); + } + return (0, import_node_crypto2.timingSafeEqual)(signatureBuffer, verificationBuffer); } verify.VERSION = VERSION; -exports.sign = sign; -exports.verify = verify; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 18513: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var AggregateError = _interopDefault(__nccwpck_require__(61231)); -var webhooksMethods = __nccwpck_require__(49768); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); +// pkg/dist-src/index.js +async function verifyWithFallback(secret, payload, signature, additionalSecrets) { + const firstPass = await verify(secret, payload, signature); + if (firstPass) { + return true; + } + if (additionalSecrets !== void 0) { + for (const s of additionalSecrets) { + const v = await verify(s, payload, signature); + if (v) { + return v; + } } - - keys.push.apply(keys, symbols); } - - return keys; + return false; } +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } +/***/ }), - return target; -} +/***/ 5964: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } +"use strict"; - return obj; -} +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + Webhooks: () => Webhooks, + createEventHandler: () => createEventHandler, + createNodeMiddleware: () => createNodeMiddleware, + emitterEventNames: () => emitterEventNames +}); +module.exports = __toCommonJS(dist_src_exports); -const createLogger = logger => _objectSpread2({ - debug: () => {}, - info: () => {}, +// pkg/dist-src/createLogger.js +var createLogger = (logger) => ({ + debug: () => { + }, + info: () => { + }, warn: console.warn.bind(console), - error: console.error.bind(console) -}, logger); + error: console.error.bind(console), + ...logger +}); -// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY -// make edits in scripts/generate-types.ts -const emitterEventNames = ["branch_protection_rule", "branch_protection_rule.created", "branch_protection_rule.deleted", "branch_protection_rule.edited", "check_run", "check_run.completed", "check_run.created", "check_run.requested_action", "check_run.rerequested", "check_suite", "check_suite.completed", "check_suite.requested", "check_suite.rerequested", "code_scanning_alert", "code_scanning_alert.appeared_in_branch", "code_scanning_alert.closed_by_user", "code_scanning_alert.created", "code_scanning_alert.fixed", "code_scanning_alert.reopened", "code_scanning_alert.reopened_by_user", "commit_comment", "commit_comment.created", "create", "delete", "deploy_key", "deploy_key.created", "deploy_key.deleted", "deployment", "deployment.created", "deployment_status", "deployment_status.created", "discussion", "discussion.answered", "discussion.category_changed", "discussion.created", "discussion.deleted", "discussion.edited", "discussion.labeled", "discussion.locked", "discussion.pinned", "discussion.transferred", "discussion.unanswered", "discussion.unlabeled", "discussion.unlocked", "discussion.unpinned", "discussion_comment", "discussion_comment.created", "discussion_comment.deleted", "discussion_comment.edited", "fork", "github_app_authorization", "github_app_authorization.revoked", "gollum", "installation", "installation.created", "installation.deleted", "installation.new_permissions_accepted", "installation.suspend", "installation.unsuspend", "installation_repositories", "installation_repositories.added", "installation_repositories.removed", "issue_comment", "issue_comment.created", "issue_comment.deleted", "issue_comment.edited", "issues", "issues.assigned", "issues.closed", "issues.deleted", "issues.demilestoned", "issues.edited", "issues.labeled", "issues.locked", "issues.milestoned", "issues.opened", "issues.pinned", "issues.reopened", "issues.transferred", "issues.unassigned", "issues.unlabeled", "issues.unlocked", "issues.unpinned", "label", "label.created", "label.deleted", "label.edited", "marketplace_purchase", "marketplace_purchase.cancelled", "marketplace_purchase.changed", "marketplace_purchase.pending_change", "marketplace_purchase.pending_change_cancelled", "marketplace_purchase.purchased", "member", "member.added", "member.edited", "member.removed", "membership", "membership.added", "membership.removed", "meta", "meta.deleted", "milestone", "milestone.closed", "milestone.created", "milestone.deleted", "milestone.edited", "milestone.opened", "org_block", "org_block.blocked", "org_block.unblocked", "organization", "organization.deleted", "organization.member_added", "organization.member_invited", "organization.member_removed", "organization.renamed", "package", "package.published", "package.updated", "page_build", "ping", "project", "project.closed", "project.created", "project.deleted", "project.edited", "project.reopened", "project_card", "project_card.converted", "project_card.created", "project_card.deleted", "project_card.edited", "project_card.moved", "project_column", "project_column.created", "project_column.deleted", "project_column.edited", "project_column.moved", "public", "pull_request", "pull_request.assigned", "pull_request.auto_merge_disabled", "pull_request.auto_merge_enabled", "pull_request.closed", "pull_request.converted_to_draft", "pull_request.edited", "pull_request.labeled", "pull_request.locked", "pull_request.opened", "pull_request.ready_for_review", "pull_request.reopened", "pull_request.review_request_removed", "pull_request.review_requested", "pull_request.synchronize", "pull_request.unassigned", "pull_request.unlabeled", "pull_request.unlocked", "pull_request_review", "pull_request_review.dismissed", "pull_request_review.edited", "pull_request_review.submitted", "pull_request_review_comment", "pull_request_review_comment.created", "pull_request_review_comment.deleted", "pull_request_review_comment.edited", "pull_request_review_thread", "pull_request_review_thread.resolved", "pull_request_review_thread.unresolved", "push", "release", "release.created", "release.deleted", "release.edited", "release.prereleased", "release.published", "release.released", "release.unpublished", "repository", "repository.archived", "repository.created", "repository.deleted", "repository.edited", "repository.privatized", "repository.publicized", "repository.renamed", "repository.transferred", "repository.unarchived", "repository_dispatch", "repository_import", "repository_vulnerability_alert", "repository_vulnerability_alert.create", "repository_vulnerability_alert.dismiss", "repository_vulnerability_alert.reopen", "repository_vulnerability_alert.resolve", "secret_scanning_alert", "secret_scanning_alert.created", "secret_scanning_alert.reopened", "secret_scanning_alert.resolved", "security_advisory", "security_advisory.performed", "security_advisory.published", "security_advisory.updated", "security_advisory.withdrawn", "sponsorship", "sponsorship.cancelled", "sponsorship.created", "sponsorship.edited", "sponsorship.pending_cancellation", "sponsorship.pending_tier_change", "sponsorship.tier_changed", "star", "star.created", "star.deleted", "status", "team", "team.added_to_repository", "team.created", "team.deleted", "team.edited", "team.removed_from_repository", "team_add", "watch", "watch.started", "workflow_dispatch", "workflow_job", "workflow_job.completed", "workflow_job.in_progress", "workflow_job.queued", "workflow_run", "workflow_run.completed", "workflow_run.requested"]; +// pkg/dist-src/generated/webhook-names.js +var emitterEventNames = [ + "branch_protection_configuration", + "branch_protection_configuration.disabled", + "branch_protection_configuration.enabled", + "branch_protection_rule", + "branch_protection_rule.created", + "branch_protection_rule.deleted", + "branch_protection_rule.edited", + "check_run", + "check_run.completed", + "check_run.created", + "check_run.requested_action", + "check_run.rerequested", + "check_suite", + "check_suite.completed", + "check_suite.requested", + "check_suite.rerequested", + "code_scanning_alert", + "code_scanning_alert.appeared_in_branch", + "code_scanning_alert.closed_by_user", + "code_scanning_alert.created", + "code_scanning_alert.fixed", + "code_scanning_alert.reopened", + "code_scanning_alert.reopened_by_user", + "commit_comment", + "commit_comment.created", + "create", + "custom_property", + "custom_property.created", + "custom_property.deleted", + "custom_property_values", + "custom_property_values.updated", + "delete", + "dependabot_alert", + "dependabot_alert.created", + "dependabot_alert.dismissed", + "dependabot_alert.fixed", + "dependabot_alert.reintroduced", + "dependabot_alert.reopened", + "deploy_key", + "deploy_key.created", + "deploy_key.deleted", + "deployment", + "deployment.created", + "deployment_protection_rule", + "deployment_protection_rule.requested", + "deployment_review", + "deployment_review.approved", + "deployment_review.rejected", + "deployment_review.requested", + "deployment_status", + "deployment_status.created", + "discussion", + "discussion.answered", + "discussion.category_changed", + "discussion.created", + "discussion.deleted", + "discussion.edited", + "discussion.labeled", + "discussion.locked", + "discussion.pinned", + "discussion.transferred", + "discussion.unanswered", + "discussion.unlabeled", + "discussion.unlocked", + "discussion.unpinned", + "discussion_comment", + "discussion_comment.created", + "discussion_comment.deleted", + "discussion_comment.edited", + "fork", + "github_app_authorization", + "github_app_authorization.revoked", + "gollum", + "installation", + "installation.created", + "installation.deleted", + "installation.new_permissions_accepted", + "installation.suspend", + "installation.unsuspend", + "installation_repositories", + "installation_repositories.added", + "installation_repositories.removed", + "installation_target", + "installation_target.renamed", + "issue_comment", + "issue_comment.created", + "issue_comment.deleted", + "issue_comment.edited", + "issues", + "issues.assigned", + "issues.closed", + "issues.deleted", + "issues.demilestoned", + "issues.edited", + "issues.labeled", + "issues.locked", + "issues.milestoned", + "issues.opened", + "issues.pinned", + "issues.reopened", + "issues.transferred", + "issues.unassigned", + "issues.unlabeled", + "issues.unlocked", + "issues.unpinned", + "label", + "label.created", + "label.deleted", + "label.edited", + "marketplace_purchase", + "marketplace_purchase.cancelled", + "marketplace_purchase.changed", + "marketplace_purchase.pending_change", + "marketplace_purchase.pending_change_cancelled", + "marketplace_purchase.purchased", + "member", + "member.added", + "member.edited", + "member.removed", + "membership", + "membership.added", + "membership.removed", + "merge_group", + "merge_group.checks_requested", + "merge_group.destroyed", + "meta", + "meta.deleted", + "milestone", + "milestone.closed", + "milestone.created", + "milestone.deleted", + "milestone.edited", + "milestone.opened", + "org_block", + "org_block.blocked", + "org_block.unblocked", + "organization", + "organization.deleted", + "organization.member_added", + "organization.member_invited", + "organization.member_removed", + "organization.renamed", + "package", + "package.published", + "package.updated", + "page_build", + "ping", + "project", + "project.closed", + "project.created", + "project.deleted", + "project.edited", + "project.reopened", + "project_card", + "project_card.converted", + "project_card.created", + "project_card.deleted", + "project_card.edited", + "project_card.moved", + "project_column", + "project_column.created", + "project_column.deleted", + "project_column.edited", + "project_column.moved", + "projects_v2_item", + "projects_v2_item.archived", + "projects_v2_item.converted", + "projects_v2_item.created", + "projects_v2_item.deleted", + "projects_v2_item.edited", + "projects_v2_item.reordered", + "projects_v2_item.restored", + "public", + "pull_request", + "pull_request.assigned", + "pull_request.auto_merge_disabled", + "pull_request.auto_merge_enabled", + "pull_request.closed", + "pull_request.converted_to_draft", + "pull_request.demilestoned", + "pull_request.dequeued", + "pull_request.edited", + "pull_request.enqueued", + "pull_request.labeled", + "pull_request.locked", + "pull_request.milestoned", + "pull_request.opened", + "pull_request.ready_for_review", + "pull_request.reopened", + "pull_request.review_request_removed", + "pull_request.review_requested", + "pull_request.synchronize", + "pull_request.unassigned", + "pull_request.unlabeled", + "pull_request.unlocked", + "pull_request_review", + "pull_request_review.dismissed", + "pull_request_review.edited", + "pull_request_review.submitted", + "pull_request_review_comment", + "pull_request_review_comment.created", + "pull_request_review_comment.deleted", + "pull_request_review_comment.edited", + "pull_request_review_thread", + "pull_request_review_thread.resolved", + "pull_request_review_thread.unresolved", + "push", + "registry_package", + "registry_package.published", + "registry_package.updated", + "release", + "release.created", + "release.deleted", + "release.edited", + "release.prereleased", + "release.published", + "release.released", + "release.unpublished", + "repository", + "repository.archived", + "repository.created", + "repository.deleted", + "repository.edited", + "repository.privatized", + "repository.publicized", + "repository.renamed", + "repository.transferred", + "repository.unarchived", + "repository_dispatch", + "repository_import", + "repository_vulnerability_alert", + "repository_vulnerability_alert.create", + "repository_vulnerability_alert.dismiss", + "repository_vulnerability_alert.reopen", + "repository_vulnerability_alert.resolve", + "secret_scanning_alert", + "secret_scanning_alert.created", + "secret_scanning_alert.reopened", + "secret_scanning_alert.resolved", + "secret_scanning_alert.revoked", + "secret_scanning_alert_location", + "secret_scanning_alert_location.created", + "security_advisory", + "security_advisory.performed", + "security_advisory.published", + "security_advisory.updated", + "security_advisory.withdrawn", + "sponsorship", + "sponsorship.cancelled", + "sponsorship.created", + "sponsorship.edited", + "sponsorship.pending_cancellation", + "sponsorship.pending_tier_change", + "sponsorship.tier_changed", + "star", + "star.created", + "star.deleted", + "status", + "team", + "team.added_to_repository", + "team.created", + "team.deleted", + "team.edited", + "team.removed_from_repository", + "team_add", + "watch", + "watch.started", + "workflow_dispatch", + "workflow_job", + "workflow_job.completed", + "workflow_job.in_progress", + "workflow_job.queued", + "workflow_job.waiting", + "workflow_run", + "workflow_run.completed", + "workflow_run.in_progress", + "workflow_run.requested" +]; +// pkg/dist-src/event-handler/on.js function handleEventHandlers(state, webhookName, handler) { if (!state.hooks[webhookName]) { state.hooks[webhookName] = []; } - state.hooks[webhookName].push(handler); } - function receiverOn(state, webhookNameOrNames, handler) { if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)); + webhookNameOrNames.forEach( + (webhookName) => receiverOn(state, webhookName, handler) + ); return; } - if (["*", "error"].includes(webhookNameOrNames)) { const webhookName = webhookNameOrNames === "*" ? "any" : webhookNameOrNames; const message = `Using the "${webhookNameOrNames}" event with the regular Webhooks.on() function is not supported. Please use the Webhooks.on${webhookName.charAt(0).toUpperCase() + webhookName.slice(1)}() method instead`; throw new Error(message); } - if (!emitterEventNames.includes(webhookNameOrNames)) { - state.log.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`); + state.log.warn( + `"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)` + ); } - handleEventHandlers(state, webhookNameOrNames, handler); } function receiverOnAny(state, handler) { @@ -6159,108 +9824,93 @@ function receiverOnError(state, handler) { handleEventHandlers(state, "error", handler); } -// Errors thrown or rejected Promises in "error" event handlers are not handled -// as they are in the webhook event handlers. If errors occur, we log a -// "Fatal: Error occurred" message to stdout +// pkg/dist-src/event-handler/receive.js +var import_aggregate_error = __toESM(__nccwpck_require__(77784)); + +// pkg/dist-src/event-handler/wrap-error-handler.js function wrapErrorHandler(handler, error) { let returnValue; - try { returnValue = handler(error); - } catch (error) { + } catch (error2) { console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); + console.log(error2); } - if (returnValue && returnValue.catch) { - returnValue.catch(error => { + returnValue.catch((error2) => { console.log('FATAL: Error occurred in "error" event handler'); - console.log(error); + console.log(error2); }); } } -// @ts-ignore to address #245 - +// pkg/dist-src/event-handler/receive.js function getHooks(state, eventPayloadAction, eventName) { const hooks = [state.hooks[eventName], state.hooks["*"]]; - if (eventPayloadAction) { hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]); } - return [].concat(...hooks.filter(Boolean)); -} // main handler function - - +} function receiverHandle(state, event) { const errorHandlers = state.hooks.error || []; - if (event instanceof Error) { - const error = Object.assign(new AggregateError([event]), { + const error = Object.assign(new import_aggregate_error.default([event]), { event, errors: [event] }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + errorHandlers.forEach((handler) => wrapErrorHandler(handler, error)); return Promise.reject(error); } - if (!event || !event.name) { - throw new AggregateError(["Event name not passed"]); + throw new import_aggregate_error.default(["Event name not passed"]); } - if (!event.payload) { - throw new AggregateError(["Event payload not passed"]); - } // flatten arrays of event listeners and remove undefined values - - - const hooks = getHooks(state, "action" in event.payload ? event.payload.action : null, event.name); - + throw new import_aggregate_error.default(["Event payload not passed"]); + } + const hooks = getHooks( + state, + "action" in event.payload ? event.payload.action : null, + event.name + ); if (hooks.length === 0) { return Promise.resolve(); } - const errors = []; - const promises = hooks.map(handler => { + const promises = hooks.map((handler) => { let promise = Promise.resolve(event); - if (state.transform) { promise = promise.then(state.transform); } - - return promise.then(event => { - return handler(event); - }).catch(error => errors.push(Object.assign(error, { - event - }))); + return promise.then((event2) => { + return handler(event2); + }).catch((error) => errors.push(Object.assign(error, { event }))); }); return Promise.all(promises).then(() => { if (errors.length === 0) { return; } - - const error = new AggregateError(errors); + const error = new import_aggregate_error.default(errors); Object.assign(error, { event, errors }); - errorHandlers.forEach(handler => wrapErrorHandler(handler, error)); + errorHandlers.forEach((handler) => wrapErrorHandler(handler, error)); throw error; }); } +// pkg/dist-src/event-handler/remove-listener.js function removeListener(state, webhookNameOrNames, handler) { if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => removeListener(state, webhookName, handler)); + webhookNameOrNames.forEach( + (webhookName) => removeListener(state, webhookName, handler) + ); return; } - if (!state.hooks[webhookNameOrNames]) { return; - } // remove last hook that has been added, that way - // it behaves the same as removeListener - - + } for (let i = state.hooks[webhookNameOrNames].length - 1; i >= 0; i--) { if (state.hooks[webhookNameOrNames][i] === handler) { state.hooks[webhookNameOrNames].splice(i, 1); @@ -6269,16 +9919,15 @@ function removeListener(state, webhookNameOrNames, handler) { } } +// pkg/dist-src/event-handler/index.js function createEventHandler(options) { const state = { hooks: {}, log: createLogger(options && options.log) }; - if (options && options.transform) { state.transform = options.transform; } - return { on: receiverOn.bind(null, state), onAny: receiverOnAny.bind(null, state), @@ -6288,178 +9937,203 @@ function createEventHandler(options) { }; } -/** - * GitHub sends its JSON with an indentation of 2 spaces and a line break at the end - */ -function toNormalizedJsonString(payload) { - const payloadString = JSON.stringify(payload); - return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, s => { - return s.substr(0, 3) + s.substr(3).toUpperCase(); - }); -} - -async function sign(secret, payload) { - return webhooksMethods.sign(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload)); -} - -async function verify(secret, payload, signature) { - return webhooksMethods.verify(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature); -} +// pkg/dist-src/index.js +var import_webhooks_methods2 = __nccwpck_require__(75511); +// pkg/dist-src/verify-and-receive.js +var import_aggregate_error2 = __toESM(__nccwpck_require__(77784)); +var import_webhooks_methods = __nccwpck_require__(75511); async function verifyAndReceive(state, event) { - // verify will validate that the secret is not undefined - const matchesSignature = await webhooksMethods.verify(state.secret, typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload, event.signature); - + const matchesSignature = await (0, import_webhooks_methods.verify)( + state.secret, + event.payload, + event.signature + ).catch(() => false); if (!matchesSignature) { - const error = new Error("[@octokit/webhooks] signature does not match event payload and secret"); - return state.eventHandler.receive(Object.assign(error, { - event, - status: 400 - })); + const error = new Error( + "[@octokit/webhooks] signature does not match event payload and secret" + ); + return state.eventHandler.receive( + Object.assign(error, { event, status: 400 }) + ); + } + let payload; + try { + payload = JSON.parse(event.payload); + } catch (error) { + error.message = "Invalid JSON"; + error.status = 400; + throw new import_aggregate_error2.default([error]); } - return state.eventHandler.receive({ id: event.id, name: event.name, - payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload + payload }); } -const WEBHOOK_HEADERS = ["x-github-event", "x-hub-signature-256", "x-github-delivery"]; // https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers - +// pkg/dist-src/middleware/node/get-missing-headers.js +var WEBHOOK_HEADERS = [ + "x-github-event", + "x-hub-signature-256", + "x-github-delivery" +]; function getMissingHeaders(request) { - return WEBHOOK_HEADERS.filter(header => !(header in request.headers)); + return WEBHOOK_HEADERS.filter((header) => !(header in request.headers)); } -// @ts-ignore to address #245 +// pkg/dist-src/middleware/node/get-payload.js +var import_aggregate_error3 = __toESM(__nccwpck_require__(77784)); function getPayload(request) { - // If request.body already exists we can stop here - // See https://github.com/octokit/webhooks.js/pull/23 - if (request.body) return Promise.resolve(request.body); + if ("body" in request) { + if (typeof request.body === "object" && "rawBody" in request && request.rawBody instanceof Buffer) { + return Promise.resolve(request.rawBody.toString("utf8")); + } else { + return Promise.resolve(request.body); + } + } return new Promise((resolve, reject) => { - let data = ""; - request.setEncoding("utf8"); // istanbul ignore next + let data = []; + request.on("error", (error) => reject(new import_aggregate_error3.default([error]))); + request.on("data", (chunk) => data.push(chunk)); + request.on( + "end", + () => ( + // setImmediate improves the throughput by reducing the pressure from + // the event loop + setImmediate( + resolve, + data.length === 1 ? data[0].toString("utf8") : Buffer.concat(data).toString("utf8") + ) + ) + ); + }); +} - request.on("error", error => reject(new AggregateError([error]))); - request.on("data", chunk => data += chunk); - request.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (error) { - error.message = "Invalid JSON"; - error.status = 400; - reject(new AggregateError([error])); - } - }); +// pkg/dist-src/middleware/node/on-unhandled-request-default.js +function onUnhandledRequestDefault(request, response) { + response.writeHead(404, { + "content-type": "application/json" }); + response.end( + JSON.stringify({ + error: `Unknown route: ${request.method} ${request.url}` + }) + ); } +// pkg/dist-src/middleware/node/middleware.js async function middleware(webhooks, options, request, response, next) { let pathname; - try { pathname = new URL(request.url, "http://localhost").pathname; } catch (error) { response.writeHead(422, { "content-type": "application/json" }); - response.end(JSON.stringify({ - error: `Request URL could not be parsed: ${request.url}` - })); - return; + response.end( + JSON.stringify({ + error: `Request URL could not be parsed: ${request.url}` + }) + ); + return true; } - - const isUnknownRoute = request.method !== "POST" || pathname !== options.path; - const isExpressMiddleware = typeof next === "function"; - - if (isUnknownRoute) { - if (isExpressMiddleware) { - return next(); - } else { - return options.onUnhandledRequest(request, response); - } + if (pathname !== options.path) { + next?.(); + return false; + } else if (request.method !== "POST") { + onUnhandledRequestDefault(request, response); + return true; + } + if (!request.headers["content-type"] || !request.headers["content-type"].startsWith("application/json")) { + response.writeHead(415, { + "content-type": "application/json", + accept: "application/json" + }); + response.end( + JSON.stringify({ + error: `Unsupported "Content-Type" header value. Must be "application/json"` + }) + ); + return true; } - const missingHeaders = getMissingHeaders(request).join(", "); - if (missingHeaders) { response.writeHead(400, { "content-type": "application/json" }); - response.end(JSON.stringify({ - error: `Required headers missing: ${missingHeaders}` - })); - return; + response.end( + JSON.stringify({ + error: `Required headers missing: ${missingHeaders}` + }) + ); + return true; } - const eventName = request.headers["x-github-event"]; const signatureSHA256 = request.headers["x-hub-signature-256"]; const id = request.headers["x-github-delivery"]; - options.log.debug(`${eventName} event received (id: ${id})`); // GitHub will abort the request if it does not receive a response within 10s - // See https://github.com/octokit/webhooks.js/issues/185 - + options.log.debug(`${eventName} event received (id: ${id})`); let didTimeout = false; const timeout = setTimeout(() => { didTimeout = true; response.statusCode = 202; response.end("still processing\n"); - }, 9000).unref(); - + }, 9e3).unref(); try { const payload = await getPayload(request); await webhooks.verifyAndReceive({ - id: id, + id, name: eventName, - payload: payload, + payload, signature: signatureSHA256 }); clearTimeout(timeout); - if (didTimeout) return; + if (didTimeout) + return true; response.end("ok\n"); + return true; } catch (error) { clearTimeout(timeout); - if (didTimeout) return; - const statusCode = Array.from(error)[0].status; - response.statusCode = typeof statusCode !== "undefined" ? statusCode : 500; - response.end(String(error)); + if (didTimeout) + return true; + const err = Array.from(error)[0]; + const errorMessage = err.message ? `${err.name}: ${err.message}` : "Error: An Unspecified error occurred"; + response.statusCode = typeof err.status !== "undefined" ? err.status : 500; + options.log.error(error); + response.end( + JSON.stringify({ + error: errorMessage + }) + ); + return true; } } -function onUnhandledRequestDefault(request, response) { - response.writeHead(404, { - "content-type": "application/json" - }); - response.end(JSON.stringify({ - error: `Unknown route: ${request.method} ${request.url}` - })); -} - +// pkg/dist-src/middleware/node/index.js function createNodeMiddleware(webhooks, { path = "/api/github/webhooks", - onUnhandledRequest = onUnhandledRequestDefault, log = createLogger() } = {}) { return middleware.bind(null, webhooks, { path, - onUnhandledRequest, log }); } -class Webhooks { +// pkg/dist-src/index.js +var Webhooks = class { constructor(options) { if (!options || !options.secret) { throw new Error("[@octokit/webhooks] options.secret required"); } - const state = { eventHandler: createEventHandler(options), secret: options.secret, hooks: {}, log: createLogger(options.log) }; - this.sign = sign.bind(null, options.secret); - this.verify = verify.bind(null, options.secret); + this.sign = import_webhooks_methods2.sign.bind(null, options.secret); + this.verify = import_webhooks_methods2.verify.bind(null, options.secret); this.on = state.eventHandler.on; this.onAny = state.eventHandler.onAny; this.onError = state.eventHandler.onError; @@ -6467,300 +10141,807 @@ class Webhooks { this.receive = state.eventHandler.receive; this.verifyAndReceive = verifyAndReceive.bind(null, state); } - -} - -exports.Webhooks = Webhooks; -exports.createEventHandler = createEventHandler; -exports.createNodeMiddleware = createNodeMiddleware; -exports.emitterEventNames = emitterEventNames; -//# sourceMappingURL=index.js.map +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 93159: +/***/ 40885: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const ProbotExports = __nccwpck_require__(58930); -const pino = __nccwpck_require__(79608); +"use strict"; -const { transport } = __nccwpck_require__(96645); -module.exports = { ...ProbotExports, run }; +const { version } = __nccwpck_require__(34717) +const { EventEmitter } = __nccwpck_require__(24434) +const { Worker } = __nccwpck_require__(28167) +const { join } = __nccwpck_require__(16928) +const { pathToFileURL } = __nccwpck_require__(87016) +const { wait } = __nccwpck_require__(57568) +const { + WRITE_INDEX, + READ_INDEX +} = __nccwpck_require__(41157) +const buffer = __nccwpck_require__(20181) +const assert = __nccwpck_require__(42613) -async function run(app) { - const log = pino({}, transport); +const kImpl = Symbol('kImpl') - const githubToken = - process.env.GITHUB_TOKEN || - process.env.INPUT_GITHUB_TOKEN || - process.env.INPUT_TOKEN; +// V8 limit for string size +const MAX_STRING = buffer.constants.MAX_STRING_LENGTH - if (!githubToken) { - log.error( - "[probot/adapter-github-actions] a token must be passed as `env.GITHUB_TOKEN` or `with.GITHUB_TOKEN` or `with.token`, see https://github.com/probot/adapter-github-actions#usage" - ); - return; +class FakeWeakRef { + constructor (value) { + this._value = value } - const envVariablesMissing = [ - "GITHUB_RUN_ID", - "GITHUB_EVENT_NAME", - "GITHUB_EVENT_PATH", - ].filter((name) => !process.env[name]); - - if (envVariablesMissing.length) { - log.error( - `[probot/adapter-github-actions] GitHub Action default environment variables missing: ${envVariablesMissing.join( - ", " - )}. See https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables` - ); - return; + deref () { + return this._value } - - const probot = ProbotExports.createProbot({ - overrides: { - githubToken, - log, - }, - }); - - await probot.load(app); - - return probot - .receive({ - id: process.env.GITHUB_RUN_ID, - name: process.env.GITHUB_EVENT_NAME, - payload: require(process.env.GITHUB_EVENT_PATH), - }) - .catch((error) => { - probot.log.error(error); - }); } +class FakeFinalizationRegistry { + register () {} -/***/ }), + unregister () {} +} -/***/ 96645: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Currently using FinalizationRegistry with code coverage breaks the world +// Ref: https://github.com/nodejs/node/issues/49344 +const FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry +const WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef -const { inspect } = __nccwpck_require__(73837); +const registry = new FinalizationRegistry((worker) => { + if (worker.exited) { + return + } + worker.terminate() +}) -const through = __nccwpck_require__(18180); -const core = __nccwpck_require__(42186); -const pino = __nccwpck_require__(79608); +function createWorker (stream, opts) { + const { filename, workerData } = opts + + const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {} + const toExecute = bundlerOverrides['thread-stream-worker'] || __nccwpck_require__.ab + "worker1.js" + + const worker = new Worker(toExecute, { + ...opts.workerOpts, + trackUnmanagedFds: false, + workerData: { + filename: filename.indexOf('file://') === 0 + ? filename + : pathToFileURL(filename).href, + dataBuf: stream[kImpl].dataBuf, + stateBuf: stream[kImpl].stateBuf, + workerData: { + $context: { + threadStreamVersion: version + }, + ...workerData + } + } + }) -const LEVEL_TO_ACTIONS_CORE_LOG_METHOD = { - trace: "debug", - debug: "debug", - info: "info", - warn: "warning", - error: "error", - fatal: "error", -}; + // We keep a strong reference for now, + // we need to start writing first + worker.stream = new FakeWeakRef(stream) -const transport = through.obj(function (chunk, enc, cb) { - const { level, hostname, pid, msg, time, ...meta } = JSON.parse(chunk); - const levelLabel = pino.levels.labels[level] || level; - const logMethodName = LEVEL_TO_ACTIONS_CORE_LOG_METHOD[levelLabel]; + worker.on('message', onWorkerMessage) + worker.on('exit', onWorkerExit) + registry.register(stream, worker) - const output = [ - msg, - Object.keys(meta).length ? inspect(meta, { depth: Infinity }) : "", - ] - .join("\n") - .trim(); + return worker +} - if (logMethodName in core) { - core[logMethodName](output); - } else { - core.error(`"${level}" is not a known log level - ${output}`); +function drain (stream) { + assert(!stream[kImpl].sync) + if (stream[kImpl].needDrain) { + stream[kImpl].needDrain = false + stream.emit('drain') } +} - cb(); -}); - -module.exports = { transport }; - +function nextFlush (stream) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX) + let leftover = stream[kImpl].data.length - writeIndex -/***/ }), + if (leftover > 0) { + if (stream[kImpl].buf.length === 0) { + stream[kImpl].flushing = false -/***/ 97743: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (stream[kImpl].ending) { + end(stream) + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream) + } -"use strict"; + return + } + let toWrite = stream[kImpl].buf.slice(0, leftover) + let toWriteBytes = Buffer.byteLength(toWrite) + if (toWriteBytes <= leftover) { + stream[kImpl].buf = stream[kImpl].buf.slice(leftover) + // process._rawDebug('writing ' + toWrite.length) + write(stream, toWrite, nextFlush.bind(null, stream)) + } else { + // multi-byte utf-8 + stream.flush(() => { + // err is already handled in flush() + if (stream.destroyed) { + return + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + Atomics.store(stream[kImpl].state, READ_INDEX, 0) + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0) -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + // Find a toWrite length that fits the buffer + // it must exists as the buffer is at least 4 bytes length + // and the max utf-8 length for a char is 4 bytes. + while (toWriteBytes > stream[kImpl].data.length) { + leftover = leftover / 2 + toWrite = stream[kImpl].buf.slice(0, leftover) + toWriteBytes = Buffer.byteLength(toWrite) + } + stream[kImpl].buf = stream[kImpl].buf.slice(leftover) + write(stream, toWrite, nextFlush.bind(null, stream)) + }) + } + } else if (leftover === 0) { + if (writeIndex === 0 && stream[kImpl].buf.length === 0) { + // we had a flushSync in the meanwhile + return + } + stream.flush(() => { + Atomics.store(stream[kImpl].state, READ_INDEX, 0) + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0) + nextFlush(stream) + }) + } else { + // This should never happen + destroy(stream, new Error('overwritten')) + } +} -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -var isBase64 = _interopDefault(__nccwpck_require__(31310)); +function onWorkerMessage (msg) { + const stream = this.stream.deref() + if (stream === undefined) { + this.exited = true + // Terminate the worker. + this.terminate() + return + } -const VERSION = "0.0.0-development"; + switch (msg.code) { + case 'READY': + // Replace the FakeWeakRef with a + // proper one. + this.stream = new WeakRef(stream) -const begin = "-----BEGIN RSA PRIVATE KEY-----"; -const end = "-----END RSA PRIVATE KEY-----"; -function getPrivateKey(options = {}) { - const env = options.env || process.env; - const cwd = options.cwd || process.cwd(); + stream.flush(() => { + stream[kImpl].ready = true + stream.emit('ready') + }) + break + case 'ERROR': + destroy(stream, msg.err) + break + case 'EVENT': + if (Array.isArray(msg.args)) { + stream.emit(msg.name, ...msg.args) + } else { + stream.emit(msg.name, msg.args) + } + break + case 'WARNING': + process.emitWarning(msg.err) + break + default: + destroy(stream, new Error('this should not happen: ' + msg.code)) + } +} - if (options.filepath) { - return fs.readFileSync(path.resolve(cwd, options.filepath), "utf-8"); +function onWorkerExit (code) { + const stream = this.stream.deref() + if (stream === undefined) { + // Nothing to do, the worker already exit + return + } + registry.unregister(stream) + stream.worker.exited = true + stream.worker.off('exit', onWorkerExit) + destroy(stream, code !== 0 ? new Error('the worker thread exited') : null) +} + +class ThreadStream extends EventEmitter { + constructor (opts = {}) { + super() + + if (opts.bufferSize < 4) { + throw new Error('bufferSize must at least fit a 4-byte utf-8 char') + } + + this[kImpl] = {} + this[kImpl].stateBuf = new SharedArrayBuffer(128) + this[kImpl].state = new Int32Array(this[kImpl].stateBuf) + this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024) + this[kImpl].data = Buffer.from(this[kImpl].dataBuf) + this[kImpl].sync = opts.sync || false + this[kImpl].ending = false + this[kImpl].ended = false + this[kImpl].needDrain = false + this[kImpl].destroyed = false + this[kImpl].flushing = false + this[kImpl].ready = false + this[kImpl].finished = false + this[kImpl].errored = null + this[kImpl].closed = false + this[kImpl].buf = '' + + // TODO (fix): Make private? + this.worker = createWorker(this, opts) // TODO (fix): make private + this.on('message', (message, transferList) => { + this.worker.postMessage(message, transferList) + }) } - if (env.PRIVATE_KEY) { - let privateKey = env.PRIVATE_KEY; + write (data) { + if (this[kImpl].destroyed) { + error(this, new Error('the worker has exited')) + return false + } - if (isBase64(privateKey)) { - // Decode base64-encoded certificate - privateKey = Buffer.from(privateKey, "base64").toString(); + if (this[kImpl].ending) { + error(this, new Error('the worker is ending')) + return false } - if (privateKey.includes(begin) && privateKey.includes(end)) { - // newlines are escaped - if (privateKey.indexOf("\\n") !== -1) { - privateKey = privateKey.replace(/\\n/g, "\n"); - } // newlines are missing + if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) { + try { + writeSync(this) + this[kImpl].flushing = true + } catch (err) { + destroy(this, err) + return false + } + } + this[kImpl].buf += data - if (privateKey.indexOf("\n") === -1) { - privateKey = addNewlines(privateKey); + if (this[kImpl].sync) { + try { + writeSync(this) + return true + } catch (err) { + destroy(this, err) + return false } + } - return privateKey; + if (!this[kImpl].flushing) { + this[kImpl].flushing = true + setImmediate(nextFlush, this) } - throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`); + this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0 + return !this[kImpl].needDrain } - if (env.PRIVATE_KEY_PATH) { - const filepath = path.resolve(cwd, env.PRIVATE_KEY_PATH); + end () { + if (this[kImpl].destroyed) { + return + } - if (fs.existsSync(filepath)) { - return fs.readFileSync(filepath, "utf-8"); - } else { - throw new Error(`[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.`); + this[kImpl].ending = true + end(this) + } + + flush (cb) { + if (this[kImpl].destroyed) { + if (typeof cb === 'function') { + process.nextTick(cb, new Error('the worker has exited')) + } + return + } + + // TODO write all .buf + const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX) + // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`) + wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => { + if (err) { + destroy(this, err) + process.nextTick(cb, err) + return + } + if (res === 'not-equal') { + // TODO handle deadlock + this.flush(cb) + return + } + process.nextTick(cb) + }) + } + + flushSync () { + if (this[kImpl].destroyed) { + return } + + writeSync(this) + flushSync(this) } - const pemFiles = fs.readdirSync(cwd).filter(path => path.endsWith(".pem")); + unref () { + this.worker.unref() + } - if (pemFiles.length > 1) { - const paths = pemFiles.join(", "); - throw new Error(`[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH`); - } else if (pemFiles[0]) { - return getPrivateKey({ - filepath: pemFiles[0], - cwd - }); + ref () { + this.worker.ref() } - return null; + get ready () { + return this[kImpl].ready + } + + get destroyed () { + return this[kImpl].destroyed + } + + get closed () { + return this[kImpl].closed + } + + get writable () { + return !this[kImpl].destroyed && !this[kImpl].ending + } + + get writableEnded () { + return this[kImpl].ending + } + + get writableFinished () { + return this[kImpl].finished + } + + get writableNeedDrain () { + return this[kImpl].needDrain + } + + get writableObjectMode () { + return false + } + + get writableErrored () { + return this[kImpl].errored + } } -function addNewlines(privateKey) { - const middleLength = privateKey.length - begin.length - end.length - 2; - const middle = privateKey.substr(begin.length + 1, middleLength); - return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end}`; +function error (stream, err) { + setImmediate(() => { + stream.emit('error', err) + }) } -getPrivateKey.VERSION = VERSION; +function destroy (stream, err) { + if (stream[kImpl].destroyed) { + return + } + stream[kImpl].destroyed = true -exports.getPrivateKey = getPrivateKey; -//# sourceMappingURL=index.js.map + if (err) { + stream[kImpl].errored = err + error(stream, err) + } + if (!stream.worker.exited) { + stream.worker.terminate() + .catch(() => {}) + .then(() => { + stream[kImpl].closed = true + stream.emit('close') + }) + } else { + setImmediate(() => { + stream[kImpl].closed = true + stream.emit('close') + }) + } +} -/***/ }), +function write (stream, data, cb) { + // data is smaller than the shared buffer length + const current = Atomics.load(stream[kImpl].state, WRITE_INDEX) + const length = Buffer.byteLength(data) + stream[kImpl].data.write(data, current) + Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length) + Atomics.notify(stream[kImpl].state, WRITE_INDEX) + cb() + return true +} -/***/ 59326: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function end (stream) { + if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) { + return + } + stream[kImpl].ended = true -"use strict"; + try { + stream.flushSync() + let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX) -Object.defineProperty(exports, "__esModule", ({ value: true })); + // process._rawDebug('writing index') + Atomics.store(stream[kImpl].state, WRITE_INDEX, -1) + // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`) + Atomics.notify(stream[kImpl].state, WRITE_INDEX) -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + // Wait for the process to complete + let spins = 0 + while (readIndex !== -1) { + // process._rawDebug(`read = ${read}`) + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000) + readIndex = Atomics.load(stream[kImpl].state, READ_INDEX) -var yaml = _interopDefault(__nccwpck_require__(80557)); + if (readIndex === -2) { + destroy(stream, new Error('end() failed')) + return + } -const VERSION = "1.1.5"; + if (++spins === 10) { + destroy(stream, new Error('end() took too long (10s)')) + return + } + } -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; + process.nextTick(() => { + stream[kImpl].finished = true + stream.emit('finish') + }) + } catch (err) { + destroy(stream, err) } + // process._rawDebug('end finished...') +} - return obj; +function writeSync (stream) { + const cb = () => { + if (stream[kImpl].ending) { + end(stream) + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream) + } + } + stream[kImpl].flushing = false + + while (stream[kImpl].buf.length !== 0) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX) + let leftover = stream[kImpl].data.length - writeIndex + if (leftover === 0) { + flushSync(stream) + Atomics.store(stream[kImpl].state, READ_INDEX, 0) + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0) + continue + } else if (leftover < 0) { + // stream should never happen + throw new Error('overwritten') + } + + let toWrite = stream[kImpl].buf.slice(0, leftover) + let toWriteBytes = Buffer.byteLength(toWrite) + if (toWriteBytes <= leftover) { + stream[kImpl].buf = stream[kImpl].buf.slice(leftover) + // process._rawDebug('writing ' + toWrite.length) + write(stream, toWrite, cb) + } else { + // multi-byte utf-8 + flushSync(stream) + Atomics.store(stream[kImpl].state, READ_INDEX, 0) + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0) + + // Find a toWrite length that fits the buffer + // it must exists as the buffer is at least 4 bytes length + // and the max utf-8 length for a char is 4 bytes. + while (toWriteBytes > stream[kImpl].buf.length) { + leftover = leftover / 2 + toWrite = stream[kImpl].buf.slice(0, leftover) + toWriteBytes = Buffer.byteLength(toWrite) + } + stream[kImpl].buf = stream[kImpl].buf.slice(leftover) + write(stream, toWrite, cb) + } + } } -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +function flushSync (stream) { + if (stream[kImpl].flushing) { + throw new Error('unable to flush while flushing') + } - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); + // process._rawDebug('flushSync started') + + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX) + + let spins = 0 + + // TODO handle deadlock + while (true) { + const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX) + + if (readIndex === -2) { + throw Error('_flushSync failed') + } + + // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`) + if (readIndex !== writeIndex) { + // TODO stream timeouts for some reason. + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000) + } else { + break + } + + if (++spins === 10) { + throw new Error('_flushSync took too long (10s)') + } } + // process._rawDebug('flushSync finished') +} - return keys; +module.exports = ThreadStream + + +/***/ }), + +/***/ 41157: +/***/ ((module) => { + +"use strict"; + + +const WRITE_INDEX = 4 +const READ_INDEX = 8 + +module.exports = { + WRITE_INDEX, + READ_INDEX } -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); +/***/ }), + +/***/ 57568: +/***/ ((module) => { + +"use strict"; + + +const MAX_TIMEOUT = 1000 + +function wait (state, index, expected, timeout, done) { + const max = Date.now() + timeout + let current = Atomics.load(state, index) + if (current === expected) { + done(null, 'ok') + return + } + let prior = current + const check = (backoff) => { + if (Date.now() > max) { + done(null, 'timed-out') } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); + setTimeout(() => { + prior = current + current = Atomics.load(state, index) + if (current === prior) { + check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2) + } else { + if (current === expected) done(null, 'ok') + else done(null, 'not-equal') + } + }, backoff) } } + check(1) +} - return target; +// let waitDiffCount = 0 +function waitDiff (state, index, expected, timeout, done) { + // const id = waitDiffCount++ + // process._rawDebug(`>>> waitDiff ${id}`) + const max = Date.now() + timeout + let current = Atomics.load(state, index) + if (current !== expected) { + done(null, 'ok') + return + } + const check = (backoff) => { + // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`) + // process._rawDebug('' + backoff) + if (Date.now() > max) { + done(null, 'timed-out') + } else { + setTimeout(() => { + current = Atomics.load(state, index) + if (current !== expected) { + done(null, 'ok') + } else { + check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2) + } + }, backoff) + } + } + check(1) } -const SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; -/** - * Load configuration from a given repository and path. - * - * @param octokit Octokit instance - * @param options - */ +module.exports = { wait, waitDiff } -async function getConfigFile(octokit, { - owner, - repo, - path, - ref -}) { - const fileExtension = path.split(".").pop().toLowerCase(); - if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { - throw new Error(`[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")`); - } // https://docs.github.com/en/rest/reference/repos#get-repository-content +/***/ }), + +/***/ 26807: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + getPrivateKey: () => getPrivateKey +}); +module.exports = __toCommonJS(dist_src_exports); +var import_path = __nccwpck_require__(16928); +var import_fs = __nccwpck_require__(79896); + +// pkg/dist-src/version.js +var VERSION = "1.1.2"; + +// pkg/dist-src/index.js +var begin = "-----BEGIN RSA PRIVATE KEY-----"; +var end = "-----END RSA PRIVATE KEY-----"; +function getPrivateKey(options = {}) { + const env = options.env || process.env; + const cwd = options.cwd || process.cwd(); + if (options.filepath) { + return (0, import_fs.readFileSync)((0, import_path.resolve)(cwd, options.filepath), "utf-8"); + } + if (env.PRIVATE_KEY) { + let privateKey = env.PRIVATE_KEY; + if (isBase64(privateKey)) { + privateKey = Buffer.from(privateKey, "base64").toString(); + } + if (privateKey.includes(begin) && privateKey.includes(end)) { + if (privateKey.indexOf("\\n") !== -1) { + privateKey = privateKey.replace(/\\n/g, "\n"); + } + if (privateKey.indexOf("\n") === -1) { + privateKey = addNewlines(privateKey); + } + return privateKey; + } + throw new Error( + `[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.` + ); + } + if (env.PRIVATE_KEY_PATH) { + const filepath = (0, import_path.resolve)(cwd, env.PRIVATE_KEY_PATH); + if ((0, import_fs.existsSync)(filepath)) { + return (0, import_fs.readFileSync)(filepath, "utf-8"); + } else { + throw new Error( + `[@probot/get-private-key] Private key does not exists at path: "${env.PRIVATE_KEY_PATH}". Please check to ensure that "env.PRIVATE_KEY_PATH" is correct.` + ); + } + } + const pemFiles = (0, import_fs.readdirSync)(cwd).filter((path) => path.endsWith(".pem")); + if (pemFiles.length > 1) { + const paths = pemFiles.join(", "); + throw new Error( + `[@probot/get-private-key] More than one file found: "${paths}". Set { filepath } option or set one of the environment variables: PRIVATE_KEY, PRIVATE_KEY_PATH` + ); + } else if (pemFiles[0]) { + return getPrivateKey({ filepath: pemFiles[0], cwd }); + } + return null; +} +function isBase64(str) { + return Buffer.from(str, "base64").toString("base64") === str; +} +function addNewlines(privateKey) { + const middleLength = privateKey.length - begin.length - end.length - 2; + const middle = privateKey.substr(begin.length + 1, middleLength); + return `${begin} +${middle.trim().replace(/\s+/g, "\n")} +${end}`; +} +getPrivateKey.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 7139: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composeConfigGet: () => composeConfigGet, + config: () => config +}); +module.exports = __toCommonJS(dist_src_exports); +var import_core4 = __nccwpck_require__(61897); + +// pkg/dist-src/version.js +var VERSION = "2.0.1"; + +// pkg/dist-src/compose-config-get.js +var import_core3 = __nccwpck_require__(61897); + +// pkg/dist-src/util/get-config-files.js +var import_core2 = __nccwpck_require__(61897); - const endpoint = _objectSpread2({ +// pkg/dist-src/util/get-config-file.js +var import_core = __nccwpck_require__(61897); +var import_js_yaml = __toESM(__nccwpck_require__(74281)); +var SUPPORTED_FILE_EXTENSIONS = ["json", "yml", "yaml"]; +async function getConfigFile(octokit, { owner, repo, path, ref }) { + const fileExtension = path.split(".").pop().toLowerCase(); + if (!SUPPORTED_FILE_EXTENSIONS.includes(fileExtension)) { + throw new Error( + `[@probot/octokit-plugin-config] .${fileExtension} extension is not support for configuration (path: "${path}")` + ); + } + const endpoint = { method: "GET", url: "/repos/{owner}/{repo}/contents/{path}", owner, @@ -6768,14 +10949,11 @@ async function getConfigFile(octokit, { path, mediaType: { format: "raw" - } - }, ref ? { - ref - } : {}); - - const { - url - } = await octokit.request.endpoint(endpoint); + }, + // this can be just `ref` once https://github.com/octokit/endpoint.js/issues/206 is resolved + ...ref ? { ref } : {} + }; + const { url } = await octokit.request.endpoint(endpoint); const emptyConfigResult = { owner, repo, @@ -6783,71 +10961,53 @@ async function getConfigFile(octokit, { url, config: null }; - try { - const { - data, - headers - } = await octokit.request(endpoint); // If path is a submodule, or a folder, then a JSON string is returned with - // the "Content-Type" header set to "application/json; charset=utf-8". - // - // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-submodule - // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-directory - // - // symlinks just return the content of the linked file when requesting the raw formt, - // so we are fine - + const { data, headers } = await octokit.request(endpoint); if (headers["content-type"] === "application/json; charset=utf-8") { - throw new Error(`[@probot/octokit-plugin-config] ${url} exists, but is either a directory or a submodule. Ignoring.`); + throw new Error( + `[@probot/octokit-plugin-config] ${url} exists, but is either a directory or a submodule. Ignoring.` + ); } - if (fileExtension === "json") { if (typeof data === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (invalid JSON)`); + throw new Error( + `[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (invalid JSON)` + ); } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { + return { + ...emptyConfigResult, config: data - }); + }; } - - const config = yaml.load(data) || {}; - - if (typeof config === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (YAML is not an object)`); + const config2 = import_js_yaml.default.load(data) || {}; + if (typeof config2 === "string") { + throw new Error( + `[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (YAML is not an object)` + ); } - - return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { - config - }); + return { + ...emptyConfigResult, + config: config2 + }; } catch (error) { if (error.status === 404) { return emptyConfigResult; } - if (error.name === "YAMLException") { const reason = /unknown tag/.test(error.message) ? "unsafe YAML" : "invalid YAML"; - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (${reason})`); + throw new Error( + `[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (${reason})` + ); } - throw error; } } -const EXTENDS_REGEX = new RegExp("^" + "(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?" + // org -"([-_.\\w\\d]+)" + // project -"(?::([-_./\\w\\d]+\\.ya?ml))?" + // filename -"$", "i"); -/** - * Computes parameters to retrieve the configuration file specified in _extends - * - * Base can either be the name of a repository in the same organization or - * a full slug "organization/repo". - * - * @param options - * @return The params needed to retrieve a configuration file - */ - +// pkg/dist-src/util/extends-to-get-content-params.js +var EXTENDS_REGEX = new RegExp( + "^(?:([a-z\\d](?:[a-z\\d]|-(?=[a-z\\d])){0,38})/)?([-_.\\w\\d]+)(?::([-_./\\w\\d]+\\.ya?ml))?$", + "i" +); function extendsToGetContentParams({ owner, path, @@ -6855,15 +11015,18 @@ function extendsToGetContentParams({ extendsValue }) { if (typeof extendsValue !== "string") { - throw new Error(`[@probot/octokit-plugin-config] Invalid value ${JSON.stringify(extendsValue)} for _extends in ${url}`); + throw new Error( + `[@probot/octokit-plugin-config] Invalid value ${JSON.stringify( + extendsValue + )} for _extends in ${url}` + ); } - const match = extendsValue.match(EXTENDS_REGEX); - if (match === null) { - throw new Error(`[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}`); + throw new Error( + `[@probot/octokit-plugin-config] Invalid value "${extendsValue}" for _extends in ${url}` + ); } - return { owner: match[1] || owner, repo: match[2], @@ -6871,37 +11034,19 @@ function extendsToGetContentParams({ }; } -/** - * Load configuration from selected repository file. If the file does not exist - * it loads configuration from the owners `.github` repository. - * - * If the repository file configuration includes an `_extends` key, that file - * is loaded. Same with the target file until no `_extends` key is present. - * - * @param octokit Octokit instance - * @param options - */ - -async function getConfigFiles(octokit, { - owner, - repo, - path, - branch -}) { +// pkg/dist-src/util/get-config-files.js +async function getConfigFiles(octokit, { owner, repo, path, branch }) { const requestedRepoFile = await getConfigFile(octokit, { owner, repo, path, ref: branch }); - const files = [requestedRepoFile]; // if no configuration file present in selected repository, - // try to load it from the `.github` repository - + const files = [requestedRepoFile]; if (!requestedRepoFile.config) { if (repo === ".github") { return files; } - const defaultRepoConfig = await getConfigFile(octokit, { owner, repo: ".github", @@ -6909,26345 +11054,29115 @@ async function getConfigFiles(octokit, { }); files.push(defaultRepoConfig); } - - const file = files[files.length - 1]; // if the configuration has no `_extends` key, we are done here. - + const file = files[files.length - 1]; if (!file.config || !file.config._extends) { return files; - } // parse the value of `_extends` into request parameters to - // retrieve the new configuration file - - + } let extendConfigOptions = extendsToGetContentParams({ owner, path, url: file.url, extendsValue: file.config._extends - }); // remove the `_extends` key from the configuration that is returned - - delete file.config._extends; // now load the configuration linked from the `_extends` key. If that - // configuration also includes an `_extends` key, then load that configuration - // as well, until the target configuration has no `_extends` key - + }); + delete file.config._extends; do { const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); files.push(extendRepoConfig); - if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { return files; } - extendConfigOptions = extendsToGetContentParams({ owner, path, url: extendRepoConfig.url, extendsValue: extendRepoConfig.config._extends }); - delete extendRepoConfig.config._extends; // Avoid loops - - const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); - + delete extendRepoConfig.config._extends; + const alreadyLoaded = files.find( + (file2) => file2.owner === extendConfigOptions.owner && file2.repo === extendConfigOptions.repo && file2.path === extendConfigOptions.path + ); if (alreadyLoaded) { - throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`); + throw new Error( + `[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.` + ); } } while (true); } -/** - * Loads configuration from one or multiple files and resolves with - * the combined configuration as well as the list of files the configuration - * was loaded from - * - * @param octokit Octokit instance - * @param options - */ - -async function composeConfigGet(octokit, { - owner, - repo, - defaults, - path, - branch -}) { +// pkg/dist-src/compose-config-get.js +async function composeConfigGet(octokit, { owner, repo, defaults, path, branch }) { const files = await getConfigFiles(octokit, { owner, repo, path, branch }); - const configs = files.map(file => file.config).reverse().filter(Boolean); + const configs = files.map((file) => file.config).reverse().filter(Boolean); return { files, config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs) }; } -/** - * @param octokit Octokit instance - */ - +// pkg/dist-src/index.js function config(octokit) { return { config: { async get(options) { return composeConfigGet(octokit, options); } - } }; } config.VERSION = VERSION; - -exports.composeConfigGet = composeConfigGet; -exports.config = config; -//# sourceMappingURL=index.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 80557: +/***/ 22581: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +module.exports = { getTransformStream }; +const { Transform } = __nccwpck_require__(86131); +const prettyFactory = __nccwpck_require__(96372); +const Sentry = __nccwpck_require__(97873); -var loader = __nccwpck_require__(26106); -var dumper = __nccwpck_require__(73811); +const LEVEL_MAP = { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal", +}; +/** + * Implements Probot's default logging formatting and error captionaing using Sentry. + * + * @param {import("./").Options} options + * @returns Transform + * @see https://getpino.io/#/docs/transports + */ +function getTransformStream(options = {}) { + const formattingEnabled = options.logFormat !== "json"; -function renamed(from, to) { - return function () { - throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + - 'Use yaml.' + to + ' instead, which is now safe by default.'); - }; -} + const levelAsString = options.logLevelInString; + const sentryEnabled = !!options.sentryDsn; + if (sentryEnabled) { + Sentry.init({ + dsn: options.sentryDsn, + // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 + // 6 is enough to serialize the deepest property across all GitHub Event payloads + normalizeDepth: 6, + }); + } -module.exports.Type = __nccwpck_require__(57480); -module.exports.Schema = __nccwpck_require__(22258); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(54323); -module.exports.JSON_SCHEMA = __nccwpck_require__(70265); -module.exports.CORE_SCHEMA = __nccwpck_require__(90085); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(77599); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.dump = dumper.dump; -module.exports.YAMLException = __nccwpck_require__(30780); + const pretty = prettyFactory({ + ignore: [ + // default pino keys + "time", + "pid", + "hostname", + // remove keys from pino-http + "req", + "res", + "responseTime", + ].join(","), + errorProps: ["event", "status", "headers", "request", "sentryEventId"].join( + "," + ), + }); -// Re-export all types in case user wants to create custom schema -module.exports.types = { - binary: __nccwpck_require__(56942), - float: __nccwpck_require__(56128), - map: __nccwpck_require__(74352), - null: __nccwpck_require__(61002), - pairs: __nccwpck_require__(18978), - set: __nccwpck_require__(87424), - timestamp: __nccwpck_require__(9561), - bool: __nccwpck_require__(85327), - int: __nccwpck_require__(2848), - merge: __nccwpck_require__(70884), - omap: __nccwpck_require__(65894), - seq: __nccwpck_require__(89695), - str: __nccwpck_require__(32568) -}; + return new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + const line = chunk.toString().trim(); -// Removed functions from JS-YAML 3.0.x -module.exports.safeLoad = renamed('safeLoad', 'load'); -module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); -module.exports.safeDump = renamed('safeDump', 'dump'); + /* istanbul ignore if */ + if (line === undefined) return cb(); + const data = sentryEnabled ? JSON.parse(line) : null; -/***/ }), + if (!sentryEnabled || data.level < 50) { + if (formattingEnabled) { + return cb(null, pretty(line)); + } -/***/ 44828: -/***/ ((module) => { + if (levelAsString) { + return cb(null, stringifyLogLevel(JSON.parse(line))); + } -"use strict"; + cb(null, line + "\n"); + return; + } + Sentry.withScope(function (scope) { + const sentryLevelName = data.level === 50 ? "error" : "fatal"; + scope.setLevel(sentryLevelName); + for (const extra of ["event", "headers", "request", "status"]) { + if (!data[extra]) continue; -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} + scope.setExtra(extra, data[extra]); + } + // set user id and username to installation ID and account login + if (data.event && data.event.payload) { + const { + // When GitHub App is installed organization wide + installation: { id, account: { login: account } = {} } = {}, -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} + // When the repository belongs to an organization + organization: { login: organization } = {}, + // When the repository belongs to a user + repository: { owner: { login: owner } = {} } = {}, + } = data.event.payload; + scope.setUser({ + id: id, + username: account || organization || owner, + }); + } -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; + const sentryEventId = Sentry.captureException(toSentryError(data)); - return [ sequence ]; -} + // reduce logging data and add reference to sentry event instead + if (data.event) { + data.event = { id: data.event.id }; + } + if (data.request) { + data.request = { + method: data.request.method, + url: data.request.url, + }; + } + data.sentryEventId = sentryEventId; + if (formattingEnabled) { + return cb(null, pretty(data)); + } -function extend(target, source) { - var index, length, key, sourceKeys; + // istanbul ignore if + if (levelAsString) { + return cb(null, stringifyLogLevel(data)); + } - if (source) { - sourceKeys = Object.keys(source); + cb(null, JSON.stringify(data) + "\n"); + }); + }, + }); +} - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } - } +function stringifyLogLevel(data) { + data.level = LEVEL_MAP[data.level]; + return JSON.stringify(data) + "\n"; +} - return target; +function toSentryError(data) { + const error = new Error(data.msg); + error.name = data.type; + error.stack = data.stack; + return error; } -function repeat(string, count) { - var result = '', cycle; +/***/ }), - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } +/***/ 40687: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return result; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const types = __nccwpck_require__(29073); -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} +/** + * Add a listener that cancels and finishes a transaction when the global + * document is hidden. + */ +function registerBackgroundTabDetection() { + if (types.WINDOW.document) { + types.WINDOW.document.addEventListener('visibilitychange', () => { + // eslint-disable-next-line deprecation/deprecation + const activeTransaction = core.getActiveTransaction() ; + if (types.WINDOW.document.hidden && activeTransaction) { + const statusType = 'cancelled'; + const { op, status } = core.spanToJSON(activeTransaction); -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; + debugBuild.DEBUG_BUILD && + utils.logger.log(`[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${op}`); + // We should not set status if it is already set, this prevent important statuses like + // error or data loss from being overwritten on transaction. + if (!status) { + activeTransaction.setStatus(statusType); + } + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + activeTransaction.setTag('visibilitychange', 'document.hidden'); + activeTransaction.end(); + } + }); + } else { + debugBuild.DEBUG_BUILD && utils.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); + } +} + +exports.registerBackgroundTabDetection = registerBackgroundTabDetection; +//# sourceMappingURL=backgroundtab.js.map /***/ }), -/***/ 73811: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 60720: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const backgroundtab = __nccwpck_require__(40687); +const instrument = __nccwpck_require__(63187); +const index = __nccwpck_require__(5902); +const request = __nccwpck_require__(15737); +const types = __nccwpck_require__(29073); -/*eslint-disable no-use-before-define*/ +const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing'; -var common = __nccwpck_require__(44828); -var YAMLException = __nccwpck_require__(30780); -var DEFAULT_SCHEMA = __nccwpck_require__(77599); +/** Options for Browser Tracing integration */ -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; +const DEFAULT_BROWSER_TRACING_OPTIONS = { + ...core.TRACING_DEFAULTS, + instrumentNavigation: true, + instrumentPageLoad: true, + markBackgroundSpan: true, + enableLongTask: true, + enableInp: false, + interactionsSampleRate: 1, + _experiments: {}, + ...request.defaultRequestInstrumentationOptions, +}; -var CHAR_BOM = 0xFEFF; -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ +/** + * The Browser Tracing integration automatically instruments browser pageload/navigation + * actions as transactions, and captures requests, metrics and errors as spans. + * + * The integration can be configured with a variety of options, and can be extended to use + * any routing library. This integration uses {@see IdleTransaction} to create transactions. + * + * We explicitly export the proper type here, as this has to be extended in some cases. + */ +const browserTracingIntegration = ((_options = {}) => { + const _hasSetTracePropagationTargets = debugBuild.DEBUG_BUILD + ? !!( + // eslint-disable-next-line deprecation/deprecation + (_options.tracePropagationTargets || _options.tracingOrigins) + ) + : false; -var ESCAPE_SEQUENCES = {}; + core.addTracingExtensions(); -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; + // TODO (v8): remove this block after tracingOrigins is removed + // Set tracePropagationTargets to tracingOrigins if specified by the user + // In case both are specified, tracePropagationTargets takes precedence + // eslint-disable-next-line deprecation/deprecation + if (!_options.tracePropagationTargets && _options.tracingOrigins) { + // eslint-disable-next-line deprecation/deprecation + _options.tracePropagationTargets = _options.tracingOrigins; + } -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; + const options = { + ...DEFAULT_BROWSER_TRACING_OPTIONS, + ..._options, + }; -var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + const _collectWebVitals = index.startTrackingWebVitals(); -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; + /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */ + const interactionIdToRouteNameMapping = {}; + if (options.enableInp) { + index.startTrackingINP(interactionIdToRouteNameMapping, options.interactionsSampleRate); + } - if (map === null) return {}; + if (options.enableLongTask) { + index.startTrackingLongTasks(); + } + if (options._experiments.enableInteractions) { + index.startTrackingInteractions(); + } - result = {}; - keys = Object.keys(map); + const latestRoute - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); + = { + name: undefined, + context: undefined, + }; - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); + /** Create routing idle transaction. */ + function _createRouteTransaction(context) { + // eslint-disable-next-line deprecation/deprecation + const hub = core.getCurrentHub(); + + const { beforeStartSpan, idleTimeout, finalTimeout, heartbeatInterval } = options; + + const isPageloadTransaction = context.op === 'pageload'; + + let expandedContext; + if (isPageloadTransaction) { + const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : ''; + const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined; + const { traceId, dsc, parentSpanId, sampled } = utils.propagationContextFromHeaders(sentryTrace, baggage); + expandedContext = { + traceId, + parentSpanId, + parentSampled: sampled, + ...context, + metadata: { + // eslint-disable-next-line deprecation/deprecation + ...context.metadata, + dynamicSamplingContext: dsc, + }, + trimEnd: true, + }; + } else { + expandedContext = { + trimEnd: true, + ...context, + }; } - type = schema.compiledTypeMap['fallback'][tag]; - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; + const finalContext = beforeStartSpan ? beforeStartSpan(expandedContext) : expandedContext; + + // If `beforeStartSpan` set a custom name, record that fact + // eslint-disable-next-line deprecation/deprecation + finalContext.metadata = + finalContext.name !== expandedContext.name + ? // eslint-disable-next-line deprecation/deprecation + { ...finalContext.metadata, source: 'custom' } + : // eslint-disable-next-line deprecation/deprecation + finalContext.metadata; + + latestRoute.name = finalContext.name; + latestRoute.context = finalContext; + + if (finalContext.sampled === false) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`); } - result[tag] = style; - } + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`); - return result; -} + const { location } = types.WINDOW; -function encodeHex(character) { - var string, handle, length; + const idleTransaction = core.startIdleTransaction( + hub, + finalContext, + idleTimeout, + finalTimeout, + true, + { location }, // for use in the tracesSampler + heartbeatInterval, + isPageloadTransaction, // should wait for finish signal if it's a pageload transaction + ); - string = character.toString(16).toUpperCase(); + if (isPageloadTransaction && types.WINDOW.document) { + types.WINDOW.document.addEventListener('readystatechange', () => { + if (['interactive', 'complete'].includes(types.WINDOW.document.readyState)) { + idleTransaction.sendAutoFinishSignal(); + } + }); - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + if (['interactive', 'complete'].includes(types.WINDOW.document.readyState)) { + idleTransaction.sendAutoFinishSignal(); + } + } + + idleTransaction.registerBeforeFinishCallback(transaction => { + _collectWebVitals(); + index.addPerformanceEntries(transaction); + }); + + return idleTransaction ; } - return '\\' + handle + common.repeat('0', length - string.length) + string; -} + return { + name: BROWSER_TRACING_INTEGRATION_ID, + // eslint-disable-next-line @typescript-eslint/no-empty-function + setupOnce: () => {}, + afterAllSetup(client) { + const clientOptions = client.getOptions(); + + const { markBackgroundSpan, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, _experiments } = + options; + + const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets; + // There are three ways to configure tracePropagationTargets: + // 1. via top level client option `tracePropagationTargets` + // 2. via BrowserTracing option `tracePropagationTargets` + // 3. via BrowserTracing option `tracingOrigins` (deprecated) + // + // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to + // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated). + // This is done as it minimizes bundle size (we don't have to have undefined checks). + // + // If both 1 and either one of 2 or 3 are set (from above), we log out a warning. + // eslint-disable-next-line deprecation/deprecation + const tracePropagationTargets = clientOptionsTracePropagationTargets || options.tracePropagationTargets; + if (debugBuild.DEBUG_BUILD && _hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) { + utils.logger.warn( + '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.', + ); + } + let activeSpan; + let startingUrl = types.WINDOW.location && types.WINDOW.location.href; -var QUOTING_TYPE_SINGLE = 1, - QUOTING_TYPE_DOUBLE = 2; + if (client.on) { + client.on('startNavigationSpan', (context) => { + if (activeSpan) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${core.spanToJSON(activeSpan).op}`); + // If there's an open transaction on the scope, we need to finish it before creating an new one. + activeSpan.end(); + } + activeSpan = _createRouteTransaction({ + op: 'navigation', + ...context, + }); + }); -function State(options) { - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; - this.forceQuotes = options['forceQuotes'] || false; - this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + client.on('startPageLoadSpan', (context) => { + if (activeSpan) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${core.spanToJSON(activeSpan).op}`); + // If there's an open transaction on the scope, we need to finish it before creating an new one. + activeSpan.end(); + } + activeSpan = _createRouteTransaction({ + op: 'pageload', + ...context, + }); + }); + } - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; + if (options.instrumentPageLoad && client.emit && types.WINDOW.location) { + const context = { + name: types.WINDOW.location.pathname, + // pageload should always start at timeOrigin (and needs to be in s, not ms) + startTimestamp: utils.browserPerformanceTimeOrigin ? utils.browserPerformanceTimeOrigin / 1000 : undefined, + origin: 'auto.pageload.browser', + attributes: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url', + }, + }; + startBrowserTracingPageLoadSpan(client, context); + } + + if (options.instrumentNavigation && client.emit && types.WINDOW.location) { + utils.addHistoryInstrumentationHandler(({ to, from }) => { + /** + * This early return is there to account for some cases where a navigation transaction starts right after + * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't + * create an uneccessary navigation transaction. + * + * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also + * only be caused in certain development environments where the usage of a hot module reloader is causing + * errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } - this.tag = null; - this.result = ''; + if (from !== to) { + startingUrl = undefined; + const context = { + name: types.WINDOW.location.pathname, + origin: 'auto.navigation.browser', + attributes: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url', + }, + }; - this.duplicates = []; - this.usedDuplicates = null; -} + startBrowserTracingNavigationSpan(client, context); + } + }); + } -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; + if (markBackgroundSpan) { + backgroundtab.registerBackgroundTabDetection(); + } - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } + if (_experiments.enableInteractions) { + registerInteractionListener(options, latestRoute); + } - if (line.length && line !== '\n') result += ind; + if (options.enableInp) { + registerInpInteractionListener(interactionIdToRouteNameMapping, latestRoute); + } - result += line; + request.instrumentOutgoingRequests({ + traceFetch, + traceXHR, + tracePropagationTargets, + shouldCreateSpanForRequest, + enableHTTPTimings, + }); + }, + // TODO v8: Remove this again + // This is private API that we use to fix converted BrowserTracing integrations in Next.js & SvelteKit + options, + }; +}) ; + +/** + * Manually start a page load span. + * This will only do something if the BrowserTracing integration has been setup. + */ +function startBrowserTracingPageLoadSpan(client, spanOptions) { + if (!client.emit) { + return; } - return result; + client.emit('startPageLoadSpan', spanOptions); + + const span = core.getActiveSpan(); + const op = span && core.spanToJSON(span).op; + return op === 'pageload' ? span : undefined; } -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); +/** + * Manually start a navigation span. + * This will only do something if the BrowserTracing integration has been setup. + */ +function startBrowserTracingNavigationSpan(client, spanOptions) { + if (!client.emit) { + return; + } + + client.emit('startNavigationSpan', spanOptions); + + const span = core.getActiveSpan(); + const op = span && core.spanToJSON(span).op; + return op === 'navigation' ? span : undefined; } -function testImplicitResolving(state, str) { - var index, length, type; +/** Returns the value of a meta tag */ +function getMetaContent(metaName) { + // Can't specify generic to `getDomElement` because tracing can be used + // in a variety of environments, have to disable `no-unsafe-member-access` + // as a result. + const metaTag = utils.getDomElement(`meta[name=${metaName}]`); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return metaTag ? metaTag.getAttribute('content') : undefined; +} - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; +/** Start listener for interaction transactions */ +function registerInteractionListener( + options, + latestRoute - if (type.resolve(str)) { - return true; +, +) { + let inflightInteractionTransaction; + const registerInteractionTransaction = () => { + const { idleTimeout, finalTimeout, heartbeatInterval } = options; + const op = 'ui.action.click'; + + // eslint-disable-next-line deprecation/deprecation + const currentTransaction = core.getActiveTransaction(); + if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`, + ); + return undefined; } - } - return false; -} + if (inflightInteractionTransaction) { + inflightInteractionTransaction.setFinishReason('interactionInterrupted'); + inflightInteractionTransaction.end(); + inflightInteractionTransaction = undefined; + } -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} + if (!latestRoute.name) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`); + return undefined; + } -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) - || (0x10000 <= c && c <= 0x10FFFF); -} + const { location } = types.WINDOW; -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// Including s-white (for some reason, examples doesn't match specs in this aspect) -// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark -function isNsCharOrWhitespace(c) { - return isPrintable(c) - && c !== CHAR_BOM - // - b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; + const context = { + name: latestRoute.name, + op, + trimEnd: true, + data: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.context ? getSource(latestRoute.context) : 'url', + }, + }; + + inflightInteractionTransaction = core.startIdleTransaction( + // eslint-disable-next-line deprecation/deprecation + core.getCurrentHub(), + context, + idleTimeout, + finalTimeout, + true, + { location }, // for use in the tracesSampler + heartbeatInterval, + ); + }; + + ['click'].forEach(type => { + if (types.WINDOW.document) { + addEventListener(type, registerInteractionTransaction, { once: false, capture: true }); + } + }); } -// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out -// c = flow-in ⇒ ns-plain-safe-in -// c = block-key ⇒ ns-plain-safe-out -// c = flow-key ⇒ ns-plain-safe-in -// [128] ns-plain-safe-out ::= ns-char -// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator -// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) -// | ( /* An ns-char preceding */ “#” ) -// | ( “:” /* Followed by an ns-plain-safe(c) */ ) -function isPlainSafe(c, prev, inblock) { - var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return ( - // ns-plain-safe - inblock ? // c = flow-in - cIsNsCharOrWhitespace - : cIsNsCharOrWhitespace - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - ) - // ns-plain-char - && c !== CHAR_SHARP // false on '#' - && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' - || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' - || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +function isPerformanceEventTiming(entry) { + return 'duration' in entry; } -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part - return isPrintable(c) && c !== CHAR_BOM - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; +/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */ +const MAX_INTERACTIONS = 10; + +/** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */ +function registerInpInteractionListener( + interactionIdToRouteNameMapping, + latestRoute + +, +) { + const handleEntries = ({ entries }) => { + const client = core.getClient(); + // We need to get the replay, user, and activeTransaction from the current scope + // so that we can associate replay id, profile id, and a user display to the span + const replay = + client !== undefined && client.getIntegrationByName !== undefined + ? (client.getIntegrationByName('Replay') ) + : undefined; + const replayId = replay !== undefined ? replay.getReplayId() : undefined; + // eslint-disable-next-line deprecation/deprecation + const activeTransaction = core.getActiveTransaction(); + const currentScope = core.getCurrentScope(); + const user = currentScope !== undefined ? currentScope.getUser() : undefined; + entries.forEach(entry => { + if (isPerformanceEventTiming(entry)) { + const interactionId = entry.interactionId; + if (interactionId === undefined) { + return; + } + const existingInteraction = interactionIdToRouteNameMapping[interactionId]; + const duration = entry.duration; + const startTime = entry.startTime; + const keys = Object.keys(interactionIdToRouteNameMapping); + const minInteractionId = + keys.length > 0 + ? keys.reduce((a, b) => { + return interactionIdToRouteNameMapping[a].duration < interactionIdToRouteNameMapping[b].duration + ? a + : b; + }) + : undefined; + // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time. + // This is also checked in the web-vitals library. + if (entry.entryType === 'first-input') { + const matchingEntry = keys + .map(key => interactionIdToRouteNameMapping[key]) + .some(interaction => { + return interaction.duration === duration && interaction.startTime === startTime; + }); + if (matchingEntry) { + return; + } + } + // Interactions with an id of 0 and are not first-input are not valid. + if (!interactionId) { + return; + } + // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses. + if (existingInteraction) { + existingInteraction.duration = Math.max(existingInteraction.duration, duration); + } else if ( + keys.length < MAX_INTERACTIONS || + minInteractionId === undefined || + duration > interactionIdToRouteNameMapping[minInteractionId].duration + ) { + // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry. + const routeName = latestRoute.name; + const parentContext = latestRoute.context; + if (routeName && parentContext) { + if (minInteractionId && Object.keys(interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete interactionIdToRouteNameMapping[minInteractionId]; + } + interactionIdToRouteNameMapping[interactionId] = { + routeName, + duration, + parentContext, + user, + activeTransaction, + replayId, + startTime, + }; + } + } + } + }); + }; + instrument.addPerformanceInstrumentationHandler('event', handleEntries); + instrument.addPerformanceInstrumentationHandler('first-input', handleEntries); } -// Simplified test for values allowed as the last character in plain style. -function isPlainSafeLast(c) { - // just not whitespace or colon, it will be checked to be plain character later - return !isWhitespace(c) && c !== CHAR_COLON; +function getSource(context) { + const sourceFromAttributes = context.attributes && context.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + // eslint-disable-next-line deprecation/deprecation + const sourceFromData = context.data && context.data[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + // eslint-disable-next-line deprecation/deprecation + const sourceFromMetadata = context.metadata && context.metadata.source; + + return sourceFromAttributes || sourceFromData || sourceFromMetadata; } -// Same as 'string'.codePointAt(pos), but works in older browsers. -function codePointAt(string, pos) { - var first = string.charCodeAt(pos), second; - if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { - second = string.charCodeAt(pos + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; +exports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID; +exports.browserTracingIntegration = browserTracingIntegration; +exports.getMetaContent = getMetaContent; +exports.startBrowserTracingNavigationSpan = startBrowserTracingNavigationSpan; +exports.startBrowserTracingPageLoadSpan = startBrowserTracingPageLoadSpan; +//# sourceMappingURL=browserTracingIntegration.js.map + + +/***/ }), + +/***/ 72416: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const backgroundtab = __nccwpck_require__(40687); +const instrument = __nccwpck_require__(63187); +const index = __nccwpck_require__(5902); +const request = __nccwpck_require__(15737); +const router = __nccwpck_require__(99503); +const types = __nccwpck_require__(29073); + +const BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing'; + +/** Options for Browser Tracing integration */ + +const DEFAULT_BROWSER_TRACING_OPTIONS = { + ...core.TRACING_DEFAULTS, + markBackgroundTransactions: true, + routingInstrumentation: router.instrumentRoutingWithDefaults, + startTransactionOnLocationChange: true, + startTransactionOnPageLoad: true, + enableLongTask: true, + enableInp: false, + interactionsSampleRate: 1, + _experiments: {}, + ...request.defaultRequestInstrumentationOptions, +}; + +/** We store up to 10 interaction candidates max to cap memory usage. This is the same cap as getINP from web-vitals */ +const MAX_INTERACTIONS = 10; + +/** + * The Browser Tracing integration automatically instruments browser pageload/navigation + * actions as transactions, and captures requests, metrics and errors as spans. + * + * The integration can be configured with a variety of options, and can be extended to use + * any routing library. This integration uses {@see IdleTransaction} to create transactions. + * + * @deprecated Use `browserTracingIntegration()` instead. + */ +class BrowserTracing { + // This class currently doesn't have a static `id` field like the other integration classes, because it prevented + // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects. + // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all + // integrations. + + /** Browser Tracing integration options */ + + /** + * @inheritDoc + */ + + // eslint-disable-next-line deprecation/deprecation + + constructor(_options) { + this.name = BROWSER_TRACING_INTEGRATION_ID; + this._hasSetTracePropagationTargets = false; + + core.addTracingExtensions(); + + if (debugBuild.DEBUG_BUILD) { + this._hasSetTracePropagationTargets = !!( + _options && + // eslint-disable-next-line deprecation/deprecation + (_options.tracePropagationTargets || _options.tracingOrigins) + ); } - } - return first; -} -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} + this.options = { + ...DEFAULT_BROWSER_TRACING_OPTIONS, + ..._options, + }; -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; + // Special case: enableLongTask can be set in _experiments + // TODO (v8): Remove this in v8 + if (this.options._experiments.enableLongTask !== undefined) { + this.options.enableLongTask = this.options._experiments.enableLongTask; + } -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, - testAmbiguousType, quotingType, forceQuotes, inblock) { + // TODO (v8): remove this block after tracingOrigins is removed + // Set tracePropagationTargets to tracingOrigins if specified by the user + // In case both are specified, tracePropagationTargets takes precedence + // eslint-disable-next-line deprecation/deprecation + if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) { + // eslint-disable-next-line deprecation/deprecation + this.options.tracePropagationTargets = _options.tracingOrigins; + } - var i; - var char = 0; - var prevChar = null; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(codePointAt(string, 0)) - && isPlainSafeLast(codePointAt(string, string.length - 1)); + this._collectWebVitals = index.startTrackingWebVitals(); + /** Stores a mapping of interactionIds from PerformanceEventTimings to the origin interaction path */ + this._interactionIdToRouteNameMapping = {}; - if (singleLineOnly || forceQuotes) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; + if (this.options.enableInp) { + index.startTrackingINP(this._interactionIdToRouteNameMapping, this.options.interactionsSampleRate); } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; + if (this.options.enableLongTask) { + index.startTrackingLongTasks(); } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - if (plain && !forceQuotes && !testAmbiguousType(string)) { - return STYLE_PLAIN; + if (this.options._experiments.enableInteractions) { + index.startTrackingInteractions(); } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - if (!forceQuotes) { - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + + this._latestRoute = { + name: undefined, + context: undefined, + }; } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; -} -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey, inblock) { - state.dump = (function () { - if (string.length === 0) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + this._getCurrentHub = getCurrentHub; + const hub = getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const client = hub.getClient(); + const clientOptions = client && client.getOptions(); + + const { + routingInstrumentation: instrumentRouting, + startTransactionOnLocationChange, + startTransactionOnPageLoad, + markBackgroundTransactions, + traceFetch, + traceXHR, + shouldCreateSpanForRequest, + enableHTTPTimings, + _experiments, + } = this.options; + + const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets; + // There are three ways to configure tracePropagationTargets: + // 1. via top level client option `tracePropagationTargets` + // 2. via BrowserTracing option `tracePropagationTargets` + // 3. via BrowserTracing option `tracingOrigins` (deprecated) + // + // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to + // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated). + // This is done as it minimizes bundle size (we don't have to have undefined checks). + // + // If both 1 and either one of 2 or 3 are set (from above), we log out a warning. + // eslint-disable-next-line deprecation/deprecation + const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets; + if (debugBuild.DEBUG_BUILD && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) { + utils.logger.warn( + '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.', + ); } - if (!state.noCompatMode) { - if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); - } + + instrumentRouting( + (context) => { + const transaction = this._createRouteTransaction(context); + + this.options._experiments.onStartRouteTransaction && + this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub); + + return transaction; + }, + startTransactionOnPageLoad, + startTransactionOnLocationChange, + ); + + if (markBackgroundTransactions) { + backgroundtab.registerBackgroundTabDetection(); } - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + if (_experiments.enableInteractions) { + this._registerInteractionListener(); + } - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); + if (this.options.enableInp) { + this._registerInpInteractionListener(); } - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, - testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + request.instrumentOutgoingRequests({ + traceFetch, + traceXHR, + tracePropagationTargets, + shouldCreateSpanForRequest, + enableHTTPTimings, + }); + } - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); + /** Create routing idle transaction. */ + _createRouteTransaction(context) { + if (!this._getCurrentHub) { + debugBuild.DEBUG_BUILD && + utils.logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`); + return undefined; } - }()); + + const hub = this._getCurrentHub(); + + const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options; + + const isPageloadTransaction = context.op === 'pageload'; + + let expandedContext; + if (isPageloadTransaction) { + const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : ''; + const baggage = isPageloadTransaction ? getMetaContent('baggage') : undefined; + const { traceId, dsc, parentSpanId, sampled } = utils.propagationContextFromHeaders(sentryTrace, baggage); + expandedContext = { + traceId, + parentSpanId, + parentSampled: sampled, + ...context, + metadata: { + // eslint-disable-next-line deprecation/deprecation + ...context.metadata, + dynamicSamplingContext: dsc, + }, + trimEnd: true, + }; + } else { + expandedContext = { + trimEnd: true, + ...context, + }; + } + + const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; + + // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it + // from being sent to Sentry). + const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext; + + // If `beforeNavigate` set a custom name, record that fact + // eslint-disable-next-line deprecation/deprecation + finalContext.metadata = + finalContext.name !== expandedContext.name + ? // eslint-disable-next-line deprecation/deprecation + { ...finalContext.metadata, source: 'custom' } + : // eslint-disable-next-line deprecation/deprecation + finalContext.metadata; + + this._latestRoute.name = finalContext.name; + this._latestRoute.context = finalContext; + + // eslint-disable-next-line deprecation/deprecation + if (finalContext.sampled === false) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`); + } + + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`); + + const { location } = types.WINDOW; + + const idleTransaction = core.startIdleTransaction( + hub, + finalContext, + idleTimeout, + finalTimeout, + true, + { location }, // for use in the tracesSampler + heartbeatInterval, + isPageloadTransaction, // should wait for finish signal if it's a pageload transaction + ); + + if (isPageloadTransaction) { + if (types.WINDOW.document) { + types.WINDOW.document.addEventListener('readystatechange', () => { + if (['interactive', 'complete'].includes(types.WINDOW.document.readyState)) { + idleTransaction.sendAutoFinishSignal(); + } + }); + + if (['interactive', 'complete'].includes(types.WINDOW.document.readyState)) { + idleTransaction.sendAutoFinishSignal(); + } + } + } + + idleTransaction.registerBeforeFinishCallback(transaction => { + this._collectWebVitals(); + index.addPerformanceEntries(transaction); + }); + + return idleTransaction ; + } + + /** Start listener for interaction transactions */ + _registerInteractionListener() { + let inflightInteractionTransaction; + const registerInteractionTransaction = () => { + const { idleTimeout, finalTimeout, heartbeatInterval } = this.options; + const op = 'ui.action.click'; + + // eslint-disable-next-line deprecation/deprecation + const currentTransaction = core.getActiveTransaction(); + if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`, + ); + return undefined; + } + + if (inflightInteractionTransaction) { + inflightInteractionTransaction.setFinishReason('interactionInterrupted'); + inflightInteractionTransaction.end(); + inflightInteractionTransaction = undefined; + } + + if (!this._getCurrentHub) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`); + return undefined; + } + + if (!this._latestRoute.name) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`); + return undefined; + } + + const hub = this._getCurrentHub(); + const { location } = types.WINDOW; + + const context = { + name: this._latestRoute.name, + op, + trimEnd: true, + data: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: this._latestRoute.context + ? getSource(this._latestRoute.context) + : 'url', + }, + }; + + inflightInteractionTransaction = core.startIdleTransaction( + hub, + context, + idleTimeout, + finalTimeout, + true, + { location }, // for use in the tracesSampler + heartbeatInterval, + ); + }; + + ['click'].forEach(type => { + if (types.WINDOW.document) { + addEventListener(type, registerInteractionTransaction, { once: false, capture: true }); + } + }); + } + + /** Creates a listener on interaction entries, and maps interactionIds to the origin path of the interaction */ + _registerInpInteractionListener() { + const handleEntries = ({ entries }) => { + const client = core.getClient(); + // We need to get the replay, user, and activeTransaction from the current scope + // so that we can associate replay id, profile id, and a user display to the span + const replay = + client !== undefined && client.getIntegrationByName !== undefined + ? (client.getIntegrationByName('Replay') ) + : undefined; + const replayId = replay !== undefined ? replay.getReplayId() : undefined; + // eslint-disable-next-line deprecation/deprecation + const activeTransaction = core.getActiveTransaction(); + const currentScope = core.getCurrentScope(); + const user = currentScope !== undefined ? currentScope.getUser() : undefined; + entries.forEach(entry => { + if (isPerformanceEventTiming(entry)) { + const interactionId = entry.interactionId; + if (interactionId === undefined) { + return; + } + const existingInteraction = this._interactionIdToRouteNameMapping[interactionId]; + const duration = entry.duration; + const startTime = entry.startTime; + const keys = Object.keys(this._interactionIdToRouteNameMapping); + const minInteractionId = + keys.length > 0 + ? keys.reduce((a, b) => { + return this._interactionIdToRouteNameMapping[a].duration < + this._interactionIdToRouteNameMapping[b].duration + ? a + : b; + }) + : undefined; + // For a first input event to be considered, we must check that an interaction event does not already exist with the same duration and start time. + // This is also checked in the web-vitals library. + if (entry.entryType === 'first-input') { + const matchingEntry = keys + .map(key => this._interactionIdToRouteNameMapping[key]) + .some(interaction => { + return interaction.duration === duration && interaction.startTime === startTime; + }); + if (matchingEntry) { + return; + } + } + // Interactions with an id of 0 and are not first-input are not valid. + if (!interactionId) { + return; + } + // If the interaction already exists, we want to use the duration of the longest entry, since that is what the INP metric uses. + if (existingInteraction) { + existingInteraction.duration = Math.max(existingInteraction.duration, duration); + } else if ( + keys.length < MAX_INTERACTIONS || + minInteractionId === undefined || + duration > this._interactionIdToRouteNameMapping[minInteractionId].duration + ) { + // If the interaction does not exist, we want to add it to the mapping if there is space, or if the duration is longer than the shortest entry. + const routeName = this._latestRoute.name; + const parentContext = this._latestRoute.context; + if (routeName && parentContext) { + if (minInteractionId && Object.keys(this._interactionIdToRouteNameMapping).length >= MAX_INTERACTIONS) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._interactionIdToRouteNameMapping[minInteractionId]; + } + this._interactionIdToRouteNameMapping[interactionId] = { + routeName, + duration, + parentContext, + user, + activeTransaction, + replayId, + startTime, + }; + } + } + } + }); + }; + instrument.addPerformanceInstrumentationHandler('event', handleEntries); + instrument.addPerformanceInstrumentationHandler('first-input', handleEntries); + } } -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; +/** Returns the value of a meta tag */ +function getMetaContent(metaName) { + // Can't specify generic to `getDomElement` because tracing can be used + // in a variety of environments, have to disable `no-unsafe-member-access` + // as a result. + const metaTag = utils.getDomElement(`meta[name=${metaName}]`); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return metaTag ? metaTag.getAttribute('content') : undefined; +} - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); +function getSource(context) { + const sourceFromAttributes = context.attributes && context.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + // eslint-disable-next-line deprecation/deprecation + const sourceFromData = context.data && context.data[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + // eslint-disable-next-line deprecation/deprecation + const sourceFromMetadata = context.metadata && context.metadata.source; - return indentIndicator + chomp + '\n'; + return sourceFromAttributes || sourceFromData || sourceFromMetadata; } -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +function isPerformanceEventTiming(entry) { + return 'duration' in entry; } -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; +exports.BROWSER_TRACING_INTEGRATION_ID = BROWSER_TRACING_INTEGRATION_ID; +exports.BrowserTracing = BrowserTracing; +exports.getMetaContent = getMetaContent; +//# sourceMappingURL=browsertracing.js.map - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } +/***/ }), - return result; +/***/ 63187: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const getCLS = __nccwpck_require__(76435); +const getFID = __nccwpck_require__(27308); +const getINP = __nccwpck_require__(83462); +const getLCP = __nccwpck_require__(48404); +const observe = __nccwpck_require__(80215); +const onTTFB = __nccwpck_require__(18146); + +const handlers = {}; +const instrumented = {}; + +let _previousCls; +let _previousFid; +let _previousLcp; +let _previousTtfb; +let _previousInp; + +/** + * Add a callback that will be triggered when a CLS metric is available. + * Returns a cleanup callback which can be called to remove the instrumentation handler. + * + * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called. + * This will lead to the CLS being finalized and frozen. + */ +function addClsInstrumentationHandler( + callback, + stopOnCallback = false, +) { + return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback); } -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; +/** + * Add a callback that will be triggered when a LCP metric is available. + * Returns a cleanup callback which can be called to remove the instrumentation handler. + * + * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called. + * This will lead to the LCP being finalized and frozen. + */ +function addLcpInstrumentationHandler( + callback, + stopOnCallback = false, +) { + return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback); +} - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; +/** + * Add a callback that will be triggered when a FID metric is available. + */ +function addTtfbInstrumentationHandler(callback) { + return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb); +} - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } +/** + * Add a callback that will be triggered when a FID metric is available. + * Returns a cleanup callback which can be called to remove the instrumentation handler. + */ +function addFidInstrumentationHandler(callback) { + return addMetricObserver('fid', callback, instrumentFid, _previousFid); +} - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); +/** + * Add a callback that will be triggered when a INP metric is available. + * Returns a cleanup callback which can be called to remove the instrumentation handler. + */ +function addInpInstrumentationHandler( + callback, +) { + return addMetricObserver('inp', callback, instrumentInp, _previousInp); +} + +/** + * Add a callback that will be triggered when a performance observer is triggered, + * and receives the entries of the observer. + * Returns a cleanup callback which can be called to remove the instrumentation handler. + */ +function addPerformanceInstrumentationHandler( + type, + callback, +) { + addHandler(type, callback); + + if (!instrumented[type]) { + instrumentPerformanceObserver(type); + instrumented[type] = true; } - return result.slice(1); // drop extra \n joiner + return getCleanupCallback(type, callback); } -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char = 0; - var escapeSeq; +/** Trigger all handlers of a given type. */ +function triggerHandlers(type, data) { + const typeHandlers = handlers[type]; - for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - escapeSeq = ESCAPE_SEQUENCES[char]; + if (!typeHandlers || !typeHandlers.length) { + return; + } - if (!escapeSeq && isPrintable(char)) { - result += string[i]; - if (char >= 0x10000) result += string[i + 1]; - } else { - result += escapeSeq || encodeHex(char); + for (const handler of typeHandlers) { + try { + handler(data); + } catch (e) { + debugBuild.DEBUG_BUILD && + utils.logger.error( + `Error while triggering instrumentation handler.\nType: ${type}\nName: ${utils.getFunctionName(handler)}\nError:`, + e, + ); } } +} - return result; +function instrumentCls() { + return getCLS.onCLS( + metric => { + triggerHandlers('cls', { + metric, + }); + _previousCls = metric; + }, + { reportAllChanges: true }, + ); } -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length, - value; +function instrumentFid() { + return getFID.onFID(metric => { + triggerHandlers('fid', { + metric, + }); + _previousFid = metric; + }); +} - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; +function instrumentLcp() { + return getLCP.onLCP(metric => { + triggerHandlers('lcp', { + metric, + }); + _previousLcp = metric; + }); +} - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } +function instrumentTtfb() { + return onTTFB.onTTFB(metric => { + triggerHandlers('ttfb', { + metric, + }); + _previousTtfb = metric; + }); +} - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level, value, false, false) || - (typeof value === 'undefined' && - writeNode(state, level, null, false, false))) { +function instrumentInp() { + return getINP.onINP(metric => { + triggerHandlers('inp', { + metric, + }); + _previousInp = metric; + }); +} - if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } +function addMetricObserver( + type, + callback, + instrumentFn, + previousValue, + stopOnCallback = false, +) { + addHandler(type, callback); + + let stopListening; + + if (!instrumented[type]) { + stopListening = instrumentFn(); + instrumented[type] = true; } - state.tag = _tag; - state.dump = '[' + _result + ']'; + if (previousValue) { + callback({ metric: previousValue }); + } + + return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined); } -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length, - value; +function instrumentPerformanceObserver(type) { + const options = {}; - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; + // Special per-type options we want to use + if (type === 'event') { + options.durationThreshold = 0; + } - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } + observe.observe( + type, + entries => { + triggerHandlers(type, { entries }); + }, + options, + ); +} - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level + 1, value, true, true, false, true) || - (typeof value === 'undefined' && - writeNode(state, level + 1, null, true, true, false, true))) { +function addHandler(type, handler) { + handlers[type] = handlers[type] || []; + (handlers[type] ).push(handler); +} - if (!compact || _result !== '') { - _result += generateNextLine(state, level); - } +// Get a callback which can be called to remove the instrumentation handler +function getCleanupCallback( + type, + callback, + stopListening, +) { + return () => { + if (stopListening) { + stopListening(); + } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } + const typeHandlers = handlers[type]; - _result += state.dump; + if (!typeHandlers) { + return; } - } - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. + const index = typeHandlers.indexOf(callback); + if (index !== -1) { + typeHandlers.splice(index, 1); + } + }; } -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; +exports.addClsInstrumentationHandler = addClsInstrumentationHandler; +exports.addFidInstrumentationHandler = addFidInstrumentationHandler; +exports.addInpInstrumentationHandler = addInpInstrumentationHandler; +exports.addLcpInstrumentationHandler = addLcpInstrumentationHandler; +exports.addPerformanceInstrumentationHandler = addPerformanceInstrumentationHandler; +exports.addTtfbInstrumentationHandler = addTtfbInstrumentationHandler; +//# sourceMappingURL=instrument.js.map - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - if (_result !== '') pairBuffer += ', '; +/***/ }), - if (state.condenseFlow) pairBuffer += '"'; +/***/ 5902: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const instrument = __nccwpck_require__(63187); +const types = __nccwpck_require__(29073); +const getVisibilityWatcher = __nccwpck_require__(17531); +const utils$1 = __nccwpck_require__(99551); +const getNavigationEntry = __nccwpck_require__(64453); - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; +const MAX_INT_AS_BYTES = 2147483647; + +/** + * Converts from milliseconds to seconds + * @param time time in ms + */ +function msToSec(time) { + return time / 1000; +} + +function getBrowserPerformanceAPI() { + // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are + return types.WINDOW && types.WINDOW.addEventListener && types.WINDOW.performance; +} + +let _performanceCursor = 0; + +let _measurements = {}; +let _lcpEntry; +let _clsEntry; + +/** + * Start tracking web vitals. + * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured. + * + * @returns A function that forces web vitals collection + */ +function startTrackingWebVitals() { + const performance = getBrowserPerformanceAPI(); + if (performance && utils.browserPerformanceTimeOrigin) { + // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are + if (performance.mark) { + types.WINDOW.performance.mark('sentry-tracing-init'); } + const fidCallback = _trackFID(); + const clsCallback = _trackCLS(); + const lcpCallback = _trackLCP(); + const ttfbCallback = _trackTtfb(); - if (state.dump.length > 1024) pairBuffer += '? '; + return () => { + fidCallback(); + clsCallback(); + lcpCallback(); + ttfbCallback(); + }; + } - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + return () => undefined; +} - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. +/** + * Start tracking long tasks. + */ +function startTrackingLongTasks() { + instrument.addPerformanceInstrumentationHandler('longtask', ({ entries }) => { + for (const entry of entries) { + // eslint-disable-next-line deprecation/deprecation + const transaction = core.getActiveTransaction() ; + if (!transaction) { + return; + } + const startTime = msToSec((utils.browserPerformanceTimeOrigin ) + entry.startTime); + const duration = msToSec(entry.duration); + + // eslint-disable-next-line deprecation/deprecation + transaction.startChild({ + description: 'Main UI thread blocked', + op: 'ui.long-task', + origin: 'auto.ui.browser.metrics', + startTimestamp: startTime, + endTimestamp: startTime + duration, + }); } + }); +} - pairBuffer += state.dump; +/** + * Start tracking interaction events. + */ +function startTrackingInteractions() { + instrument.addPerformanceInstrumentationHandler('event', ({ entries }) => { + for (const entry of entries) { + // eslint-disable-next-line deprecation/deprecation + const transaction = core.getActiveTransaction() ; + if (!transaction) { + return; + } - // Both key and value are valid. - _result += pairBuffer; - } + if (entry.name === 'click') { + const startTime = msToSec((utils.browserPerformanceTimeOrigin ) + entry.startTime); + const duration = msToSec(entry.duration); - state.tag = _tag; - state.dump = '{' + _result + '}'; + const span = { + description: utils.htmlTreeAsString(entry.target), + op: `ui.interaction.${entry.name}`, + origin: 'auto.ui.browser.metrics', + startTimestamp: startTime, + endTimestamp: startTime + duration, + }; + + const componentName = utils.getComponentName(entry.target); + if (componentName) { + span.attributes = { 'ui.component_name': componentName }; + } + + // eslint-disable-next-line deprecation/deprecation + transaction.startChild(span); + } + } + }); } -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; +/** + * Start tracking INP webvital events. + */ +function startTrackingINP( + interactionIdtoRouteNameMapping, + interactionsSampleRate, +) { + const performance = getBrowserPerformanceAPI(); + if (performance && utils.browserPerformanceTimeOrigin) { + const inpCallback = _trackINP(interactionIdtoRouteNameMapping, interactionsSampleRate); - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); + return () => { + inpCallback(); + }; } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; + return () => undefined; +} - if (!compact || _result !== '') { - pairBuffer += generateNextLine(state, level); +/** Starts tracking the Cumulative Layout Shift on the current page. */ +function _trackCLS() { + return instrument.addClsInstrumentationHandler(({ metric }) => { + const entry = metric.entries[metric.entries.length - 1]; + if (!entry) { + return; } - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding CLS'); + _measurements['cls'] = { value: metric.value, unit: '' }; + _clsEntry = entry ; + }, true); +} - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); +/** Starts tracking the Largest Contentful Paint on the current page. */ +function _trackLCP() { + return instrument.addLcpInstrumentationHandler(({ metric }) => { + const entry = metric.entries[metric.entries.length - 1]; + if (!entry) { + return; } - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding LCP'); + _measurements['lcp'] = { value: metric.value, unit: 'millisecond' }; + _lcpEntry = entry ; + }, true); +} + +/** Starts tracking the First Input Delay on the current page. */ +function _trackFID() { + return instrument.addFidInstrumentationHandler(({ metric }) => { + const entry = metric.entries[metric.entries.length - 1]; + if (!entry) { + return; } - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); + const timeOrigin = msToSec(utils.browserPerformanceTimeOrigin ); + const startTime = msToSec(entry.startTime); + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding FID'); + _measurements['fid'] = { value: metric.value, unit: 'millisecond' }; + _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' }; + }); +} - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } +function _trackTtfb() { + return instrument.addTtfbInstrumentationHandler(({ metric }) => { + const entry = metric.entries[metric.entries.length - 1]; + if (!entry) { + return; } - pairBuffer += state.dump; + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding TTFB'); + _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' }; + }); +} - if (explicitPair) { - pairBuffer += generateNextLine(state, level); +const INP_ENTRY_MAP = { + click: 'click', + pointerdown: 'click', + pointerup: 'click', + mousedown: 'click', + mouseup: 'click', + touchstart: 'click', + touchend: 'click', + mouseover: 'hover', + mouseout: 'hover', + mouseenter: 'hover', + mouseleave: 'hover', + pointerover: 'hover', + pointerout: 'hover', + pointerenter: 'hover', + pointerleave: 'hover', + dragstart: 'drag', + dragend: 'drag', + drag: 'drag', + dragenter: 'drag', + dragleave: 'drag', + dragover: 'drag', + drop: 'drag', + keydown: 'press', + keyup: 'press', + keypress: 'press', + input: 'press', +}; + +/** Starts tracking the Interaction to Next Paint on the current page. */ +function _trackINP( + interactionIdToRouteNameMapping, + interactionsSampleRate, +) { + return instrument.addInpInstrumentationHandler(({ metric }) => { + if (metric.value === undefined) { + return; } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. + const entry = metric.entries.find( + entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name] !== undefined, + ); + const client = core.getClient(); + if (!entry || !client) { + return; + } + const interactionType = INP_ENTRY_MAP[entry.name]; + const options = client.getOptions(); + /** Build the INP span, create an envelope from the span, and then send the envelope */ + const startTime = msToSec((utils.browserPerformanceTimeOrigin ) + entry.startTime); + const duration = msToSec(metric.value); + const interaction = + entry.interactionId !== undefined ? interactionIdToRouteNameMapping[entry.interactionId] : undefined; + if (interaction === undefined) { + return; } + const { routeName, parentContext, activeTransaction, user, replayId } = interaction; + const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined; + // eslint-disable-next-line deprecation/deprecation + const profileId = activeTransaction !== undefined ? activeTransaction.getProfileId() : undefined; + const span = new core.Span({ + startTimestamp: startTime, + endTimestamp: startTime + duration, + op: `ui.interaction.${interactionType}`, + name: utils.htmlTreeAsString(entry.target), + attributes: { + release: options.release, + environment: options.environment, + transaction: routeName, + ...(userDisplay !== undefined && userDisplay !== '' ? { user: userDisplay } : {}), + ...(profileId !== undefined ? { profile_id: profileId } : {}), + ...(replayId !== undefined ? { replay_id: replayId } : {}), + }, + exclusiveTime: metric.value, + measurements: { + inp: { value: metric.value, unit: 'millisecond' }, + }, + }); - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; + /** Check to see if the span should be sampled */ + const sampleRate = getSampleRate(parentContext, options, interactionsSampleRate); + + if (!sampleRate) { + return; } - pairBuffer += state.dump; + if (Math.random() < (sampleRate )) { + const envelope = span ? core.createSpanEnvelope([span], client.getDsn()) : undefined; + const transport = client && client.getTransport(); + if (transport && envelope) { + transport.send(envelope).then(null, reason => { + debugBuild.DEBUG_BUILD && utils.logger.error('Error while sending interaction:', reason); + }); + } + return; + } + }); +} - // Both key and value are valid. - _result += pairBuffer; +/** Add performance related spans to a transaction */ +function addPerformanceEntries(transaction) { + const performance = getBrowserPerformanceAPI(); + if (!performance || !types.WINDOW.performance.getEntries || !utils.browserPerformanceTimeOrigin) { + // Gatekeeper if performance API not available + return; } - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] Adding & adjusting spans using Performance API'); + const timeOrigin = msToSec(utils.browserPerformanceTimeOrigin); -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; + const performanceEntries = performance.getEntries(); - typeList = explicit ? state.explicitTypes : state.implicitTypes; + const { op, start_timestamp: transactionStartTime } = core.spanToJSON(transaction); - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + performanceEntries.slice(_performanceCursor).forEach((entry) => { + const startTime = msToSec(entry.startTime); + const duration = msToSec(entry.duration); - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { + // eslint-disable-next-line deprecation/deprecation + if (transaction.op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) { + return; + } - if (explicit) { - if (type.multi && type.representName) { - state.tag = type.representName(object); - } else { - state.tag = type.tag; - } - } else { - state.tag = '?'; + switch (entry.entryType) { + case 'navigation': { + _addNavigationSpans(transaction, entry, timeOrigin); + break; } + case 'mark': + case 'paint': + case 'measure': { + _addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; + // capture web vitals + const firstHidden = getVisibilityWatcher.getVisibilityWatcher(); + // Only report if the page wasn't hidden prior to the web vital. + const shouldRecord = entry.startTime < firstHidden.firstHiddenTime; - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + if (entry.name === 'first-paint' && shouldRecord) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding FP'); + _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' }; } + if (entry.name === 'first-contentful-paint' && shouldRecord) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding FCP'); + _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' }; + } + break; + } + case 'resource': { + _addResourceSpans(transaction, entry, entry.name , startTime, duration, timeOrigin); + break; + } + // Ignore other entry types. + } + }); - state.dump = _result; + _performanceCursor = Math.max(performanceEntries.length - 1, 0); + + _trackNavigator(transaction); + + // Measurements are only available for pageload transactions + if (op === 'pageload') { + _addTtfbRequestTimeToMeasurements(_measurements); + + ['fcp', 'fp', 'lcp'].forEach(name => { + if (!_measurements[name] || !transactionStartTime || timeOrigin >= transactionStartTime) { + return; } + // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. + // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need + // to be adjusted to be relative to transaction.startTimestamp. + const oldValue = _measurements[name].value; + const measurementTimestamp = timeOrigin + msToSec(oldValue); - return true; + // normalizedValue should be in milliseconds + const normalizedValue = Math.abs((measurementTimestamp - transactionStartTime) * 1000); + const delta = normalizedValue - oldValue; + + debugBuild.DEBUG_BUILD && utils.logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`); + _measurements[name].value = normalizedValue; + }); + + const fidMark = _measurements['mark.fid']; + if (fidMark && _measurements['fid']) { + // create span for FID + utils$1._startChild(transaction, { + description: 'first input delay', + endTimestamp: fidMark.value + msToSec(_measurements['fid'].value), + op: 'ui.action', + origin: 'auto.ui.browser.metrics', + startTimestamp: fidMark.value, + }); + + // Delete mark.fid as we don't want it to be part of final payload + delete _measurements['mark.fid']; } + + // If FCP is not recorded we should not record the cls value + // according to the new definition of CLS. + if (!('fcp' in _measurements)) { + delete _measurements.cls; + } + + Object.keys(_measurements).forEach(measurementName => { + core.setMeasurement(measurementName, _measurements[measurementName].value, _measurements[measurementName].unit); + }); + + _tagMetricInfo(transaction); } - return false; + _lcpEntry = undefined; + _clsEntry = undefined; + _measurements = {}; } -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey, isblockseq) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } +/** Create measure related spans */ +function _addMeasureSpans( + transaction, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + entry, + startTime, + duration, + timeOrigin, +) { + const measureStartTimestamp = timeOrigin + startTime; + const measureEndTimestamp = measureStartTimestamp + duration; + + utils$1._startChild(transaction, { + description: entry.name , + endTimestamp: measureEndTimestamp, + op: entry.entryType , + origin: 'auto.resource.browser.metrics', + startTimestamp: measureStartTimestamp, + }); - var type = _toString.call(state.dump); - var inblock = block; - var tagStr; + return measureStartTimestamp; +} - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); +/** Instrument navigation entries */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _addNavigationSpans(transaction, entry, timeOrigin) { + ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => { + _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin); + }); + _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd'); + _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart'); + _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS'); + _addRequest(transaction, entry, timeOrigin); +} + +/** Create performance navigation related spans */ +function _addPerformanceNavigationTiming( + transaction, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + entry, + event, + timeOrigin, + description, + eventEnd, +) { + const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] ); + const start = entry[`${event}Start`] ; + if (!start || !end) { + return; } + utils$1._startChild(transaction, { + op: 'browser', + origin: 'auto.browser.browser.metrics', + description: description || event, + startTimestamp: timeOrigin + msToSec(start), + endTimestamp: timeOrigin + msToSec(end), + }); +} - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; +/** Create request and response related spans */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _addRequest(transaction, entry, timeOrigin) { + if (entry.responseEnd) { + // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in. + // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0. + // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect + // these spans when the responseEnd value is available. The backend (Relay) would drop the entire transaction if it contained faulty spans. + utils$1._startChild(transaction, { + op: 'browser', + origin: 'auto.browser.browser.metrics', + description: 'request', + startTimestamp: timeOrigin + msToSec(entry.requestStart ), + endTimestamp: timeOrigin + msToSec(entry.responseEnd ), + }); - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; + utils$1._startChild(transaction, { + op: 'browser', + origin: 'auto.browser.browser.metrics', + description: 'response', + startTimestamp: timeOrigin + msToSec(entry.responseStart ), + endTimestamp: timeOrigin + msToSec(entry.responseEnd ), + }); } +} - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; +/** Create resource-related spans */ +function _addResourceSpans( + transaction, + entry, + resourceUrl, + startTime, + duration, + timeOrigin, +) { + // we already instrument based on fetch and xhr, so we don't need to + // duplicate spans here. + if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { + return; } - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - if (state.noArrayIndent && !isblockseq && level > 0) { - writeBlockSequence(state, level - 1, state.dump, compact); - } else { - writeBlockSequence(state, level, state.dump, compact); - } - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey, inblock); - } - } else if (type === '[object Undefined]') { - return false; - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - // Need to encode all characters except those allowed by the spec: - // - // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ - // [36] ns-hex-digit ::= ns-dec-digit - // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ - // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ - // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” - // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” - // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” - // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” - // - // Also need to encode '!' because it has special meaning (end of tag prefix). - // - tagStr = encodeURI( - state.tag[0] === '!' ? state.tag.slice(1) : state.tag - ).replace(/!/g, '%21'); + const parsedUrl = utils.parseUrl(resourceUrl); - if (state.tag[0] === '!') { - tagStr = '!' + tagStr; - } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { - tagStr = '!!' + tagStr.slice(18); - } else { - tagStr = '!<' + tagStr + '>'; - } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const data = {}; + setResourceEntrySizeData(data, entry, 'transferSize', 'http.response_transfer_size'); + setResourceEntrySizeData(data, entry, 'encodedBodySize', 'http.response_content_length'); + setResourceEntrySizeData(data, entry, 'decodedBodySize', 'http.decoded_response_content_length'); - state.dump = tagStr + ' ' + state.dump; - } + if ('renderBlockingStatus' in entry) { + data['resource.render_blocking_status'] = entry.renderBlockingStatus; + } + if (parsedUrl.protocol) { + data['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it. } - return true; -} + if (parsedUrl.host) { + data['server.address'] = parsedUrl.host; + } -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; + data['url.same_origin'] = resourceUrl.includes(types.WINDOW.location.origin); - inspectNode(object, objects, duplicatesIndexes); + const startTimestamp = timeOrigin + startTime; + const endTimestamp = startTimestamp + duration; - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); + utils$1._startChild(transaction, { + description: resourceUrl.replace(types.WINDOW.location.origin, ''), + endTimestamp, + op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other', + origin: 'auto.resource.browser.metrics', + startTimestamp, + data, + }); } -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; +/** + * Capture the information of the user agent. + */ +function _trackNavigator(transaction) { + const navigator = types.WINDOW.navigator ; + if (!navigator) { + return; + } - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); + // track network connectivity + const connection = navigator.connection; + if (connection) { + if (connection.effectiveType) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('effectiveConnectionType', connection.effectiveType); + } - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); + if (connection.type) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('connectionType', connection.type); + } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } + if (utils$1.isMeasurementValue(connection.rtt)) { + _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' }; } } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - var value = input; - if (state.replacer) { - value = state.replacer.call({ '': value }, '', value); + if (utils$1.isMeasurementValue(navigator.deviceMemory)) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`); } - if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; - - return ''; + if (utils$1.isMeasurementValue(navigator.hardwareConcurrency)) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); + } } -module.exports.dump = dump; - - -/***/ }), - -/***/ 30780: -/***/ ((module) => { - -"use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// +/** Add LCP / CLS data to transaction to allow debugging */ +function _tagMetricInfo(transaction) { + if (_lcpEntry) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding LCP Data'); + // Capture Properties of the LCP element that contributes to the LCP. + if (_lcpEntry.element) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('lcp.element', utils.htmlTreeAsString(_lcpEntry.element)); + } -function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; + if (_lcpEntry.id) { + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('lcp.id', _lcpEntry.id); + } - if (!exception.mark) return message; + if (_lcpEntry.url) { + // Trim URL to the first 200 characters. + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200)); + } - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag('lcp.size', _lcpEntry.size); } - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; + // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift + if (_clsEntry && _clsEntry.sources) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding CLS Data'); + _clsEntry.sources.forEach((source, index) => + // TODO: Can we rewrite this to an attribute? + // eslint-disable-next-line deprecation/deprecation + transaction.setTag(`cls.source.${index + 1}`, utils.htmlTreeAsString(source.node)), + ); } +} - return message + ' ' + where; +function setResourceEntrySizeData( + data, + entry, + key, + dataKey, +) { + const entryVal = entry[key]; + if (entryVal != null && entryVal < MAX_INT_AS_BYTES) { + data[dataKey] = entryVal; + } } +/** + * Add ttfb request time information to measurements. + * + * ttfb information is added via vendored web vitals library. + */ +function _addTtfbRequestTimeToMeasurements(_measurements) { + const navEntry = getNavigationEntry.getNavigationEntry(); + if (!navEntry) { + return; + } -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); + const { responseStart, requestStart } = navEntry; - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); + if (requestStart <= responseStart) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Measurements] Adding TTFB Request Time'); + _measurements['ttfb.requestTime'] = { + value: responseStart - requestStart, + unit: 'millisecond', + }; + } +} - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); +/** Taken from @sentry/core sampling.ts */ +function getSampleRate( + transactionContext, + options, + interactionsSampleRate, +) { + if (!core.hasTracingEnabled(options)) { + return false; + } + let sampleRate; + if (transactionContext !== undefined && typeof options.tracesSampler === 'function') { + sampleRate = options.tracesSampler({ + transactionContext, + name: transactionContext.name, + parentSampled: transactionContext.parentSampled, + attributes: { + // eslint-disable-next-line deprecation/deprecation + ...transactionContext.data, + ...transactionContext.attributes, + }, + location: types.WINDOW.location, + }); + } else if (transactionContext !== undefined && transactionContext.sampled !== undefined) { + sampleRate = transactionContext.sampled; + } else if (typeof options.tracesSampleRate !== 'undefined') { + sampleRate = options.tracesSampleRate; } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; + sampleRate = 1; + } + if (!core.isValidSampleRate(sampleRate)) { + debugBuild.DEBUG_BUILD && utils.logger.warn('[Tracing] Discarding interaction span because of invalid sample rate.'); + return false; + } + if (sampleRate === true) { + return interactionsSampleRate; + } else if (sampleRate === false) { + return 0; } + return sampleRate * interactionsSampleRate; } - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); -}; - - -module.exports = YAMLException; +exports._addMeasureSpans = _addMeasureSpans; +exports._addResourceSpans = _addResourceSpans; +exports.addPerformanceEntries = addPerformanceEntries; +exports.startTrackingINP = startTrackingINP; +exports.startTrackingInteractions = startTrackingInteractions; +exports.startTrackingLongTasks = startTrackingLongTasks; +exports.startTrackingWebVitals = startTrackingWebVitals; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 26106: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 99551: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Checks if a given value is a valid measurement value. + */ +function isMeasurementValue(value) { + return typeof value === 'number' && isFinite(value); +} -/*eslint-disable max-len,no-use-before-define*/ +/** + * Helper function to start child on transactions. This function will make sure that the transaction will + * use the start timestamp of the created child span if it is earlier than the transactions actual + * start timestamp. + * + * Note: this will not be possible anymore in v8, + * unless we do some special handling for browser here... + */ +function _startChild(transaction, { startTimestamp, ...ctx }) { + // eslint-disable-next-line deprecation/deprecation + if (startTimestamp && transaction.startTimestamp > startTimestamp) { + // eslint-disable-next-line deprecation/deprecation + transaction.startTimestamp = startTimestamp; + } + + // eslint-disable-next-line deprecation/deprecation + return transaction.startChild({ + startTimestamp, + ...ctx, + }); +} -var common = __nccwpck_require__(44828); -var YAMLException = __nccwpck_require__(30780); -var makeSnippet = __nccwpck_require__(68947); -var DEFAULT_SCHEMA = __nccwpck_require__(77599); +exports._startChild = _startChild; +exports.isMeasurementValue = isMeasurementValue; +//# sourceMappingURL=utils.js.map -var _hasOwnProperty = Object.prototype.hasOwnProperty; +/***/ }), +/***/ 15737: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const fetch = __nccwpck_require__(14165); +const instrument = __nccwpck_require__(63187); +const types = __nccwpck_require__(29073); -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; +/* eslint-disable max-lines */ +const DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\/(?!\/)/]; -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +/** Options for Request Instrumentation */ +const defaultRequestInstrumentationOptions = { + traceFetch: true, + traceXHR: true, + enableHTTPTimings: true, + // TODO (v8): Remove this property + tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS, + tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS, +}; -function _class(obj) { return Object.prototype.toString.call(obj); } +/** Registers span creators for xhr and fetch requests */ +function instrumentOutgoingRequests(_options) { + const { + traceFetch, + traceXHR, + // eslint-disable-next-line deprecation/deprecation + tracePropagationTargets, + // eslint-disable-next-line deprecation/deprecation + tracingOrigins, + shouldCreateSpanForRequest, + enableHTTPTimings, + } = { + traceFetch: defaultRequestInstrumentationOptions.traceFetch, + traceXHR: defaultRequestInstrumentationOptions.traceXHR, + ..._options, + }; -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} + const shouldCreateSpan = + typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true; + + // TODO(v8) Remove tracingOrigins here + // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported + // and we don't want to break the API. We can remove it in v8. + const shouldAttachHeadersWithTargets = (url) => + shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins); + + const spans = {}; + + if (traceFetch) { + utils.addFetchInstrumentationHandler(handlerData => { + const createdSpan = fetch.instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); + // We cannot use `window.location` in the generic fetch instrumentation, + // but we need it for reliable `server.address` attribute. + // so we extend this in here + if (createdSpan) { + const fullUrl = getFullURL(handlerData.fetchData.url); + const host = fullUrl ? utils.parseUrl(fullUrl).host : undefined; + createdSpan.setAttributes({ + 'http.url': fullUrl, + 'server.address': host, + }); + } -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} + if (enableHTTPTimings && createdSpan) { + addHTTPTimings(createdSpan); + } + }); + } -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); + if (traceXHR) { + utils.addXhrInstrumentationHandler(handlerData => { + const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans); + if (enableHTTPTimings && createdSpan) { + addHTTPTimings(createdSpan); + } + }); + } } -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; +function isPerformanceResourceTiming(entry) { + return ( + entry.entryType === 'resource' && + 'initiatorType' in entry && + typeof (entry ).nextHopProtocol === 'string' && + (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest') + ); } -function fromHexCode(c) { - var lc; +/** + * Creates a temporary observer to listen to the next fetch/xhr resourcing timings, + * so that when timings hit their per-browser limit they don't need to be removed. + * + * @param span A span that has yet to be finished, must contain `url` on data. + */ +function addHTTPTimings(span) { + const { url } = core.spanToJSON(span).data || {}; - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; + if (!url || typeof url !== 'string') { + return; } - /*eslint-disable no-bitwise*/ - lc = c | 0x20; + const cleanup = instrument.addPerformanceInstrumentationHandler('resource', ({ entries }) => { + entries.forEach(entry => { + if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) { + const spanData = resourceTimingEntryToSpanData(entry); + spanData.forEach(data => span.setAttribute(...data)); + // In the next tick, clean this handler up + // We have to wait here because otherwise this cleans itself up before it is fully done + setTimeout(cleanup); + } + }); + }); +} - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; +/** + * Converts ALPN protocol ids to name and version. + * + * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids) + * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol + */ +function extractNetworkProtocol(nextHopProtocol) { + let name = 'unknown'; + let version = 'unknown'; + let _name = ''; + for (const char of nextHopProtocol) { + // http/1.1 etc. + if (char === '/') { + [name, version] = nextHopProtocol.split('/'); + break; + } + // h2, h3 etc. + if (!isNaN(Number(char))) { + name = _name === 'h' ? 'http' : _name; + version = nextHopProtocol.split(_name)[1]; + break; + } + _name += char; } - - return -1; + if (_name === nextHopProtocol) { + // webrtc, ftp, etc. + name = _name; + } + return { name, version }; } -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; +function getAbsoluteTime(time = 0) { + return ((utils.browserPerformanceTimeOrigin || performance.timeOrigin) + time) / 1000; } -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } +function resourceTimingEntryToSpanData(resourceTiming) { + const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol); - return -1; -} + const timingSpanData = []; -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} + timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]); -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); + if (!utils.browserPerformanceTimeOrigin) { + return timingSpanData; } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); + return [ + ...timingSpanData, + ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)], + ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)], + ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)], + ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)], + ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)], + ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)], + ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)], + ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)], + ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)], + ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)], + ]; } -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); +/** + * A function that determines whether to attach tracing headers to a request. + * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders. + * We only export this fuction for testing purposes. + */ +function shouldAttachHeaders(url, tracePropagationTargets) { + return utils.stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS); } +/** + * Create and track xhr request spans + * + * @returns Span if a span was created, otherwise void. + */ +// eslint-disable-next-line complexity +function xhrCallback( + handlerData, + shouldCreateSpan, + shouldAttachHeaders, + spans, +) { + const xhr = handlerData.xhr; + const sentryXhrData = xhr && xhr[utils.SENTRY_XHR_DATA_KEY]; + + if (!core.hasTracingEnabled() || !xhr || xhr.__sentry_own_request__ || !sentryXhrData) { + return undefined; + } -function State(input, options) { - this.input = input; + const shouldCreateSpanResult = shouldCreateSpan(sentryXhrData.url); - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; + // check first if the request has finished and is tracked by an existing span which should now end + if (handlerData.endTimestamp && shouldCreateSpanResult) { + const spanId = xhr.__sentry_xhr_span_id__; + if (!spanId) return; - this.json = options['json'] || false; - this.listener = options['listener'] || null; + const span = spans[spanId]; + if (span && sentryXhrData.status_code !== undefined) { + core.setHttpStatus(span, sentryXhrData.status_code); + span.end(); - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[spanId]; + } + return undefined; + } - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; + const scope = core.getCurrentScope(); + const isolationScope = core.getIsolationScope(); - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; + const fullUrl = getFullURL(sentryXhrData.url); + const host = fullUrl ? utils.parseUrl(fullUrl).host : undefined; - this.documents = []; + const span = shouldCreateSpanResult + ? core.startInactiveSpan({ + name: `${sentryXhrData.method} ${sentryXhrData.url}`, + onlyIfParent: true, + attributes: { + type: 'xhr', + 'http.method': sentryXhrData.method, + 'http.url': fullUrl, + url: sentryXhrData.url, + 'server.address': host, + [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser', + }, + op: 'http.client', + }) + : undefined; - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ + if (span) { + xhr.__sentry_xhr_span_id__ = span.spanContext().spanId; + spans[xhr.__sentry_xhr_span_id__] = span; + } -} + const client = core.getClient(); + if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url) && client) { + const { traceId, spanId, sampled, dsc } = { + ...isolationScope.getPropagationContext(), + ...scope.getPropagationContext(), + }; -function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; + const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled); - mark.snippet = makeSnippet(mark); + const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader( + dsc || + (span ? core.getDynamicSamplingContextFromSpan(span) : core.getDynamicSamplingContextFromClient(traceId, client, scope)), + ); - return new YAMLException(message, mark); + setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader); + } + + return span; } -function throwError(state, message) { - throw generateError(state, message); +function setHeaderOnXhr( + xhr, + sentryTraceHeader, + sentryBaggageHeader, +) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + xhr.setRequestHeader('sentry-trace', sentryTraceHeader); + if (sentryBaggageHeader) { + // From MDN: "If this method is called several times with the same header, the values are merged into one single request header." + // We can therefore simply set a baggage header without checking what was there before + // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + xhr.setRequestHeader(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader); + } + } catch (_) { + // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. + } } -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); +function getFullURL(url) { + try { + // By adding a base URL to new URL(), this will also work for relative urls + // If `url` is a full URL, the base URL is ignored anyhow + const parsed = new URL(url, types.WINDOW.location.origin); + return parsed.href; + } catch (e) { + return undefined; } } +exports.DEFAULT_TRACE_PROPAGATION_TARGETS = DEFAULT_TRACE_PROPAGATION_TARGETS; +exports.defaultRequestInstrumentationOptions = defaultRequestInstrumentationOptions; +exports.extractNetworkProtocol = extractNetworkProtocol; +exports.instrumentOutgoingRequests = instrumentOutgoingRequests; +exports.shouldAttachHeaders = shouldAttachHeaders; +exports.xhrCallback = xhrCallback; +//# sourceMappingURL=request.js.map -var directiveHandlers = { - YAML: function handleYamlDirective(state, name, args) { +/***/ }), - var match, major, minor; +/***/ 99503: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const types = __nccwpck_require__(29073); - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); +/** + * Default function implementing pageload and navigation transactions + */ +function instrumentRoutingWithDefaults( + customStartTransaction, + startTransactionOnPageLoad = true, + startTransactionOnLocationChange = true, +) { + if (!types.WINDOW || !types.WINDOW.location) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Could not initialize routing instrumentation due to invalid location'); + return; + } - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } + let startingUrl = types.WINDOW.location.href; - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); + let activeTransaction; + if (startTransactionOnPageLoad) { + activeTransaction = customStartTransaction({ + name: types.WINDOW.location.pathname, + // pageload should always start at timeOrigin (and needs to be in s, not ms) + startTimestamp: utils.browserPerformanceTimeOrigin ? utils.browserPerformanceTimeOrigin / 1000 : undefined, + op: 'pageload', + origin: 'auto.pageload.browser', + metadata: { source: 'url' }, + }); + } - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } + if (startTransactionOnLocationChange) { + utils.addHistoryInstrumentationHandler(({ to, from }) => { + /** + * This early return is there to account for some cases where a navigation transaction starts right after + * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't + * create an uneccessary navigation transaction. + * + * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also + * only be caused in certain development environments where the usage of a hot module reloader is causing + * errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } - state.version = args[0]; - state.checkLineBreaks = (minor < 2); + if (from !== to) { + startingUrl = undefined; + if (activeTransaction) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`); + // If there's an open transaction on the scope, we need to finish it before creating an new one. + activeTransaction.end(); + } + activeTransaction = customStartTransaction({ + name: types.WINDOW.location.pathname, + op: 'navigation', + origin: 'auto.navigation.browser', + metadata: { source: 'url' }, + }); + } + }); + } +} - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, +exports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults; +//# sourceMappingURL=router.js.map - TAG: function handleTagDirective(state, name, args) { - var handle, prefix; +/***/ }), - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } +/***/ 29073: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - handle = args[0]; - prefix = args[1]; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } +const utils = __nccwpck_require__(25304); - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } +const WINDOW = utils.GLOBAL_OBJ - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } +; - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); - } +exports.WINDOW = WINDOW; +//# sourceMappingURL=types.js.map - state.tagMap[handle] = prefix; - } -}; +/***/ }), -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; +/***/ 76435: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (start < end) { - _result = state.input.slice(start, end); +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); +const bindReporter = __nccwpck_require__(3097); +const initMetric = __nccwpck_require__(28613); +const observe = __nccwpck_require__(80215); +const onHidden = __nccwpck_require__(43330); + +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Calculates the [CLS](https://web.dev/cls/) value for the current page and + * calls the `callback` function once the value is ready to be reported, along + * with all `layout-shift` performance entries that were used in the metric + * value calculation. The reported value is a `double` (corresponding to a + * [layout shift score](https://web.dev/cls/#layout-shift-score)). + * + * If the `reportAllChanges` configuration option is set to `true`, the + * `callback` function will be called as soon as the value is initially + * determined as well as any time the value changes throughout the page + * lifespan. + * + * _**Important:** CLS should be continually monitored for changes throughout + * the entire lifespan of a page—including if the user returns to the page after + * it's been hidden/backgrounded. However, since browsers often [will not fire + * additional callbacks once the user has backgrounded a + * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), + * `callback` is always called when the page's visibility state changes to + * hidden. As a result, the `callback` function might be called multiple times + * during the same page load._ + */ +const onCLS = ( + onReport, + options = {}, +) => { + const metric = initMetric.initMetric('CLS', 0); + let report; + + let sessionValue = 0; + let sessionEntries = []; + + // const handleEntries = (entries: Metric['entries']) => { + const handleEntries = (entries) => { + entries.forEach(entry => { + // Only count layout shifts without recent user input. + if (!entry.hadRecentInput) { + const firstSessionEntry = sessionEntries[0]; + const lastSessionEntry = sessionEntries[sessionEntries.length - 1]; + + // If the entry occurred less than 1 second after the previous entry and + // less than 5 seconds after the first entry in the session, include the + // entry in the current session. Otherwise, start a new session. + if ( + sessionValue && + sessionEntries.length !== 0 && + entry.startTime - lastSessionEntry.startTime < 1000 && + entry.startTime - firstSessionEntry.startTime < 5000 + ) { + sessionValue += entry.value; + sessionEntries.push(entry); + } else { + sessionValue = entry.value; + sessionEntries = [entry]; + } + + // If the current session value is larger than the current CLS value, + // update CLS and the entries contributing to it. + if (sessionValue > metric.value) { + metric.value = sessionValue; + metric.entries = sessionEntries; + if (report) { + report(); + } } } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } + }); + }; - state.result += _result; - } -} + const po = observe.observe('layout-shift', handleEntries); + if (po) { + report = bindReporter.bindReporter(onReport, metric, options.reportAllChanges); -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; + const stopListening = () => { + handleEntries(po.takeRecords() ); + report(true); + }; - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + onHidden.onHidden(stopListening); + + return stopListening; } - sourceKeys = Object.keys(source); + return; +}; - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; +exports.onCLS = onCLS; +//# sourceMappingURL=getCLS.js.map - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } -} -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { +/***/ }), - var index, quantity; +/***/ 27308: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); +Object.defineProperty(exports, "__esModule", ({ value: true })); - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } +const bindReporter = __nccwpck_require__(3097); +const getVisibilityWatcher = __nccwpck_require__(17531); +const initMetric = __nccwpck_require__(28613); +const observe = __nccwpck_require__(80215); +const onHidden = __nccwpck_require__(43330); - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } +/** + * Calculates the [FID](https://web.dev/fid/) value for the current page and + * calls the `callback` function once the value is ready, along with the + * relevant `first-input` performance entry used to determine the value. The + * reported value is a `DOMHighResTimeStamp`. + * + * _**Important:** since FID is only reported after the user interacts with the + * page, it's possible that it will not be reported for some page loads._ + */ +const onFID = (onReport) => { + const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher(); + const metric = initMetric.initMetric('FID'); + // eslint-disable-next-line prefer-const + let report; + const handleEntry = (entry) => { + // Only report if the page wasn't hidden prior to the first input. + if (entry.startTime < visibilityWatcher.firstHiddenTime) { + metric.value = entry.processingStart - entry.startTime; + metric.entries.push(entry); + report(true); + } + }; - keyNode = String(keyNode); + const handleEntries = (entries) => { + (entries ).forEach(handleEntry); + }; - if (_result === null) { - _result = {}; + const po = observe.observe('first-input', handleEntries); + report = bindReporter.bindReporter(onReport, metric); + + if (po) { + onHidden.onHidden(() => { + handleEntries(po.takeRecords() ); + po.disconnect(); + }, true); } +}; - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } +exports.onFID = onFID; +//# sourceMappingURL=getFID.js.map - // used for this specific key only because Object.defineProperty is slow - if (keyNode === '__proto__') { - Object.defineProperty(_result, keyNode, { - configurable: true, - enumerable: true, - writable: true, - value: valueNode - }); - } else { - _result[keyNode] = valueNode; - } - delete overridableKeys[keyNode]; - } - return _result; -} +/***/ }), -function readLineBreak(state) { - var ch; +/***/ 83462: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ch = state.input.charCodeAt(state.position); +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } +const bindReporter = __nccwpck_require__(3097); +const initMetric = __nccwpck_require__(28613); +const observe = __nccwpck_require__(80215); +const onHidden = __nccwpck_require__(43330); +const interactionCountPolyfill = __nccwpck_require__(87714); - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; -} +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); +/** + * Returns the interaction count since the last bfcache restore (or for the + * full page lifecycle if there were no bfcache restores). + */ +const getInteractionCountForNavigation = () => { + return interactionCountPolyfill.getInteractionCount(); +}; - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); - } +// To prevent unnecessary memory usage on pages with lots of interactions, +// store at most 10 of the longest interactions to consider as INP candidates. +const MAX_INTERACTIONS_TO_CONSIDER = 10; - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } +// A list of longest interactions on the page (by latency) sorted so the +// longest one is first. The list is as most MAX_INTERACTIONS_TO_CONSIDER long. +const longestInteractionList = []; - if (is_EOL(ch)) { - readLineBreak(state); +// A mapping of longest interactions by their interaction ID. +// This is used for faster lookup. +const longestInteractionMap = {}; - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; +/** + * Takes a performance entry and adds it to the list of worst interactions + * if its duration is long enough to make it among the worst. If the + * entry is part of an existing interaction, it is merged and the latency + * and entries list is updated as needed. + */ +const processEntry = (entry) => { + // The least-long of the 10 longest interactions. + const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1]; - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const existingInteraction = longestInteractionMap[entry.interactionId]; + + // Only process the entry if it's possibly one of the ten longest, + // or if it's part of an existing interaction. + if ( + existingInteraction || + longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER || + entry.duration > minLongestInteraction.latency + ) { + // If the interaction already exists, update it. Otherwise create one. + if (existingInteraction) { + existingInteraction.entries.push(entry); + existingInteraction.latency = Math.max(existingInteraction.latency, entry.duration); } else { - break; + const interaction = { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + id: entry.interactionId, + latency: entry.duration, + entries: [entry], + }; + longestInteractionMap[interaction.id] = interaction; + longestInteractionList.push(interaction); } - } - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); + // Sort the entries by latency (descending) and keep only the top ten. + longestInteractionList.sort((a, b) => b.latency - a.latency); + longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete longestInteractionMap[i.id]; + }); } +}; - return lineBreaks; -} - -function testDocumentSeparator(state) { - var _position = state.position, - ch; +/** + * Returns the estimated p98 longest interaction based on the stored + * interaction candidates and the interaction count for the current page. + */ +const estimateP98LongestInteraction = () => { + const candidateInteractionIndex = Math.min( + longestInteractionList.length - 1, + Math.floor(getInteractionCountForNavigation() / 50), + ); - ch = state.input.charCodeAt(_position); + return longestInteractionList[candidateInteractionIndex]; +}; - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { +/** + * Calculates the [INP](https://web.dev/responsiveness/) value for the current + * page and calls the `callback` function once the value is ready, along with + * the `event` performance entries reported for that interaction. The reported + * value is a `DOMHighResTimeStamp`. + * + * A custom `durationThreshold` configuration option can optionally be passed to + * control what `event-timing` entries are considered for INP reporting. The + * default threshold is `40`, which means INP scores of less than 40 are + * reported as 0. Note that this will not affect your 75th percentile INP value + * unless that value is also less than 40 (well below the recommended + * [good](https://web.dev/inp/#what-is-a-good-inp-score) threshold). + * + * If the `reportAllChanges` configuration option is set to `true`, the + * `callback` function will be called as soon as the value is initially + * determined as well as any time the value changes throughout the page + * lifespan. + * + * _**Important:** INP should be continually monitored for changes throughout + * the entire lifespan of a page—including if the user returns to the page after + * it's been hidden/backgrounded. However, since browsers often [will not fire + * additional callbacks once the user has backgrounded a + * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden), + * `callback` is always called when the page's visibility state changes to + * hidden. As a result, the `callback` function might be called multiple times + * during the same page load._ + */ +const onINP = (onReport, opts) => { + // Set defaults + // eslint-disable-next-line no-param-reassign + opts = opts || {}; - _position += 3; + // https://web.dev/inp/#what's-a-%22good%22-inp-value + // const thresholds = [200, 500]; + + // TODO(philipwalton): remove once the polyfill is no longer needed. + interactionCountPolyfill.initInteractionCountPolyfill(); + + const metric = initMetric.initMetric('INP'); + // eslint-disable-next-line prefer-const + let report; + + const handleEntries = (entries) => { + entries.forEach(entry => { + if (entry.interactionId) { + processEntry(entry); + } + + // Entries of type `first-input` don't currently have an `interactionId`, + // so to consider them in INP we have to first check that an existing + // entry doesn't match the `duration` and `startTime`. + // Note that this logic assumes that `event` entries are dispatched + // before `first-input` entries. This is true in Chrome but it is not + // true in Firefox; however, Firefox doesn't support interactionId, so + // it's not an issue at the moment. + // TODO(philipwalton): remove once crbug.com/1325826 is fixed. + if (entry.entryType === 'first-input') { + const noMatchingEntry = !longestInteractionList.some(interaction => { + return interaction.entries.some(prevEntry => { + return entry.duration === prevEntry.duration && entry.startTime === prevEntry.startTime; + }); + }); + if (noMatchingEntry) { + processEntry(entry); + } + } + }); - ch = state.input.charCodeAt(_position); + const inp = estimateP98LongestInteraction(); - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; + if (inp && inp.latency !== metric.value) { + metric.value = inp.latency; + metric.entries = inp.entries; + report(); } - } + }; - return false; -} + const po = observe.observe('event', handleEntries, { + // Event Timing entries have their durations rounded to the nearest 8ms, + // so a duration of 40ms would be any event that spans 2.5 or more frames + // at 60Hz. This threshold is chosen to strike a balance between usefulness + // and performance. Running this callback for any interaction that spans + // just one or two frames is likely not worth the insight that could be + // gained. + durationThreshold: opts.durationThreshold || 40, + } ); -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} + report = bindReporter.bindReporter(onReport, metric, opts.reportAllChanges); + if (po) { + // Also observe entries of type `first-input`. This is useful in cases + // where the first interaction is less than the `durationThreshold`. + po.observe({ type: 'first-input', buffered: true }); -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; + onHidden.onHidden(() => { + handleEntries(po.takeRecords() ); - ch = state.input.charCodeAt(state.position); + // If the interaction count shows that there were interactions but + // none were captured by the PerformanceObserver, report a latency of 0. + if (metric.value < 0 && getInteractionCountForNavigation() > 0) { + metric.value = 0; + metric.entries = []; + } - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; + report(true); + }); } +}; - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); +exports.onINP = onINP; +//# sourceMappingURL=getINP.js.map - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; +/***/ }), - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); +/***/ 48404: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); +const types = __nccwpck_require__(29073); +const bindReporter = __nccwpck_require__(3097); +const getActivationStart = __nccwpck_require__(77563); +const getVisibilityWatcher = __nccwpck_require__(17531); +const initMetric = __nccwpck_require__(28613); +const observe = __nccwpck_require__(80215); +const onHidden = __nccwpck_require__(43330); - if (is_WS_OR_EOL(preceding)) { - break; - } +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; +const reportedMetricIDs = {}; - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); +/** + * Calculates the [LCP](https://web.dev/lcp/) value for the current page and + * calls the `callback` function once the value is ready (along with the + * relevant `largest-contentful-paint` performance entry used to determine the + * value). The reported value is a `DOMHighResTimeStamp`. + */ +const onLCP = (onReport) => { + const visibilityWatcher = getVisibilityWatcher.getVisibilityWatcher(); + const metric = initMetric.initMetric('LCP'); + let report; - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; + const handleEntries = (entries) => { + const lastEntry = entries[entries.length - 1] ; + if (lastEntry) { + // The startTime attribute returns the value of the renderTime if it is + // not 0, and the value of the loadTime otherwise. The activationStart + // reference is used because LCP should be relative to page activation + // rather than navigation start if the page was prerendered. + const value = Math.max(lastEntry.startTime - getActivationStart.getActivationStart(), 0); + + // Only report if the page wasn't hidden prior to LCP. + if (value < visibilityWatcher.firstHiddenTime) { + metric.value = value; + metric.entries = [lastEntry]; + report(); } } + }; - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } + const po = observe.observe('largest-contentful-paint', handleEntries); - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } + if (po) { + report = bindReporter.bindReporter(onReport, metric); - ch = state.input.charCodeAt(++state.position); - } + const stopListening = () => { + if (!reportedMetricIDs[metric.id]) { + handleEntries(po.takeRecords() ); + po.disconnect(); + reportedMetricIDs[metric.id] = true; + report(true); + } + }; - captureSegment(state, captureStart, captureEnd, false); + // Stop listening after input. Note: while scrolling is an input that + // stop LCP observation, it's unreliable since it can be programmatically + // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75 + ['keydown', 'click'].forEach(type => { + if (types.WINDOW.document) { + addEventListener(type, stopListening, { once: true, capture: true }); + } + }); - if (state.result) { - return true; + onHidden.onHidden(stopListening, true); + + return stopListening; } - state.kind = _kind; - state.result = _result; - return false; -} + return; +}; -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; +exports.onLCP = onLCP; +//# sourceMappingURL=getLCP.js.map - ch = state.input.charCodeAt(state.position); - if (ch !== 0x27/* ' */) { - return false; - } +/***/ }), - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; +/***/ 3097: +/***/ ((__unused_webpack_module, exports) => { - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; +const bindReporter = ( + callback, + metric, + reportAllChanges, +) => { + let prevValue; + let delta; + return (forceReport) => { + if (metric.value >= 0) { + if (forceReport || reportAllChanges) { + delta = metric.value - (prevValue || 0); + + // Report the metric if there's a non-zero delta or if no previous + // value exists (which can happen in the case of the document becoming + // hidden when the metric value is 0). + // See: https://github.com/GoogleChrome/web-vitals/issues/14 + if (delta || prevValue === undefined) { + prevValue = metric.value; + metric.delta = delta; + callback(metric); + } } + } + }; +}; - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); +exports.bindReporter = bindReporter; +//# sourceMappingURL=bindReporter.js.map - } else { - state.position++; - captureEnd = state.position; - } - } - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} +/***/ }), -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; +/***/ 15214: +/***/ ((__unused_webpack_module, exports) => { - ch = state.input.charCodeAt(state.position); +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (ch !== 0x22/* " */) { - return false; - } +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; +/** + * Performantly generate a unique, 30-char string by combining a version + * number, the current timestamp with a 13-digit number integer. + * @return {string} + */ +const generateUniqueID = () => { + return `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`; +}; - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; +exports.generateUniqueID = generateUniqueID; +//# sourceMappingURL=generateUniqueID.js.map - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); +/***/ }), - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; +/***/ 77563: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); +const getNavigationEntry = __nccwpck_require__(64453); - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - } else { - throwError(state, 'expected hexadecimal character'); - } - } +const getActivationStart = () => { + const navEntry = getNavigationEntry.getNavigationEntry(); + return (navEntry && navEntry.activationStart) || 0; +}; - state.result += charFromCodepoint(hexResult); +exports.getActivationStart = getActivationStart; +//# sourceMappingURL=getActivationStart.js.map - state.position++; - } else { - throwError(state, 'unknown escape sequence'); - } +/***/ }), - captureStart = captureEnd = state.position; +/***/ 64453: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; +Object.defineProperty(exports, "__esModule", ({ value: true })); - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); +const types = __nccwpck_require__(29073); - } else { - state.position++; - captureEnd = state.position; - } - } +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} +const getNavigationEntryFromPerformanceTiming = () => { + // eslint-disable-next-line deprecation/deprecation + const timing = types.WINDOW.performance.timing; + // eslint-disable-next-line deprecation/deprecation + const type = types.WINDOW.performance.navigation.type; -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; + const navigationEntry = { + entryType: 'navigation', + startTime: 0, + type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate', + }; - ch = state.input.charCodeAt(state.position); + for (const key in timing) { + if (key !== 'navigationStart' && key !== 'toJSON') { + // eslint-disable-next-line deprecation/deprecation + navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0); + } + } + return navigationEntry ; +}; - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; +const getNavigationEntry = () => { + if (types.WINDOW.__WEB_VITALS_POLYFILL__) { + return ( + types.WINDOW.performance && + ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) || + getNavigationEntryFromPerformanceTiming()) + ); } else { - return false; + return types.WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0]; } +}; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } +exports.getNavigationEntry = getNavigationEntry; +//# sourceMappingURL=getNavigationEntry.js.map - ch = state.input.charCodeAt(++state.position); - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; +/***/ }), - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); +/***/ 17531: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); +const types = __nccwpck_require__(29073); +const onHidden = __nccwpck_require__(43330); - ch = state.input.charCodeAt(state.position); +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } +let firstHiddenTime = -1; - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } +const initHiddenTime = () => { + // If the document is hidden and not prerendering, assume it was always + // hidden and the page was loaded in the background. + if (types.WINDOW.document && types.WINDOW.document.visibilityState) { + firstHiddenTime = types.WINDOW.document.visibilityState === 'hidden' && !types.WINDOW.document.prerendering ? 0 : Infinity; + } +}; - skipSeparationSpace(state, true, nodeIndent); +const trackChanges = () => { + // Update the time if/when the document becomes hidden. + onHidden.onHidden(({ timeStamp }) => { + firstHiddenTime = timeStamp; + }, true); +}; - ch = state.input.charCodeAt(state.position); +const getVisibilityWatcher = ( - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } +) => { + if (firstHiddenTime < 0) { + // If the document is hidden when this code runs, assume it was hidden + // since navigation start. This isn't a perfect heuristic, but it's the + // best we can do until an API is available to support querying past + // visibilityState. + initHiddenTime(); + trackChanges(); } + return { + get firstHiddenTime() { + return firstHiddenTime; + }, + }; +}; - throwError(state, 'unexpected end of the stream within a flow collection'); -} +exports.getVisibilityWatcher = getVisibilityWatcher; +//# sourceMappingURL=getVisibilityWatcher.js.map -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - ch = state.input.charCodeAt(state.position); +/***/ }), - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } +/***/ 28613: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - state.kind = 'scalar'; - state.result = ''; +Object.defineProperty(exports, "__esModule", ({ value: true })); - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); +const types = __nccwpck_require__(29073); +const generateUniqueID = __nccwpck_require__(15214); +const getActivationStart = __nccwpck_require__(77563); +const getNavigationEntry = __nccwpck_require__(64453); - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } +const initMetric = (name, value) => { + const navEntry = getNavigationEntry.getNavigationEntry(); + let navigationType = 'navigate'; + if (navEntry) { + if ((types.WINDOW.document && types.WINDOW.document.prerendering) || getActivationStart.getActivationStart() > 0) { + navigationType = 'prerender'; } else { - break; + navigationType = navEntry.type.replace(/_/g, '-') ; } } - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); + return { + name, + value: typeof value === 'undefined' ? -1 : value, + rating: 'good', // Will be updated if the value changes. + delta: 0, + entries: [], + id: generateUniqueID.generateUniqueID(), + navigationType, + }; +}; - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } +exports.initMetric = initMetric; +//# sourceMappingURL=initMetric.js.map - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - ch = state.input.charCodeAt(state.position); +/***/ }), - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } +/***/ 80215: +/***/ ((__unused_webpack_module, exports) => { - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (is_EOL(ch)) { - emptyLines++; - continue; +/** + * Takes a performance entry type and a callback function, and creates a + * `PerformanceObserver` instance that will observe the specified entry type + * with buffering enabled and call the callback _for each entry_. + * + * This function also feature-detects entry support and wraps the logic in a + * try/catch to avoid errors in unsupporting browsers. + */ +const observe = ( + type, + callback, + opts, +) => { + try { + if (PerformanceObserver.supportedEntryTypes.includes(type)) { + const po = new PerformanceObserver(list => { + callback(list.getEntries() ); + }); + po.observe( + Object.assign( + { + type, + buffered: true, + }, + opts || {}, + ) , + ); + return po; } + } catch (e) { + // Do nothing. + } + return; +}; - // End of the scalar. - if (state.lineIndent < textIndent) { +exports.observe = observe; +//# sourceMappingURL=observe.js.map - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - // Break this `while` cycle and go to the funciton's epilogue. - break; - } +/***/ }), - // Folded style: use fancy rules to handle line breaks. - if (folding) { +/***/ 43330: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); +Object.defineProperty(exports, "__esModule", ({ value: true })); - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); +const types = __nccwpck_require__(29073); - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); +const onHidden = (cb, once) => { + const onHiddenOrPageHide = (event) => { + if (event.type === 'pagehide' || types.WINDOW.document.visibilityState === 'hidden') { + cb(event); + if (once) { + removeEventListener('visibilitychange', onHiddenOrPageHide, true); + removeEventListener('pagehide', onHiddenOrPageHide, true); } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } + }; - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; + if (types.WINDOW.document) { + addEventListener('visibilitychange', onHiddenOrPageHide, true); + // Some browsers have buggy implementations of visibilitychange, + // so we use pagehide in addition, just to be safe. + addEventListener('pagehide', onHiddenOrPageHide, true); + } +}; - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } +exports.onHidden = onHidden; +//# sourceMappingURL=onHidden.js.map - captureSegment(state, captureStart, state.position, false); - } - return true; -} +/***/ }), -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; +/***/ 87714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } +const observe = __nccwpck_require__(80215); - ch = state.input.charCodeAt(state.position); +let interactionCountEstimate = 0; +let minKnownInteractionId = Infinity; +let maxKnownInteractionId = 0; - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } +const updateEstimate = (entries) => { + (entries ).forEach(e => { + if (e.interactionId) { + minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId); + maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId); - if (ch !== 0x2D/* - */) { - break; + interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0; } + }); +}; - following = state.input.charCodeAt(state.position + 1); +let po; - if (!is_WS_OR_EOL(following)) { - break; - } +/** + * Returns the `interactionCount` value using the native API (if available) + * or the polyfill estimate in this module. + */ +const getInteractionCount = () => { + return po ? interactionCountEstimate : performance.interactionCount || 0; +}; - detected = true; - state.position++; +/** + * Feature detects native support or initializes the polyfill if needed. + */ +const initInteractionCountPolyfill = () => { + if ('interactionCount' in performance || po) return; - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } + po = observe.observe('event', updateEstimate, { + type: 'event', + buffered: true, + durationThreshold: 0, + } ); +}; - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); +exports.getInteractionCount = getInteractionCount; +exports.initInteractionCountPolyfill = initInteractionCountPolyfill; +//# sourceMappingURL=interactionCountPolyfill.js.map - ch = state.input.charCodeAt(state.position); - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } +/***/ }), + +/***/ 18146: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const types = __nccwpck_require__(29073); +const bindReporter = __nccwpck_require__(3097); +const getActivationStart = __nccwpck_require__(77563); +const getNavigationEntry = __nccwpck_require__(64453); +const initMetric = __nccwpck_require__(28613); + +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Runs in the next task after the page is done loading and/or prerendering. + * @param callback + */ +const whenReady = (callback) => { + if (!types.WINDOW.document) { + return; } - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; + if (types.WINDOW.document.prerendering) { + addEventListener('prerenderingchange', () => whenReady(callback), true); + } else if (types.WINDOW.document.readyState !== 'complete') { + addEventListener('load', () => whenReady(callback), true); + } else { + // Queue a task so the callback runs after `loadEventEnd`. + setTimeout(callback, 0); } - return false; -} +}; -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; +/** + * Calculates the [TTFB](https://web.dev/time-to-first-byte/) value for the + * current page and calls the `callback` function once the page has loaded, + * along with the relevant `navigation` performance entry used to determine the + * value. The reported value is a `DOMHighResTimeStamp`. + * + * Note, this function waits until after the page is loaded to call `callback` + * in order to ensure all properties of the `navigation` entry are populated. + * This is useful if you want to report on other metrics exposed by the + * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For + * example, the TTFB metric starts from the page's [time + * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it + * includes time spent on DNS lookup, connection negotiation, network latency, + * and server processing time. + */ +const onTTFB = (onReport, opts) => { + // Set defaults + // eslint-disable-next-line no-param-reassign + opts = opts || {}; - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; + // https://web.dev/ttfb/#what-is-a-good-ttfb-score + // const thresholds = [800, 1800]; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } + const metric = initMetric.initMetric('TTFB'); + const report = bindReporter.bindReporter(onReport, metric, opts.reportAllChanges); - ch = state.input.charCodeAt(state.position); + whenReady(() => { + const navEntry = getNavigationEntry.getNavigationEntry() ; - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } + if (navEntry) { + // The activationStart reference is used because TTFB should be + // relative to page activation rather than navigation start if the + // page was prerendered. But in cases where `activationStart` occurs + // after the first byte is received, this time should be clamped at 0. + metric.value = Math.max(navEntry.responseStart - getActivationStart.getActivationStart(), 0); - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. + // In some cases the value reported is negative or is larger + // than the current page time. Ignore these cases: + // https://github.com/GoogleChrome/web-vitals/issues/137 + // https://github.com/GoogleChrome/web-vitals/issues/162 + if (metric.value < 0 || metric.value > performance.now()) return; - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + metric.entries = [navEntry]; - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + report(true); + } + }); +}; - detected = true; - atExplicitKey = true; - allowCompact = true; +exports.onTTFB = onTTFB; +//# sourceMappingURL=onTTFB.js.map - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } +/***/ }), - state.position += 1; - ch = following; +/***/ 80411: +/***/ ((__unused_webpack_module, exports) => { - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } +/** + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. + * + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. + */ +const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); +exports.DEBUG_BUILD = DEBUG_BUILD; +//# sourceMappingURL=debug-build.js.map - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); +/***/ }), - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } +/***/ 14165: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); +/** + * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`. + * + * @returns Span if a span was created, otherwise void. + */ +function instrumentFetchRequest( + handlerData, + shouldCreateSpan, + shouldAttachHeaders, + spans, + spanOrigin = 'auto.http.browser', +) { + if (!core.hasTracingEnabled() || !handlerData.fetchData) { + return undefined; + } - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } + const shouldCreateSpanResult = shouldCreateSpan(handlerData.fetchData.url); - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + if (handlerData.endTimestamp && shouldCreateSpanResult) { + const spanId = handlerData.fetchData.__span; + if (!spanId) return; - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } + const span = spans[spanId]; + if (span) { + endSpan(span, handlerData); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[spanId]; } + return undefined; + } - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } + const scope = core.getCurrentScope(); + const client = core.getClient(); - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } + const { method, url } = handlerData.fetchData; - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } + const fullUrl = getFullURL(url); + const host = fullUrl ? utils.parseUrl(fullUrl).host : undefined; - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } + const span = shouldCreateSpanResult + ? core.startInactiveSpan({ + name: `${method} ${url}`, + onlyIfParent: true, + attributes: { + url, + type: 'fetch', + 'http.method': method, + 'http.url': fullUrl, + 'server.address': host, + [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin, + }, + op: 'http.client', + }) + : undefined; - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } + if (span) { + handlerData.fetchData.__span = span.spanContext().spanId; + spans[span.spanContext().spanId] = span; } - // - // Epilogue. - // + if (shouldAttachHeaders(handlerData.fetchData.url) && client) { + const request = handlerData.args[0]; - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } + // In case the user hasn't set the second argument of a fetch call we default it to `{}`. + handlerData.args[1] = handlerData.args[1] || {}; - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const options = handlerData.args[1]; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access + options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span); } - return detected; + return span; } -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; +/** + * Adds sentry-trace and baggage headers to the various forms of fetch headers + */ +function addTracingHeadersToFetchRequest( + request, // unknown is actually type Request but we can't export DOM types from this package, + client, + scope, + options - ch = state.input.charCodeAt(state.position); +, + requestSpan, +) { + // eslint-disable-next-line deprecation/deprecation + const span = requestSpan || scope.getSpan(); - if (ch !== 0x21/* ! */) return false; + const isolationScope = core.getIsolationScope(); - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } + const { traceId, spanId, sampled, dsc } = { + ...isolationScope.getPropagationContext(), + ...scope.getPropagationContext(), + }; - ch = state.input.charCodeAt(++state.position); + const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled); - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); + const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader( + dsc || + (span ? core.getDynamicSamplingContextFromSpan(span) : core.getDynamicSamplingContextFromClient(traceId, client, scope)), + ); - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); + const headers = + options.headers || + (typeof Request !== 'undefined' && utils.isInstanceOf(request, Request) ? (request ).headers : undefined); - } else { - tagHandle = '!'; - } + if (!headers) { + return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader }; + } else if (typeof Headers !== 'undefined' && utils.isInstanceOf(headers, Headers)) { + const newHeaders = new Headers(headers ); - _position = state.position; + newHeaders.append('sentry-trace', sentryTraceHeader); - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); + if (sentryBaggageHeader) { + // If the same header is appended multiple times the browser will merge the values into a single request header. + // Its therefore safe to simply push a "baggage" entry, even though there might already be another baggage header. + newHeaders.append(utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader); + } - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); + return newHeaders ; + } else if (Array.isArray(headers)) { + const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]]; - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } + if (sentryBaggageHeader) { + // If there are multiple entries with the same key, the browser will merge the values into a single request header. + // Its therefore safe to simply push a "baggage" entry, even though there might already be another baggage header. + newHeaders.push([utils.BAGGAGE_HEADER_NAME, sentryBaggageHeader]); + } - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } + return newHeaders ; + } else { + const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined; + const newBaggageHeaders = []; - ch = state.input.charCodeAt(++state.position); + if (Array.isArray(existingBaggageHeader)) { + newBaggageHeaders.push(...existingBaggageHeader); + } else if (existingBaggageHeader) { + newBaggageHeaders.push(existingBaggageHeader); } - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); + if (sentryBaggageHeader) { + newBaggageHeaders.push(sentryBaggageHeader); } - } - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); + return { + ...(headers ), + 'sentry-trace': sentryTraceHeader, + baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined, + }; } +} +function getFullURL(url) { try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); + const parsed = new URL(url); + return parsed.href; + } catch (e) { + return undefined; } +} - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; +function endSpan(span, handlerData) { + if (handlerData.response) { + core.setHttpStatus(span, handlerData.response.status); - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; + const contentLength = + handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length'); - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + if (contentLength) { + const contentLengthNum = parseInt(contentLength); + if (contentLengthNum > 0) { + span.setAttribute('http.response_content_length', contentLengthNum); + } + } + } else if (handlerData.error) { + span.setStatus('internal_error'); } - - return true; + span.end(); } -function readAnchorProperty(state) { - var _position, - ch; +exports.addTracingHeadersToFetchRequest = addTracingHeadersToFetchRequest; +exports.instrumentFetchRequest = instrumentFetchRequest; +//# sourceMappingURL=fetch.js.map - ch = state.input.charCodeAt(state.position); - if (ch !== 0x26/* & */) return false; +/***/ }), - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } +/***/ 9537: +/***/ ((module, exports, __nccwpck_require__) => { - ch = state.input.charCodeAt(++state.position); - _position = state.position; +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); +/** + * @private + */ +function _autoloadDatabaseIntegrations() { + const carrier = core.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; } - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); + const packageToIntegrationMapping = { + mongodb() { + const integration = utils.dynamicRequire(module, './node/integrations/mongo') - if (ch !== 0x2A/* * */) return false; +; + return new integration.Mongo(); + }, + mongoose() { + const integration = utils.dynamicRequire(module, './node/integrations/mongo') - ch = state.input.charCodeAt(++state.position); - _position = state.position; +; + return new integration.Mongo(); + }, + mysql() { + const integration = utils.dynamicRequire(module, './node/integrations/mysql') - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } +; + return new integration.Mysql(); + }, + pg() { + const integration = utils.dynamicRequire(module, './node/integrations/postgres') - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } +; + return new integration.Postgres(); + }, + }; - alias = state.input.slice(_position, state.position); + const mappedPackages = Object.keys(packageToIntegrationMapping) + .filter(moduleName => !!utils.loadModule(moduleName)) + .map(pkg => { + try { + return packageToIntegrationMapping[pkg](); + } catch (e) { + return undefined; + } + }) + .filter(p => p) ; - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); + if (mappedPackages.length > 0) { + carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages]; } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; } -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } +/***/ 41143: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const express = __nccwpck_require__(95818); +const postgres = __nccwpck_require__(43779); +const mysql = __nccwpck_require__(46340); +const mongo = __nccwpck_require__(55374); +const prisma = __nccwpck_require__(56392); +const graphql = __nccwpck_require__(89031); +const apollo = __nccwpck_require__(31123); +const lazy = __nccwpck_require__(4190); +const browsertracing = __nccwpck_require__(72416); +const browserTracingIntegration = __nccwpck_require__(60720); +const request = __nccwpck_require__(15737); +const instrument = __nccwpck_require__(63187); +const fetch = __nccwpck_require__(14165); +const extensions = __nccwpck_require__(9537); + + + +exports.IdleTransaction = core.IdleTransaction; +exports.Span = core.Span; +exports.SpanStatus = core.SpanStatus; +exports.Transaction = core.Transaction; +exports.extractTraceparentData = core.extractTraceparentData; +exports.getActiveTransaction = core.getActiveTransaction; +exports.hasTracingEnabled = core.hasTracingEnabled; +exports.spanStatusfromHttpCode = core.spanStatusfromHttpCode; +exports.startIdleTransaction = core.startIdleTransaction; +exports.TRACEPARENT_REGEXP = utils.TRACEPARENT_REGEXP; +exports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment; +exports.Express = express.Express; +exports.Postgres = postgres.Postgres; +exports.Mysql = mysql.Mysql; +exports.Mongo = mongo.Mongo; +exports.Prisma = prisma.Prisma; +exports.GraphQL = graphql.GraphQL; +exports.Apollo = apollo.Apollo; +exports.lazyLoadedNodePerformanceMonitoringIntegrations = lazy.lazyLoadedNodePerformanceMonitoringIntegrations; +exports.BROWSER_TRACING_INTEGRATION_ID = browsertracing.BROWSER_TRACING_INTEGRATION_ID; +exports.BrowserTracing = browsertracing.BrowserTracing; +exports.browserTracingIntegration = browserTracingIntegration.browserTracingIntegration; +exports.startBrowserTracingNavigationSpan = browserTracingIntegration.startBrowserTracingNavigationSpan; +exports.startBrowserTracingPageLoadSpan = browserTracingIntegration.startBrowserTracingPageLoadSpan; +exports.defaultRequestInstrumentationOptions = request.defaultRequestInstrumentationOptions; +exports.instrumentOutgoingRequests = request.instrumentOutgoingRequests; +exports.addClsInstrumentationHandler = instrument.addClsInstrumentationHandler; +exports.addFidInstrumentationHandler = instrument.addFidInstrumentationHandler; +exports.addLcpInstrumentationHandler = instrument.addLcpInstrumentationHandler; +exports.addPerformanceInstrumentationHandler = instrument.addPerformanceInstrumentationHandler; +exports.addTracingHeadersToFetchRequest = fetch.addTracingHeadersToFetchRequest; +exports.instrumentFetchRequest = fetch.instrumentFetchRequest; +exports.addExtensionMethods = extensions.addExtensionMethods; +//# sourceMappingURL=index.js.map - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } +/***/ }), - blockIndent = state.position - state.lineStart; +/***/ 31123: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; +var { + _optionalChain +} = __nccwpck_require__(25304); - } else if (readAlias(state)) { - hasContent = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; +/** Tracing integration for Apollo */ +class Apollo { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Apollo';} - if (state.tag === null) { - state.tag = '?'; - } - } + /** + * @inheritDoc + */ - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } + /** + * @inheritDoc + */ + constructor( + options = { + useNestjs: false, + }, + ) { + this.name = Apollo.id; + this._useNest = !!options.useNestjs; } - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + /** @inheritdoc */ + loadDependency() { + if (this._useNest) { + this._module = this._module || utils.loadModule('@nestjs/graphql'); + } else { + this._module = this._module || utils.loadModule('apollo-server-core'); } - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + return this._module; + } + + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('Apollo Integration is skipped because of instrumenter configuration.'); + return; } - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; + if (this._useNest) { + const pkg = this.loadDependency(); - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; + if (!pkg) { + debugBuild.DEBUG_BUILD && utils.logger.error('Apollo-NestJS Integration was unable to require @nestjs/graphql package.'); + return; } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; - break; - } - } - } + /** + * Iterate over resolvers of NestJS ResolversExplorerService before schemas are constructed. + */ + utils.fill( + pkg.GraphQLFactory.prototype, + 'mergeWithSchema', + function (orig) { + return function ( - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } + ...args + ) { + utils.fill(this.resolversExplorerService, 'explore', function (orig) { + return function () { + const resolvers = utils.arrayify(orig.call(this)); - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } + const instrumentedResolvers = instrumentResolvers(resolvers, getCurrentHub); - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + return instrumentedResolvers; + }; + }); + + return orig.call(this, ...args); + }; + }, + ); } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } + const pkg = this.loadDependency(); - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} + if (!pkg) { + debugBuild.DEBUG_BUILD && utils.logger.error('Apollo Integration was unable to require apollo-server-core package.'); + return; + } -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; + /** + * Iterate over resolvers of the ApolloServer instance before schemas are constructed. + */ + utils.fill(pkg.ApolloServerBase.prototype, 'constructSchema', function (orig) { + return function ( - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); +) { + if (!this.config.resolvers) { + if (debugBuild.DEBUG_BUILD) { + if (this.config.schema) { + utils.logger.warn( + 'Apollo integration is not able to trace `ApolloServer` instances constructed via `schema` property.' + + 'If you are using NestJS with Apollo, please use `Sentry.Integrations.Apollo({ useNestjs: true })` instead.', + ); + utils.logger.warn(); + } else if (this.config.modules) { + utils.logger.warn( + 'Apollo integration is not able to trace `ApolloServer` instances constructed via `modules` property.', + ); + } - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); + utils.logger.error('Skipping tracing as no resolvers found on the `ApolloServer` instance.'); + } - ch = state.input.charCodeAt(state.position); + return orig.call(this); + } - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } + const resolvers = utils.arrayify(this.config.resolvers); - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; + this.config.resolvers = instrumentResolvers(resolvers, getCurrentHub); - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + return orig.call(this); + }; + }); } + } +}Apollo.__initStatic(); - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; +// eslint-disable-next-line deprecation/deprecation +function instrumentResolvers(resolvers, getCurrentHub) { + return resolvers.map(model => { + Object.keys(model).forEach(resolverGroupName => { + Object.keys(model[resolverGroupName]).forEach(resolverName => { + if (typeof model[resolverGroupName][resolverName] !== 'function') { + return; + } - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } + wrapResolver(model, resolverGroupName, resolverName, getCurrentHub); + }); + }); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } + return model; + }); +} - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; +/** + * Wrap a single resolver which can be a parent of other resolvers and/or db operations. + */ +function wrapResolver( + model, + resolverGroupName, + resolverName, + // eslint-disable-next-line deprecation/deprecation + getCurrentHub, +) { + utils.fill(model[resolverGroupName], resolverName, function (orig) { + return function ( ...args) { + // eslint-disable-next-line deprecation/deprecation + const scope = getCurrentHub().getScope(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({ + description: `${resolverGroupName}.${resolverName}`, + op: 'graphql.resolve', + origin: 'auto.graphql.apollo', + })]); + + const rv = orig.call(this, ...args); + + if (utils.isThenable(rv)) { + return rv.then((res) => { + _optionalChain([span, 'optionalAccess', _4 => _4.end, 'call', _5 => _5()]); + return res; + }); } - if (is_EOL(ch)) break; + _optionalChain([span, 'optionalAccess', _6 => _6.end, 'call', _7 => _7()]); - _position = state.position; + return rv; + }; + }); +} - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } +exports.Apollo = Apollo; +//# sourceMappingURL=apollo.js.map - directiveArgs.push(state.input.slice(_position, state.position)); - } - if (ch !== 0) readLineBreak(state); +/***/ }), - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } +/***/ 95818: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - skipSeparationSpace(state, true, -1); +var { + _optionalChain +} = __nccwpck_require__(25304); - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); +Object.defineProperty(exports, "__esModule", ({ value: true })); - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); +/* eslint-disable max-lines */ - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } +/** + * Express integration + * + * Provides an request and error handler for Express framework as well as tracing capabilities + */ +class Express { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Express';} - state.documents.push(state.result); + /** + * @inheritDoc + */ - if (state.position === state.lineStart && testDocumentSeparator(state)) { + /** + * Express App instance + */ - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; + /** + * @inheritDoc + */ + constructor(options = {}) { + this.name = Express.id; + this._router = options.router || options.app; + this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); } - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (!this._router) { + debugBuild.DEBUG_BUILD && utils.logger.error('ExpressIntegration is missing an Express instance'); + return; + } + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('Express Integration is skipped because of instrumenter configuration.'); + return; + } -function loadDocuments(input, options) { - input = String(input); - options = options || {}; + instrumentMiddlewares(this._router, this._methods); + instrumentRouter(this._router ); + } +}Express.__initStatic(); - if (input.length !== 0) { +/** + * Wraps original middleware function in a tracing call, which stores the info about the call as a span, + * and finishes it once the middleware is done invoking. + * + * Express middlewares have 3 various forms, thus we have to take care of all of them: + * // sync + * app.use(function (req, res) { ... }) + * // async + * app.use(function (req, res, next) { ... }) + * // error handler + * app.use(function (err, req, res, next) { ... }) + * + * They all internally delegate to the `router[method]` of the given application instance. + */ +// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any +function wrap(fn, method) { + const arity = fn.length; - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; + switch (arity) { + case 2: { + return function ( req, res) { + const transaction = res.__sentry_transaction; + if (transaction) { + // eslint-disable-next-line deprecation/deprecation + const span = transaction.startChild({ + description: fn.name, + op: `middleware.express.${method}`, + origin: 'auto.middleware.express', + }); + res.once('finish', () => { + span.end(); + }); + } + return fn.call(this, req, res); + }; } + case 3: { + return function ( - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + req, + res, + next, + ) { + const transaction = res.__sentry_transaction; + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([transaction, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({ + description: fn.name, + op: `middleware.express.${method}`, + origin: 'auto.middleware.express', + })]); + fn.call(this, req, res, function ( ...args) { + _optionalChain([span, 'optionalAccess', _4 => _4.end, 'call', _5 => _5()]); + next.call(this, ...args); + }); + }; + } + case 4: { + return function ( + + err, + req, + res, + next, + ) { + const transaction = res.__sentry_transaction; + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([transaction, 'optionalAccess', _6 => _6.startChild, 'call', _7 => _7({ + description: fn.name, + op: `middleware.express.${method}`, + origin: 'auto.middleware.express', + })]); + fn.call(this, err, req, res, function ( ...args) { + _optionalChain([span, 'optionalAccess', _8 => _8.end, 'call', _9 => _9()]); + next.call(this, ...args); + }); + }; + } + default: { + throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`); } } +} - var state = new State(input, options); +/** + * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` + * and wraps every function, as well as array of functions with a call to our `wrap` method. + * We have to take care of the arrays as well as iterate over all of the arguments, + * as `app.use` can accept middlewares in few various forms. + * + * app.use([], ) + * app.use([], , ...) + * app.use([], ...[]) + */ +function wrapMiddlewareArgs(args, method) { + return args.map((arg) => { + if (typeof arg === 'function') { + return wrap(arg, method); + } - var nullpos = input.indexOf('\0'); + if (Array.isArray(arg)) { + return arg.map((a) => { + if (typeof a === 'function') { + return wrap(a, method); + } + return a; + }); + } - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } + return arg; + }); +} - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; +/** + * Patches original router to utilize our tracing functionality + */ +function patchMiddleware(router, method) { + const originalCallback = router[method]; - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } + router[method] = function (...args) { + return originalCallback.call(this, ...wrapMiddlewareArgs(args, method)); + }; - while (state.position < (state.length - 1)) { - readDocument(state); - } + return router; +} - return state.documents; +/** + * Patches original router methods + */ +function instrumentMiddlewares(router, methods = []) { + methods.forEach((method) => patchMiddleware(router, method)); } +/** + * Patches the prototype of Express.Router to accumulate the resolved route + * if a layer instance's `match` function was called and it returned a successful match. + * + * @see https://github.com/expressjs/express/blob/master/lib/router/index.js + * + * @param appOrRouter the router instance which can either be an app (i.e. top-level) or a (nested) router. + */ +function instrumentRouter(appOrRouter) { + // This is how we can distinguish between app and routers + const isApp = 'settings' in appOrRouter; -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; + // In case the app's top-level router hasn't been initialized yet, we have to do it now + if (isApp && appOrRouter._router === undefined && appOrRouter.lazyrouter) { + appOrRouter.lazyrouter(); } - var documents = loadDocuments(input, options); + const router = isApp ? appOrRouter._router : appOrRouter; - if (typeof iterator !== 'function') { - return documents; + if (!router) { + /* + If we end up here, this means likely that this integration is used with Express 3 or Express 5. + For now, we don't support these versions (3 is very old and 5 is still in beta). To support Express 5, + we'd need to make more changes to the routing instrumentation because the router is no longer part of + the Express core package but maintained in its own package. The new router has different function + signatures and works slightly differently, demanding more changes than just taking the router from + `app.router` instead of `app._router`. + @see https://github.com/pillarjs/router + + TODO: Proper Express 5 support + */ + debugBuild.DEBUG_BUILD && utils.logger.debug('Cannot instrument router for URL Parameterization (did not find a valid router).'); + debugBuild.DEBUG_BUILD && utils.logger.debug('Routing instrumentation is currently only supported in Express 4.'); + return; } - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} + const routerProto = Object.getPrototypeOf(router) ; + const originalProcessParams = routerProto.process_params; + routerProto.process_params = function process_params( + layer, + called, + req, + res, + done, + ) { + // Base case: We're in the first part of the URL (thus we start with the root '/') + if (!req._reconstructedRoute) { + req._reconstructedRoute = ''; + } -function load(input, options) { - var documents = loadDocuments(input, options); + // If the layer's partial route has params, is a regex or an array, the route is stored in layer.route. + const { layerRoutePath, isRegex, isArray, numExtraSegments } = getLayerRoutePathInfo(layer); - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} + if (layerRoutePath || isRegex || isArray) { + req._hasParameters = true; + } + // Otherwise, the hardcoded path (i.e. a partial route without params) is stored in layer.path + let partialRoute; -module.exports.loadAll = loadAll; -module.exports.load = load; + if (layerRoutePath) { + partialRoute = layerRoutePath; + } else { + /** + * prevent duplicate segment in _reconstructedRoute param if router match multiple routes before final path + * example: + * original url: /api/v1/1234 + * prevent: /api/api/v1/:userId + * router structure + * /api -> middleware + * /api/v1 -> middleware + * /1234 -> endpoint with param :userId + * final _reconstructedRoute is /api/v1/:userId + */ + partialRoute = preventDuplicateSegments(req.originalUrl, req._reconstructedRoute, layer.path) || ''; + } + + // Normalize the partial route so that it doesn't contain leading or trailing slashes + // and exclude empty or '*' wildcard routes. + // The exclusion of '*' routes is our best effort to not "pollute" the transaction name + // with interim handlers (e.g. ones that check authentication or do other middleware stuff). + // We want to end up with the parameterized URL of the incoming request without any extraneous path segments. + const finalPartialRoute = partialRoute + .split('/') + .filter(segment => segment.length > 0 && (isRegex || isArray || !segment.includes('*'))) + .join('/'); + + // If we found a valid partial URL, we append it to the reconstructed route + if (finalPartialRoute && finalPartialRoute.length > 0) { + // If the partial route is from a regex route, we append a '/' to close the regex + req._reconstructedRoute += `/${finalPartialRoute}${isRegex ? '/' : ''}`; + } + + // Now we check if we are in the "last" part of the route. We determine this by comparing the + // number of URL segments from the original URL to that of our reconstructed parameterized URL. + // If we've reached our final destination, we update the transaction name. + const urlLength = utils.getNumberOfUrlSegments(utils.stripUrlQueryAndFragment(req.originalUrl || '')) + numExtraSegments; + const routeLength = utils.getNumberOfUrlSegments(req._reconstructedRoute); + + if (urlLength === routeLength) { + if (!req._hasParameters) { + if (req._reconstructedRoute !== req.originalUrl) { + req._reconstructedRoute = req.originalUrl ? utils.stripUrlQueryAndFragment(req.originalUrl) : req.originalUrl; + } + } + + const transaction = res.__sentry_transaction; + const attributes = (transaction && core.spanToJSON(transaction).data) || {}; + if (transaction && attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] !== 'custom') { + // If the request URL is '/' or empty, the reconstructed route will be empty. + // Therefore, we fall back to setting the final route to '/' in this case. + const finalRoute = req._reconstructedRoute || '/'; + + const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true, customRoute: finalRoute }); + transaction.updateName(name); + transaction.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); + } + } + + return originalProcessParams.call(this, layer, called, req, res, done); + }; +} +/** + * Recreate layer.route.path from layer.regexp and layer.keys. + * Works until express.js used package path-to-regexp@0.1.7 + * or until layer.keys contain offset attribute + * + * @param layer the layer to extract the stringified route from + * + * @returns string in layer.route.path structure 'router/:pathParam' or undefined + */ +const extractOriginalRoute = ( + path, + regexp, + keys, +) => { + if ( + !path || + !regexp || + !keys || + Object.keys(keys).length === 0 || + _optionalChain([keys, 'access', _10 => _10[0], 'optionalAccess', _11 => _11.offset]) === undefined || + _optionalChain([keys, 'access', _12 => _12[0], 'optionalAccess', _13 => _13.offset]) === null + ) { + return undefined; + } + const orderedKeys = keys.sort((a, b) => a.offset - b.offset); -/***/ }), + // add d flag for getting indices from regexp result + // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- regexp comes from express.js + const pathRegex = new RegExp(regexp, `${regexp.flags}d`); + /** + * use custom type cause of TS error with missing indices in RegExpExecArray + */ + const execResult = pathRegex.exec(path) ; -/***/ 22258: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!execResult || !execResult.indices) { + return undefined; + } + /** + * remove first match from regex cause contain whole layer.path + */ + const [, ...paramIndices] = execResult.indices; -"use strict"; + if (paramIndices.length !== orderedKeys.length) { + return undefined; + } + let resultPath = path; + let indexShift = 0; + /** + * iterate param matches from regexp.exec + */ + paramIndices.forEach((item, index) => { + /** check if offsets is define because in some cases regex d flag returns undefined */ + if (item) { + const [startOffset, endOffset] = item; + /** + * isolate part before param + */ + const substr1 = resultPath.substring(0, startOffset - indexShift); + /** + * define paramName as replacement in format :pathParam + */ + const replacement = `:${orderedKeys[index].name}`; + + /** + * isolate part after param + */ + const substr2 = resultPath.substring(endOffset - indexShift); + + /** + * recreate original path but with param replacement + */ + resultPath = substr1 + replacement + substr2; + + /** + * calculate new index shift after resultPath was modified + */ + indexShift = indexShift + (endOffset - startOffset - replacement.length); + } + }); -/*eslint-disable max-len*/ + return resultPath; +}; -var YAMLException = __nccwpck_require__(30780); -var Type = __nccwpck_require__(57480); +/** + * Extracts and stringifies the layer's route which can either be a string with parameters (`users/:id`), + * a RegEx (`/test/`) or an array of strings and regexes (`['/path1', /\/path[2-5]/, /path/:id]`). Additionally + * returns extra information about the route, such as if the route is defined as regex or as an array. + * + * @param layer the layer to extract the stringified route from + * + * @returns an object containing the stringified route, a flag determining if the route was a regex + * and the number of extra segments to the matched path that are additionally in the route, + * if the route was an array (defaults to 0). + */ +function getLayerRoutePathInfo(layer) { + let lrp = _optionalChain([layer, 'access', _14 => _14.route, 'optionalAccess', _15 => _15.path]); + const isRegex = utils.isRegExp(lrp); + const isArray = Array.isArray(lrp); -function compileList(schema, name) { - var result = []; + if (!lrp) { + // parse node.js major version + // Next.js will complain if we directly use `proces.versions` here because of edge runtime. + const [major] = (utils.GLOBAL_OBJ ).process.versions.node.split('.').map(Number); - schema[name].forEach(function (currentType) { - var newIndex = result.length; + // allow call extractOriginalRoute only if node version support Regex d flag, node 16+ + if (major >= 16) { + /** + * If lrp does not exist try to recreate original layer path from route regexp + */ + lrp = extractOriginalRoute(layer.path, layer.regexp, layer.keys); + } + } - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { + if (!lrp) { + return { isRegex, isArray, numExtraSegments: 0 }; + } - newIndex = previousIndex; - } - }); + const numExtraSegments = isArray + ? Math.max(getNumberOfArrayUrlSegments(lrp ) - utils.getNumberOfUrlSegments(layer.path || ''), 0) + : 0; - result[newIndex] = currentType; - }); + const layerRoutePath = getLayerRoutePathString(isArray, lrp); - return result; + return { layerRoutePath, isRegex, isArray, numExtraSegments }; } +/** + * Returns the number of URL segments in an array of routes + * + * Example: ['/api/test', /\/api\/post[0-9]/, '/users/:id/details`] -> 7 + */ +function getNumberOfArrayUrlSegments(routesArray) { + return routesArray.reduce((accNumSegments, currentRoute) => { + // array members can be a RegEx -> convert them toString + return accNumSegments + utils.getNumberOfUrlSegments(currentRoute.toString()); + }, 0); +} -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; - - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } +/** + * Extracts and returns the stringified version of the layers route path + * Handles route arrays (by joining the paths together) as well as RegExp and normal + * string values (in the latter case the toString conversion is technically unnecessary but + * it doesn't hurt us either). + */ +function getLayerRoutePathString(isArray, lrp) { + if (isArray) { + return (lrp ).map(r => r.toString()).join(','); } + return lrp && lrp.toString(); +} - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } +/** + * remove duplicate segment contain in layerPath against reconstructedRoute, + * and return only unique segment that can be added into reconstructedRoute + */ +function preventDuplicateSegments( + originalUrl, + reconstructedRoute, + layerPath, +) { + // filter query params + const normalizeURL = utils.stripUrlQueryAndFragment(originalUrl || ''); + const originalUrlSplit = _optionalChain([normalizeURL, 'optionalAccess', _16 => _16.split, 'call', _17 => _17('/'), 'access', _18 => _18.filter, 'call', _19 => _19(v => !!v)]); + let tempCounter = 0; + const currentOffset = _optionalChain([reconstructedRoute, 'optionalAccess', _20 => _20.split, 'call', _21 => _21('/'), 'access', _22 => _22.filter, 'call', _23 => _23(v => !!v), 'access', _24 => _24.length]) || 0; + const result = _optionalChain([layerPath +, 'optionalAccess', _25 => _25.split, 'call', _26 => _26('/') +, 'access', _27 => _27.filter, 'call', _28 => _28(segment => { + if (_optionalChain([originalUrlSplit, 'optionalAccess', _29 => _29[currentOffset + tempCounter]]) === segment) { + tempCounter += 1; + return true; + } + return false; + }) +, 'access', _30 => _30.join, 'call', _31 => _31('/')]); return result; } +exports.Express = Express; +exports.extractOriginalRoute = extractOriginalRoute; +exports.preventDuplicateSegments = preventDuplicateSegments; +//# sourceMappingURL=express.js.map -function Schema(definition) { - return this.extend(definition); -} +/***/ }), -Schema.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; +/***/ 89031: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (definition instanceof Type) { - // Schema.extend(type) - explicit.push(definition); +var { + _optionalChain +} = __nccwpck_require__(25304); - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); +Object.defineProperty(exports, "__esModule", ({ value: true })); - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); - } else { - throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); +/** Tracing integration for graphql package */ +class GraphQL { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'GraphQL';} + + /** + * @inheritDoc + */ + + constructor() { + this.name = GraphQL.id; } - implicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } + /** @inheritdoc */ + loadDependency() { + return (this._module = this._module || utils.loadModule('graphql/execution/execute.js')); + } - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('GraphQL Integration is skipped because of instrumenter configuration.'); + return; } - if (type.multi) { - throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); + const pkg = this.loadDependency(); - explicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + if (!pkg) { + debugBuild.DEBUG_BUILD && utils.logger.error('GraphQL Integration was unable to require graphql/execution package.'); + return; } - }); - var result = Object.create(Schema.prototype); + utils.fill(pkg, 'execute', function (orig) { + return function ( ...args) { + // eslint-disable-next-line deprecation/deprecation + const scope = getCurrentHub().getScope(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({ + description: 'execute', + op: 'graphql.execute', + origin: 'auto.graphql.graphql', + })]); - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + // eslint-disable-next-line deprecation/deprecation + _optionalChain([scope, 'optionalAccess', _4 => _4.setSpan, 'call', _5 => _5(span)]); - return result; -}; + const rv = orig.call(this, ...args); + if (utils.isThenable(rv)) { + return rv.then((res) => { + _optionalChain([span, 'optionalAccess', _6 => _6.end, 'call', _7 => _7()]); + // eslint-disable-next-line deprecation/deprecation + _optionalChain([scope, 'optionalAccess', _8 => _8.setSpan, 'call', _9 => _9(parentSpan)]); -module.exports = Schema; + return res; + }); + } + + _optionalChain([span, 'optionalAccess', _10 => _10.end, 'call', _11 => _11()]); + // eslint-disable-next-line deprecation/deprecation + _optionalChain([scope, 'optionalAccess', _12 => _12.setSpan, 'call', _13 => _13(parentSpan)]); + return rv; + }; + }); + } +}GraphQL.__initStatic(); + +exports.GraphQL = GraphQL; +//# sourceMappingURL=graphql.js.map /***/ }), -/***/ 90085: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4190: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); + +const lazyLoadedNodePerformanceMonitoringIntegrations = [ + () => { + const integration = utils.dynamicRequire(module, './apollo') + +; + return new integration.Apollo(); + }, + () => { + const integration = utils.dynamicRequire(module, './apollo') + +; + return new integration.Apollo({ useNestjs: true }); + }, + () => { + const integration = utils.dynamicRequire(module, './graphql') + +; + return new integration.GraphQL(); + }, + () => { + const integration = utils.dynamicRequire(module, './mongo') +; + return new integration.Mongo(); + }, + () => { + const integration = utils.dynamicRequire(module, './mongo') +; + return new integration.Mongo({ mongoose: true }); + }, + () => { + const integration = utils.dynamicRequire(module, './mysql') +; + return new integration.Mysql(); + }, + () => { + const integration = utils.dynamicRequire(module, './postgres') +; + return new integration.Postgres(); + }, +]; -module.exports = __nccwpck_require__(70265); +exports.lazyLoadedNodePerformanceMonitoringIntegrations = lazyLoadedNodePerformanceMonitoringIntegrations; +//# sourceMappingURL=lazy.js.map /***/ }), -/***/ 77599: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 55374: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); + +// This allows us to use the same array for both defaults options and the type itself. +// (note `as const` at the end to make it a union of string literal types (i.e. "a" | "b" | ... ) +// and not just a string[]) + +const OPERATIONS = [ + 'aggregate', // aggregate(pipeline, options, callback) + 'bulkWrite', // bulkWrite(operations, options, callback) + 'countDocuments', // countDocuments(query, options, callback) + 'createIndex', // createIndex(fieldOrSpec, options, callback) + 'createIndexes', // createIndexes(indexSpecs, options, callback) + 'deleteMany', // deleteMany(filter, options, callback) + 'deleteOne', // deleteOne(filter, options, callback) + 'distinct', // distinct(key, query, options, callback) + 'drop', // drop(options, callback) + 'dropIndex', // dropIndex(indexName, options, callback) + 'dropIndexes', // dropIndexes(options, callback) + 'estimatedDocumentCount', // estimatedDocumentCount(options, callback) + 'find', // find(query, options, callback) + 'findOne', // findOne(query, options, callback) + 'findOneAndDelete', // findOneAndDelete(filter, options, callback) + 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback) + 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback) + 'indexes', // indexes(options, callback) + 'indexExists', // indexExists(indexes, options, callback) + 'indexInformation', // indexInformation(options, callback) + 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback) + 'insertMany', // insertMany(docs, options, callback) + 'insertOne', // insertOne(doc, options, callback) + 'isCapped', // isCapped(options, callback) + 'mapReduce', // mapReduce(map, reduce, options, callback) + 'options', // options(options, callback) + 'parallelCollectionScan', // parallelCollectionScan(options, callback) + 'rename', // rename(newName, options, callback) + 'replaceOne', // replaceOne(filter, doc, options, callback) + 'stats', // stats(options, callback) + 'updateMany', // updateMany(filter, update, options, callback) + 'updateOne', // updateOne(filter, update, options, callback) +] ; + +// All of the operations above take `options` and `callback` as their final parameters, but some of them +// take additional parameters as well. For those operations, this is a map of +// { : [] }, as a way to know what to call the operation's +// positional arguments when we add them to the span's `data` object later +const OPERATION_SIGNATURES + + = { + // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well + // see https://github.com/getsentry/sentry-javascript/pull/3102 + bulkWrite: ['operations'], + countDocuments: ['query'], + createIndex: ['fieldOrSpec'], + createIndexes: ['indexSpecs'], + deleteMany: ['filter'], + deleteOne: ['filter'], + distinct: ['key', 'query'], + dropIndex: ['indexName'], + find: ['query'], + findOne: ['query'], + findOneAndDelete: ['filter'], + findOneAndReplace: ['filter', 'replacement'], + findOneAndUpdate: ['filter', 'update'], + indexExists: ['indexes'], + insertMany: ['docs'], + insertOne: ['doc'], + mapReduce: ['map', 'reduce'], + rename: ['newName'], + replaceOne: ['filter', 'doc'], + updateMany: ['filter', 'update'], + updateOne: ['filter', 'update'], +}; + +function isCursor(maybeCursor) { + return maybeCursor && typeof maybeCursor === 'object' && maybeCursor.once && typeof maybeCursor.once === 'function'; +} + +/** Tracing integration for mongo package */ +class Mongo { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Mongo';} + /** + * @inheritDoc + */ + /** + * @inheritDoc + */ + constructor(options = {}) { + this.name = Mongo.id; + this._operations = Array.isArray(options.operations) ? options.operations : (OPERATIONS ); + this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; + this._useMongoose = !!options.useMongoose; + } + /** @inheritdoc */ + loadDependency() { + const moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; + return (this._module = this._module || utils.loadModule(moduleName)); + } -module.exports = (__nccwpck_require__(90085).extend)({ - implicit: [ - __nccwpck_require__(9561), - __nccwpck_require__(70884) - ], - explicit: [ - __nccwpck_require__(56942), - __nccwpck_require__(65894), - __nccwpck_require__(18978), - __nccwpck_require__(87424) - ] -}); + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('Mongo Integration is skipped because of instrumenter configuration.'); + return; + } + const pkg = this.loadDependency(); -/***/ }), + if (!pkg) { + const moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; + debugBuild.DEBUG_BUILD && utils.logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`); + return; + } -/***/ 54323: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub); + } -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 + /** + * Patches original collection methods + */ + // eslint-disable-next-line deprecation/deprecation + _instrumentOperations(collection, operations, getCurrentHub) { + operations.forEach((operation) => this._patchOperation(collection, operation, getCurrentHub)); + } + /** + * Patches original collection to utilize our tracing functionality + */ + // eslint-disable-next-line deprecation/deprecation + _patchOperation(collection, operation, getCurrentHub) { + if (!(operation in collection.prototype)) return; + const getSpanContext = this._getSpanContextFromOperationArguments.bind(this); + utils.fill(collection.prototype, operation, function (orig) { + return function ( ...args) { + const lastArg = args[args.length - 1]; + // eslint-disable-next-line deprecation/deprecation + const hub = getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const scope = hub.getScope(); + // eslint-disable-next-line deprecation/deprecation + const client = hub.getClient(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + const sendDefaultPii = _optionalChain([client, 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'access', _4 => _4.sendDefaultPii]); -var Schema = __nccwpck_require__(22258); + // Check if the operation was passed a callback. (mapReduce requires a different check, as + // its (non-callback) arguments can also be functions.) + if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _5 => _5.startChild, 'call', _6 => _6(getSpanContext(this, operation, args, sendDefaultPii))]); + const maybePromiseOrCursor = orig.call(this, ...args); + if (utils.isThenable(maybePromiseOrCursor)) { + return maybePromiseOrCursor.then((res) => { + _optionalChain([span, 'optionalAccess', _7 => _7.end, 'call', _8 => _8()]); + return res; + }); + } + // If the operation returns a Cursor + // we need to attach a listener to it to finish the span when the cursor is closed. + else if (isCursor(maybePromiseOrCursor)) { + const cursor = maybePromiseOrCursor ; -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(32568), - __nccwpck_require__(89695), - __nccwpck_require__(74352) - ] -}); + try { + cursor.once('close', () => { + _optionalChain([span, 'optionalAccess', _9 => _9.end, 'call', _10 => _10()]); + }); + } catch (e) { + // If the cursor is already closed, `once` will throw an error. In that case, we can + // finish the span immediately. + _optionalChain([span, 'optionalAccess', _11 => _11.end, 'call', _12 => _12()]); + } + return cursor; + } else { + _optionalChain([span, 'optionalAccess', _13 => _13.end, 'call', _14 => _14()]); + return maybePromiseOrCursor; + } + } -/***/ }), + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _15 => _15.startChild, 'call', _16 => _16(getSpanContext(this, operation, args.slice(0, -1)))]); -/***/ 70265: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return orig.call(this, ...args.slice(0, -1), function (err, result) { + _optionalChain([span, 'optionalAccess', _17 => _17.end, 'call', _18 => _18()]); + lastArg(err, result); + }); + }; + }); + } -"use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + /** + * Form a SpanContext based on the user input to a given operation. + */ + _getSpanContextFromOperationArguments( + collection, + operation, + args, + sendDefaultPii = false, + ) { + const data = { + 'db.system': 'mongodb', + 'db.name': collection.dbName, + 'db.operation': operation, + 'db.mongodb.collection': collection.collectionName, + }; + const spanContext = { + op: 'db', + // TODO v8: Use `${collection.collectionName}.${operation}` + origin: 'auto.db.mongo', + description: operation, + data, + }; + // If the operation takes no arguments besides `options` and `callback`, or if argument + // collection is disabled for this operation, just return early. + const signature = OPERATION_SIGNATURES[operation]; + const shouldDescribe = Array.isArray(this._describeOperations) + ? this._describeOperations.includes(operation) + : this._describeOperations; + if (!signature || !shouldDescribe || !sendDefaultPii) { + return spanContext; + } + try { + // Special case for `mapReduce`, as the only one accepting functions as arguments. + if (operation === 'mapReduce') { + const [map, reduce] = args ; + data[signature[0]] = typeof map === 'string' ? map : map.name || ''; + data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || ''; + } else { + for (let i = 0; i < signature.length; i++) { + data[`db.mongodb.${signature[i]}`] = JSON.stringify(args[i]); + } + } + } catch (_oO) { + // no-empty + } + return spanContext; + } +}Mongo.__initStatic(); -module.exports = (__nccwpck_require__(54323).extend)({ - implicit: [ - __nccwpck_require__(61002), - __nccwpck_require__(85327), - __nccwpck_require__(2848), - __nccwpck_require__(56128) - ] -}); +exports.Mongo = Mongo; +//# sourceMappingURL=mongo.js.map /***/ }), -/***/ 68947: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 46340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); -var common = __nccwpck_require__(44828); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); +/** Tracing integration for node-mysql package */ +class Mysql { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Mysql';} -// get snippet for a single line, respecting maxLength -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + /** + * @inheritDoc + */ - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; + constructor() { + this.name = Mysql.id; } - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; + /** @inheritdoc */ + loadDependency() { + return (this._module = this._module || utils.loadModule('mysql/lib/Connection.js')); } - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; -} - + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('Mysql Integration is skipped because of instrumenter configuration.'); + return; + } -function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; -} + const pkg = this.loadDependency(); + if (!pkg) { + debugBuild.DEBUG_BUILD && utils.logger.error('Mysql Integration was unable to require `mysql` package.'); + return; + } -function makeSnippet(mark, options) { - options = Object.create(options || null); + let mySqlConfig = undefined; - if (!mark.buffer) return null; + try { + pkg.prototype.connect = new Proxy(pkg.prototype.connect, { + apply(wrappingTarget, thisArg, args) { + if (!mySqlConfig) { + mySqlConfig = thisArg.config; + } + return wrappingTarget.apply(thisArg, args); + }, + }); + } catch (e) { + debugBuild.DEBUG_BUILD && utils.logger.error('Mysql Integration was unable to instrument `mysql` config.'); + } - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + function spanDataFromConfig() { + if (!mySqlConfig) { + return {}; + } + return { + 'server.address': mySqlConfig.host, + 'server.port': mySqlConfig.port, + 'db.user': mySqlConfig.user, + }; + } - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; + function finishSpan(span) { + if (!span) { + return; + } - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); + const data = spanDataFromConfig(); + Object.keys(data).forEach(key => { + span.setAttribute(key, data[key]); + }); - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; + span.end(); } - } - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + // The original function will have one of these signatures: + // function (callback) => void + // function (options, callback) => void + // function (options, values, callback) => void + utils.fill(pkg, 'createQuery', function (orig) { + return function ( options, values, callback) { + // eslint-disable-next-line deprecation/deprecation + const scope = getCurrentHub().getScope(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _2 => _2.startChild, 'call', _3 => _3({ + description: typeof options === 'string' ? options : (options ).sql, + op: 'db', + origin: 'auto.db.mysql', + data: { + 'db.system': 'mysql', + }, + })]); - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } + if (typeof callback === 'function') { + return orig.call(this, options, values, function (err, result, fields) { + finishSpan(span); + callback(err, result, fields); + }); + } - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + if (typeof values === 'function') { + return orig.call(this, options, function (err, result, fields) { + finishSpan(span); + values(err, result, fields); + }); + } - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } + // streaming, no callback! + const query = orig.call(this, options, values) ; - return result.replace(/\n$/, ''); -} + query.on('end', () => { + finishSpan(span); + }); + return query; + }; + }); + } +}Mysql.__initStatic(); -module.exports = makeSnippet; +exports.Mysql = Mysql; +//# sourceMappingURL=mysql.js.map /***/ }), -/***/ 57480: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 43779: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); -var YAMLException = __nccwpck_require__(30780); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' -]; +/** Tracing integration for node-postgres package */ +class Postgres { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Postgres';} -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; + /** + * @inheritDoc + */ -function compileStyleAliases(map) { - var result = {}; + constructor(options = {}) { + this.name = Postgres.id; + this._usePgNative = !!options.usePgNative; + this._module = options.module; + } - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); + /** @inheritdoc */ + loadDependency() { + return (this._module = this._module || utils.loadModule('pg')); } - return result; -} + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + setupOnce(_, getCurrentHub) { + if (nodeUtils.shouldDisableAutoInstrumentation(getCurrentHub)) { + debugBuild.DEBUG_BUILD && utils.logger.log('Postgres Integration is skipped because of instrumenter configuration.'); + return; + } -function Type(tag, options) { - options = options || {}; + const pkg = this.loadDependency(); - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + if (!pkg) { + debugBuild.DEBUG_BUILD && utils.logger.error('Postgres Integration was unable to require `pg` package.'); + return; } - }); - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + const Client = this._usePgNative ? _optionalChain([pkg, 'access', _2 => _2.native, 'optionalAccess', _3 => _3.Client]) : pkg.Client; - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} + if (!Client) { + debugBuild.DEBUG_BUILD && utils.logger.error("Postgres Integration was unable to access 'pg-native' bindings."); + return; + } -module.exports = Type; + /** + * function (query, callback) => void + * function (query, params, callback) => void + * function (query) => Promise + * function (query, params) => Promise + * function (pg.Cursor) => pg.Cursor + */ + utils.fill(Client.prototype, 'query', function (orig) { + return function ( config, values, callback) { + // eslint-disable-next-line deprecation/deprecation + const scope = getCurrentHub().getScope(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + const data = { + 'db.system': 'postgresql', + }; -/***/ }), + try { + if (this.database) { + data['db.name'] = this.database; + } + if (this.host) { + data['server.address'] = this.host; + } + if (this.port) { + data['server.port'] = this.port; + } + if (this.user) { + data['db.user'] = this.user; + } + } catch (e) { + // ignore + } -/***/ 56942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // eslint-disable-next-line deprecation/deprecation + const span = _optionalChain([parentSpan, 'optionalAccess', _4 => _4.startChild, 'call', _5 => _5({ + description: typeof config === 'string' ? config : (config ).text, + op: 'db', + origin: 'auto.db.postgres', + data, + })]); + + if (typeof callback === 'function') { + return orig.call(this, config, values, function (err, result) { + _optionalChain([span, 'optionalAccess', _6 => _6.end, 'call', _7 => _7()]); + callback(err, result); + }); + } -"use strict"; + if (typeof values === 'function') { + return orig.call(this, config, function (err, result) { + _optionalChain([span, 'optionalAccess', _8 => _8.end, 'call', _9 => _9()]); + values(err, result); + }); + } + const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config); -/*eslint-disable no-bitwise*/ + if (utils.isThenable(rv)) { + return rv.then((res) => { + _optionalChain([span, 'optionalAccess', _10 => _10.end, 'call', _11 => _11()]); + return res; + }); + } + _optionalChain([span, 'optionalAccess', _12 => _12.end, 'call', _13 => _13()]); + return rv; + }; + }); + } +}Postgres.__initStatic(); -var Type = __nccwpck_require__(57480); +exports.Postgres = Postgres; +//# sourceMappingURL=postgres.js.map -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; +/***/ }), +/***/ 56392: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function resolveYamlBinary(data) { - if (data === null) return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(80411); +const nodeUtils = __nccwpck_require__(69286); - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); +function isValidPrismaClient(possibleClient) { + return !!possibleClient && !!(possibleClient )['$use']; +} - // Skip CR/LF - if (code > 64) continue; +/** Tracing integration for @prisma/client package */ +class Prisma { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Prisma';} - // Fail on illegal characters - if (code < 0) return false; + /** + * @inheritDoc + */ - bitlen += 6; - } + /** + * @inheritDoc + */ + constructor(options = {}) { + this.name = Prisma.id; + + // We instrument the PrismaClient inside the constructor and not inside `setupOnce` because in some cases of server-side + // bundling (Next.js) multiple Prisma clients can be instantiated, even though users don't intend to. When instrumenting + // in setupOnce we can only ever instrument one client. + // https://github.com/getsentry/sentry-javascript/issues/7216#issuecomment-1602375012 + // In the future we might explore providing a dedicated PrismaClient middleware instead of this hack. + if (isValidPrismaClient(options.client) && !options.client._sentryInstrumented) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + utils.addNonEnumerableProperty(options.client , '_sentryInstrumented', true); + + const clientData = {}; + try { + const engineConfig = (options.client )._engineConfig; + if (engineConfig) { + const { activeProvider, clientVersion } = engineConfig; + if (activeProvider) { + clientData['db.system'] = activeProvider; + } + if (clientVersion) { + clientData['db.prisma.version'] = clientVersion; + } + } + } catch (e) { + // ignore + } - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} + options.client.$use((params, next) => { + // eslint-disable-next-line deprecation/deprecation + if (nodeUtils.shouldDisableAutoInstrumentation(core.getCurrentHub)) { + return next(params); + } -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; + const action = params.action; + const model = params.model; - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); + return core.startSpan( + { + name: model ? `${model} ${action}` : action, + onlyIfParent: true, + op: 'db.prisma', + attributes: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.prisma', + }, + data: { ...clientData, 'db.operation': action }, + }, + () => next(params), + ); + }); + } else { + debugBuild.DEBUG_BUILD && + utils.logger.warn('Unsupported Prisma client provided to PrismaIntegration. Provided client:', options.client); } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); } - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); + /** + * @inheritDoc + */ + setupOnce() { + // Noop - here for backwards compatibility } +} Prisma.__initStatic(); - return new Uint8Array(result); -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. +exports.Prisma = Prisma; +//# sourceMappingURL=prisma.js.map - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - bits = (bits << 8) + object[idx]; - } +/***/ }), - // Dump tail +/***/ 69286: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - tail = max % 3; +var { + _optionalChain +} = __nccwpck_require__(25304); - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return result; -} +/** + * Check if Sentry auto-instrumentation should be disabled. + * + * @param getCurrentHub A method to fetch the current hub + * @returns boolean + */ +// eslint-disable-next-line deprecation/deprecation +function shouldDisableAutoInstrumentation(getCurrentHub) { + // eslint-disable-next-line deprecation/deprecation + const clientOptions = _optionalChain([getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); + const instrumenter = _optionalChain([clientOptions, 'optionalAccess', _6 => _6.instrumenter]) || 'sentry'; -function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; + return instrumenter !== 'sentry'; } -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); +exports.shouldDisableAutoInstrumentation = shouldDisableAutoInstrumentation; +//# sourceMappingURL=node-utils.js.map /***/ }), -/***/ 85327: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +/***/ 28494: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var Type = __nccwpck_require__(57480); +Object.defineProperty(exports, "__esModule", ({ value: true })); -function resolveYamlBoolean(data) { - if (data === null) return false; +const utils = __nccwpck_require__(25304); - var max = data.length; +const SENTRY_API_VERSION = '7'; - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +/** Returns the prefix to construct Sentry ingestion API endpoints. */ +function getBaseApiEndpoint(dsn) { + const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; + const port = dsn.port ? `:${dsn.port}` : ''; + return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; } -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; +/** Returns the ingest API endpoint for target. */ +function _getIngestEndpoint(dsn) { + return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; } -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; +/** Returns a URL-encoded string with auth config suitable for a query string. */ +function _encodedAuth(dsn, sdkInfo) { + return utils.urlEncode({ + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.publicKey, + sentry_version: SENTRY_API_VERSION, + ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), + }); } -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); - +/** + * Returns the envelope endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ +function getEnvelopeEndpointWithUrlEncodedAuth( + dsn, + // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below + // options: ClientOptions = {} as ClientOptions, + tunnelOrOptions = {} , +) { + // TODO (v8): Use this code instead + // const { tunnel, _metadata = {} } = options; + // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; -/***/ }), + const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; + const sdkInfo = + typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; -/***/ 56128: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; +} -"use strict"; +/** Returns the url to the report dialog endpoint. */ +function getReportDialogEndpoint( + dsnLike, + dialogOptions +, +) { + const dsn = utils.makeDsn(dsnLike); + if (!dsn) { + return ''; + } -var common = __nccwpck_require__(44828); -var Type = __nccwpck_require__(57480); + const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); + let encodedOptions = `dsn=${utils.dsnToString(dsn)}`; + for (const key in dialogOptions) { + if (key === 'dsn') { + continue; + } -function resolveYamlFloat(data) { - if (data === null) return false; + if (key === 'onClose') { + continue; + } - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; + if (key === 'user') { + const user = dialogOptions.user; + if (!user) { + continue; + } + if (user.name) { + encodedOptions += `&name=${encodeURIComponent(user.name)}`; + } + if (user.email) { + encodedOptions += `&email=${encodeURIComponent(user.email)}`; + } + } else { + encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; + } } - return true; + return `${endpoint}?${encodedOptions}`; } -function constructYamlFloat(data) { - var value, sign; +exports.getEnvelopeEndpointWithUrlEncodedAuth = getEnvelopeEndpointWithUrlEncodedAuth; +exports.getReportDialogEndpoint = getReportDialogEndpoint; +//# sourceMappingURL=api.js.map - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } +/***/ }), - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; +/***/ 35746: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(25304); +const api = __nccwpck_require__(28494); +const debugBuild = __nccwpck_require__(44220); +const envelope = __nccwpck_require__(30528); +const exports$1 = __nccwpck_require__(61117); +const hub = __nccwpck_require__(5553); +const integration = __nccwpck_require__(51212); +const envelope$1 = __nccwpck_require__(98438); +const session = __nccwpck_require__(8114); +const dynamicSamplingContext = __nccwpck_require__(65372); +const prepareEvent = __nccwpck_require__(64867); -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; +const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; -function representYamlFloat(object, style) { - var res; +/** + * Base implementation for all JavaScript SDK clients. + * + * Call the constructor with the corresponding options + * specific to the client subclass. To access these options later, use + * {@link Client.getOptions}. + * + * If a Dsn is specified in the options, it will be parsed and stored. Use + * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is + * invalid, the constructor will throw a {@link SentryException}. Note that + * without a valid Dsn, the SDK will not send any events to Sentry. + * + * Before sending an event, it is passed through + * {@link BaseClient._prepareEvent} to add SDK information and scope data + * (breadcrumbs and context). To add more custom information, override this + * method and extend the resulting prepared event. + * + * To issue automatically created events (e.g. via instrumentation), use + * {@link Client.captureEvent}. It will prepare the event and pass it through + * the callback lifecycle. To issue auto-breadcrumbs, use + * {@link Client.addBreadcrumb}. + * + * @example + * class NodeClient extends BaseClient { + * public constructor(options: NodeOptions) { + * super(options); + * } + * + * // ... + * } + */ +class BaseClient { + /** + * A reference to a metrics aggregator + * + * @experimental Note this is alpha API. It may experience breaking changes in the future. + */ - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } + /** Options passed to the SDK. */ - res = object.toString(10); + /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack + /** Array of set up integrations. */ - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} + /** Indicates whether this client's integrations have been set up. */ -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} + /** Number of calls being processed */ -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); + /** Holds flushable */ + // eslint-disable-next-line @typescript-eslint/ban-types -/***/ }), + /** + * Initializes this client instance. + * + * @param options Options for the client. + */ + constructor(options) { + this._options = options; + this._integrations = {}; + this._integrationsInitialized = false; + this._numProcessing = 0; + this._outcomes = {}; + this._hooks = {}; + this._eventProcessors = []; + + if (options.dsn) { + this._dsn = utils.makeDsn(options.dsn); + } else { + debugBuild.DEBUG_BUILD && utils.logger.warn('No DSN provided, client will not send events.'); + } -/***/ 2848: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this._dsn) { + const url = api.getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options); + this._transport = options.transport({ + tunnel: this._options.tunnel, + recordDroppedEvent: this.recordDroppedEvent.bind(this), + ...options.transportOptions, + url, + }); + } + } -"use strict"; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // ensure we haven't captured this very object before + if (utils.checkOrSetAlreadyCaught(exception)) { + debugBuild.DEBUG_BUILD && utils.logger.log(ALREADY_SEEN_ERROR); + return; + } + let eventId = hint && hint.event_id; -var common = __nccwpck_require__(44828); -var Type = __nccwpck_require__(57480); + this._process( + this.eventFromException(exception, hint) + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} + return eventId; + } -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} + /** + * @inheritDoc + */ + captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level, + hint, + scope, + ) { + let eventId = hint && hint.event_id; + + const eventMessage = utils.isParameterizedString(message) ? message : String(message); + + const promisedEvent = utils.isPrimitive(message) + ? this.eventFromMessage(eventMessage, level, hint) + : this.eventFromException(message, hint); + + this._process( + promisedEvent + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} + return eventId; + } -function resolveYamlInteger(data) { - if (data === null) return false; + /** + * @inheritDoc + */ + captureEvent(event, hint, scope) { + // ensure we haven't captured this very object before + if (hint && hint.originalException && utils.checkOrSetAlreadyCaught(hint.originalException)) { + debugBuild.DEBUG_BUILD && utils.logger.log(ALREADY_SEEN_ERROR); + return; + } - var max = data.length, - index = 0, - hasDigits = false, - ch; + let eventId = hint && hint.event_id; - if (!max) return false; + const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; + const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; - ch = data[index]; + this._process( + this._captureEvent(event, hint, capturedSpanScope || scope).then(result => { + eventId = result; + }), + ); - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; + return eventId; } - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; + /** + * @inheritDoc + */ + captureSession(session$1) { + if (!(typeof session$1.release === 'string')) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Discarded session because of missing or non-string release'); + } else { + this.sendSession(session$1); + // After sending, we set init false to indicate it's not the first occurrence + session.updateSession(session$1, { init: false }); + } + } - // base 2, base 8, base 16 + /** + * @inheritDoc + */ + getDsn() { + return this._dsn; + } - if (ch === 'b') { - // base 2 - index++; + /** + * @inheritDoc + */ + getOptions() { + return this._options; + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } + /** + * @see SdkMetadata in @sentry/types + * + * @return The metadata of the SDK + */ + getSdkMetadata() { + return this._options._metadata; + } + /** + * @inheritDoc + */ + getTransport() { + return this._transport; + } - if (ch === 'x') { - // base 16 - index++; + /** + * @inheritDoc + */ + flush(timeout) { + const transport = this._transport; + if (transport) { + if (this.metricsAggregator) { + this.metricsAggregator.flush(); + } + return this._isClientDoneProcessing(timeout).then(clientFinished => { + return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); + }); + } else { + return utils.resolvedSyncPromise(true); + } + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; + /** + * @inheritDoc + */ + close(timeout) { + return this.flush(timeout).then(result => { + this.getOptions().enabled = false; + if (this.metricsAggregator) { + this.metricsAggregator.close(); } - return hasDigits && ch !== '_'; - } + return result; + }); + } + /** Get all installed event processors. */ + getEventProcessors() { + return this._eventProcessors; + } - if (ch === 'o') { - // base 8 - index++; + /** @inheritDoc */ + addEventProcessor(eventProcessor) { + this._eventProcessors.push(eventProcessor); + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; + /** + * This is an internal function to setup all integrations that should run on the client. + * @deprecated Use `client.init()` instead. + */ + setupIntegrations(forceInitialize) { + if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) { + this._setupIntegrations(); } } - // base 10 (except 0) + /** @inheritdoc */ + init() { + if (this._isEnabled()) { + this._setupIntegrations(); + } + } - // value should not start with `_`; - if (ch === '_') return false; + /** + * Gets an installed integration by its `id`. + * + * @returns The installed integration or `undefined` if no integration with that `id` was installed. + * @deprecated Use `getIntegrationByName()` instead. + */ + getIntegrationById(integrationId) { + return this.getIntegrationByName(integrationId); + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; + /** + * Gets an installed integration by its name. + * + * @returns The installed integration or `undefined` if no integration with that `name` was installed. + */ + getIntegrationByName(integrationName) { + return this._integrations[integrationName] ; + } + + /** + * Returns the client's instance of the given integration class, it any. + * @deprecated Use `getIntegrationByName()` instead. + */ + getIntegration(integration) { + try { + return (this._integrations[integration.id] ) || null; + } catch (_oO) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); + return null; } - hasDigits = true; } - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; + /** + * @inheritDoc + */ + addIntegration(integration$1) { + const isAlreadyInstalled = this._integrations[integration$1.name]; - return true; -} + // This hook takes care of only installing if not already installed + integration.setupIntegration(this, integration$1, this._integrations); + // Here we need to check manually to make sure to not run this multiple times + if (!isAlreadyInstalled) { + integration.afterSetupIntegrations(this, [integration$1]); + } + } -function constructYamlInteger(data) { - var value = data, sign = 1, ch; + /** + * @inheritDoc + */ + sendEvent(event, hint = {}) { + this.emit('beforeSendEvent', event, hint); + + let env = envelope.createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); + + for (const attachment of hint.attachments || []) { + env = utils.addItemToEnvelope( + env, + utils.createAttachmentEnvelopeItem( + attachment, + this._options.transportOptions && this._options.transportOptions.textEncoder, + ), + ); + } - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); + const promise = this._sendEnvelope(env); + if (promise) { + promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null); + } } - ch = value[0]; + /** + * @inheritDoc + */ + sendSession(session) { + const env = envelope.createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; + // _sendEnvelope should not throw + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._sendEnvelope(env); } - if (value === '0') return 0; + /** + * @inheritDoc + */ + recordDroppedEvent(reason, category, eventOrCount) { + if (this._options.sendClientReports) { + // TODO v9: We do not need the `event` passed as third argument anymore, and can possibly remove this overload + // If event is passed as third argument, we assume this is a count of 1 + const count = typeof eventOrCount === 'number' ? eventOrCount : 1; - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + // We want to track each category (error, transaction, session, replay_event) separately + // but still keep the distinction between different type of outcomes. + // We could use nested maps, but it's much easier to read and type this way. + // A correct type for map-based implementation if we want to go that route + // would be `Partial>>>` + // With typescript 4.1 we could even use template literal types + const key = `${reason}:${category}`; + debugBuild.DEBUG_BUILD && utils.logger.log(`Recording outcome: "${key}"${count > 1 ? ` (${count} times)` : ''}`); + this._outcomes[key] = (this._outcomes[key] || 0) + count; + } } - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} + /** + * @inheritDoc + */ + captureAggregateMetrics(metricBucketItems) { + debugBuild.DEBUG_BUILD && utils.logger.log(`Flushing aggregated metrics, number of metrics: ${metricBucketItems.length}`); + const metricsEnvelope = envelope$1.createMetricEnvelope( + metricBucketItems, + this._dsn, + this._options._metadata, + this._options.tunnel, + ); -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] + // _sendEnvelope should not throw + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._sendEnvelope(metricsEnvelope); } -}); - -/***/ }), + // Keep on() & emit() signatures in sync with types' client.ts interface + /* eslint-disable @typescript-eslint/unified-signatures */ -/***/ 74352: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** @inheritdoc */ -"use strict"; + /** @inheritdoc */ + on(hook, callback) { + if (!this._hooks[hook]) { + this._hooks[hook] = []; + } + // @ts-expect-error We assue the types are correct + this._hooks[hook].push(callback); + } -var Type = __nccwpck_require__(57480); + /** @inheritdoc */ -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); + /** @inheritdoc */ + emit(hook, ...rest) { + if (this._hooks[hook]) { + this._hooks[hook].forEach(callback => callback(...rest)); + } + } + /* eslint-enable @typescript-eslint/unified-signatures */ -/***/ }), + /** Setup integrations for this client. */ + _setupIntegrations() { + const { integrations } = this._options; + this._integrations = integration.setupIntegrations(this, integrations); + integration.afterSetupIntegrations(this, integrations); -/***/ 70884: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // TODO v8: We don't need this flag anymore + this._integrationsInitialized = true; + } -"use strict"; + /** Updates existing session based on the provided event */ + _updateSessionFromEvent(session$1, event) { + let crashed = false; + let errored = false; + const exceptions = event.exception && event.exception.values; + if (exceptions) { + errored = true; -var Type = __nccwpck_require__(57480); + for (const ex of exceptions) { + const mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } + } + } -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} + // A session is updated and that session update is sent in only one of the two following scenarios: + // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update + // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update + const sessionNonTerminal = session$1.status === 'ok'; + const shouldUpdateAndSend = (sessionNonTerminal && session$1.errors === 0) || (sessionNonTerminal && crashed); -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); + if (shouldUpdateAndSend) { + session.updateSession(session$1, { + ...(crashed && { status: 'crashed' }), + errors: session$1.errors || Number(errored || crashed), + }); + this.captureSession(session$1); + } + } + /** + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise + */ + _isClientDoneProcessing(timeout) { + return new utils.SyncPromise(resolve => { + let ticked = 0; + const tick = 1; + + const interval = setInterval(() => { + if (this._numProcessing == 0) { + clearInterval(interval); + resolve(true); + } else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } + } + }, tick); + }); + } -/***/ }), + /** Determines whether this SDK is enabled and a transport is present. */ + _isEnabled() { + return this.getOptions().enabled !== false && this._transport !== undefined; + } -/***/ 61002: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. + */ + _prepareEvent( + event, + hint, + scope, + isolationScope = hub.getIsolationScope(), + ) { + const options = this.getOptions(); + const integrations = Object.keys(this._integrations); + if (!hint.integrations && integrations.length > 0) { + hint.integrations = integrations; + } -"use strict"; + this.emit('preprocessEvent', event, hint); + return prepareEvent.prepareEvent(options, event, hint, scope, this, isolationScope).then(evt => { + if (evt === null) { + return evt; + } -var Type = __nccwpck_require__(57480); + const propagationContext = { + ...isolationScope.getPropagationContext(), + ...(scope ? scope.getPropagationContext() : undefined), + }; -function resolveYamlNull(data) { - if (data === null) return true; + const trace = evt.contexts && evt.contexts.trace; + if (!trace && propagationContext) { + const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext; + evt.contexts = { + trace: { + trace_id, + span_id: spanId, + parent_span_id: parentSpanId, + }, + ...evt.contexts, + }; - var max = data.length; + const dynamicSamplingContext$1 = dsc ? dsc : dynamicSamplingContext.getDynamicSamplingContextFromClient(trace_id, this, scope); - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} + evt.sdkProcessingMetadata = { + dynamicSamplingContext: dynamicSamplingContext$1, + ...evt.sdkProcessingMetadata, + }; + } + return evt; + }); + } -function constructYamlNull() { - return null; -} + /** + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope + */ + _captureEvent(event, hint = {}, scope) { + return this._processEvent(event, hint, scope).then( + finalEvent => { + return finalEvent.event_id; + }, + reason => { + if (debugBuild.DEBUG_BUILD) { + // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for + // control flow, log just the message (no stack) as a log-level log. + const sentryError = reason ; + if (sentryError.logLevel === 'log') { + utils.logger.log(sentryError.message); + } else { + utils.logger.warn(sentryError); + } + } + return undefined; + }, + ); + } -function isNull(object) { - return object === null; -} + /** + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + */ + _processEvent(event, hint, scope) { + const options = this.getOptions(); + const { sampleRate } = options; + + const isTransaction = isTransactionEvent(event); + const isError = isErrorEvent(event); + const eventType = event.type || 'error'; + const beforeSendLabel = `before send for type \`${eventType}\``; + + // 1.0 === 100% events are sent + // 0.0 === 0% events are sent + // Sampling for transaction happens somewhere else + if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) { + this.recordDroppedEvent('sample_rate', 'error', event); + return utils.rejectedSyncPromise( + new utils.SentryError( + `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, + 'log', + ), + ); + } -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' -}); + const dataCategory = eventType === 'replay_event' ? 'replay' : eventType; + const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; + const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; -/***/ }), + return this._prepareEvent(event, hint, scope, capturedSpanIsolationScope) + .then(prepared => { + if (prepared === null) { + this.recordDroppedEvent('event_processor', dataCategory, event); + throw new utils.SentryError('An event processor returned `null`, will not send event.', 'log'); + } -/***/ 65894: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const isInternalException = hint.data && (hint.data ).__sentry__ === true; + if (isInternalException) { + return prepared; + } -"use strict"; + const result = processBeforeSend(options, prepared, hint); + return _validateBeforeSendResult(result, beforeSendLabel); + }) + .then(processedEvent => { + if (processedEvent === null) { + this.recordDroppedEvent('before_send', dataCategory, event); + if (isTransaction) { + const spans = event.spans || []; + // the transaction itself counts as one span, plus all the child spans that are added + const spanCount = 1 + spans.length; + this.recordDroppedEvent('before_send', 'span', spanCount); + } + throw new utils.SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, 'log'); + } + const session = scope && scope.getSession(); + if (!isTransaction && session) { + this._updateSessionFromEvent(session, processedEvent); + } -var Type = __nccwpck_require__(57480); + if (isTransaction) { + const spanCountBefore = + (processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing) || + 0; + const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0; -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; + const droppedSpanCount = spanCountBefore - spanCountAfter; + if (droppedSpanCount > 0) { + this.recordDroppedEvent('before_send', 'span', droppedSpanCount); + } + } -function resolveYamlOmap(data) { - if (data === null) return true; + // None of the Sentry built event processor will update transaction name, + // so if the transaction name has been changed by an event processor, we know + // it has to come from custom event processor added by a user + const transactionInfo = processedEvent.transaction_info; + if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { + const source = 'custom'; + processedEvent.transaction_info = { + ...transactionInfo, + source, + }; + } - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; + this.sendEvent(processedEvent, hint); + return processedEvent; + }) + .then(null, reason => { + if (reason instanceof utils.SentryError) { + throw reason; + } - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; + this.captureException(reason, { + data: { + __sentry__: true, + }, + originalException: reason, + }); + throw new utils.SentryError( + `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, + ); + }); + } - if (_toString.call(pair) !== '[object Object]') return false; + /** + * Occupies the client with processing and event + */ + _process(promise) { + this._numProcessing++; + void promise.then( + value => { + this._numProcessing--; + return value; + }, + reason => { + this._numProcessing--; + return reason; + }, + ); + } - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } + /** + * @inheritdoc + */ + _sendEnvelope(envelope) { + this.emit('beforeEnvelope', envelope); - if (!pairHasKey) return false; + if (this._isEnabled() && this._transport) { + return this._transport.send(envelope).then(null, reason => { + debugBuild.DEBUG_BUILD && utils.logger.error('Error while sending event:', reason); + }); + } else { + debugBuild.DEBUG_BUILD && utils.logger.error('Transport disabled'); + } + } - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; + /** + * Clears outcomes on this client and returns them. + */ + _clearOutcomes() { + const outcomes = this._outcomes; + this._outcomes = {}; + return Object.keys(outcomes).map(key => { + const [reason, category] = key.split(':') ; + return { + reason, + category, + quantity: outcomes[key], + }; + }); } - return true; -} + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function constructYamlOmap(data) { - return data !== null ? data : []; } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - - -/***/ }), - -/***/ 18978: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. + */ +function _validateBeforeSendResult( + beforeSendResult, + beforeSendLabel, +) { + const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; + if (utils.isThenable(beforeSendResult)) { + return beforeSendResult.then( + event => { + if (!utils.isPlainObject(event) && event !== null) { + throw new utils.SentryError(invalidValueError); + } + return event; + }, + e => { + throw new utils.SentryError(`${beforeSendLabel} rejected with ${e}`); + }, + ); + } else if (!utils.isPlainObject(beforeSendResult) && beforeSendResult !== null) { + throw new utils.SentryError(invalidValueError); + } + return beforeSendResult; +} -"use strict"; +/** + * Process the matching `beforeSendXXX` callback. + */ +function processBeforeSend( + options, + event, + hint, +) { + const { beforeSend, beforeSendTransaction } = options; + if (isErrorEvent(event) && beforeSend) { + return beforeSend(event, hint); + } -var Type = __nccwpck_require__(57480); + if (isTransactionEvent(event) && beforeSendTransaction) { + if (event.spans) { + // We store the # of spans before processing in SDK metadata, + // so we can compare it afterwards to determine how many spans were dropped + const spanCountBefore = event.spans.length; + event.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + spanCountBeforeProcessing: spanCountBefore, + }; + } + return beforeSendTransaction(event, hint); + } -var _toString = Object.prototype.toString; + return event; +} -function resolveYamlPairs(data) { - if (data === null) return true; +function isErrorEvent(event) { + return event.type === undefined; +} - var index, length, pair, keys, result, - object = data; +function isTransactionEvent(event) { + return event.type === 'transaction'; +} - result = new Array(object.length); +/** + * Add an event processor to the current client. + * This event processor will run for all events processed by this client. + */ +function addEventProcessor(callback) { + const client = exports$1.getClient(); - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; + if (!client || !client.addEventProcessor) { + return; + } - if (_toString.call(pair) !== '[object Object]') return false; + client.addEventProcessor(callback); +} - keys = Object.keys(pair); +exports.BaseClient = BaseClient; +exports.addEventProcessor = addEventProcessor; +//# sourceMappingURL=baseclient.js.map - if (keys.length !== 1) return false; - result[index] = [ keys[0], pair[keys[0]] ]; - } +/***/ }), - return true; -} +/***/ 74109: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function constructYamlPairs(data) { - if (data === null) return []; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var index, length, pair, keys, result, - object = data; +const utils = __nccwpck_require__(25304); - result = new Array(object.length); +/** + * Create envelope from check in item. + */ +function createCheckInEnvelope( + checkIn, + dynamicSamplingContext, + metadata, + tunnel, + dsn, +) { + const headers = { + sent_at: new Date().toISOString(), + }; - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; + if (metadata && metadata.sdk) { + headers.sdk = { + name: metadata.sdk.name, + version: metadata.sdk.version, + }; + } - keys = Object.keys(pair); + if (!!tunnel && !!dsn) { + headers.dsn = utils.dsnToString(dsn); + } - result[index] = [ keys[0], pair[keys[0]] ]; + if (dynamicSamplingContext) { + headers.trace = utils.dropUndefinedKeys(dynamicSamplingContext) ; } - return result; + const item = createCheckInEnvelopeItem(checkIn); + return utils.createEnvelope(headers, [item]); } -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); +function createCheckInEnvelopeItem(checkIn) { + const checkInHeaders = { + type: 'check_in', + }; + return [checkInHeaders, checkIn]; +} +exports.createCheckInEnvelope = createCheckInEnvelope; +//# sourceMappingURL=checkin.js.map -/***/ }), -/***/ 89695: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 647: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); -var Type = __nccwpck_require__(57480); +const DEFAULT_ENVIRONMENT = 'production'; -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); +exports.DEFAULT_ENVIRONMENT = DEFAULT_ENVIRONMENT; +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 87424: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 44220: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. + * + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. + */ +const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); -var Type = __nccwpck_require__(57480); +exports.DEBUG_BUILD = DEBUG_BUILD; +//# sourceMappingURL=debug-build.js.map -var _hasOwnProperty = Object.prototype.hasOwnProperty; -function resolveYamlSet(data) { - if (data === null) return true; +/***/ }), - var key, object = data; +/***/ 30528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return true; -} +const utils = __nccwpck_require__(25304); -function constructYamlSet(data) { - return data !== null ? data : {}; +/** + * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. + * Merge with existing data if any. + **/ +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; + } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; + event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; + return event; } -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - +/** Creates an envelope from a Session */ +function createSessionEnvelope( + session, + dsn, + metadata, + tunnel, +) { + const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata); + const envelopeHeaders = { + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && dsn && { dsn: utils.dsnToString(dsn) }), + }; -/***/ }), + const envelopeItem = + 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()]; -/***/ 32568: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return utils.createEnvelope(envelopeHeaders, [envelopeItem]); +} -"use strict"; +/** + * Create an Envelope from an event. + */ +function createEventEnvelope( + event, + dsn, + metadata, + tunnel, +) { + const sdkInfo = utils.getSdkMetadataForEnvelopeHeader(metadata); + /* + Note: Due to TS, event.type may be `replay_event`, theoretically. + In practice, we never call `createEventEnvelope` with `replay_event` type, + and we'd have to adjut a looot of types to make this work properly. + We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type) + So the safe choice is to really guard against the replay_event type here. + */ + const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event'; -var Type = __nccwpck_require__(57480); + enhanceEventWithSdkInfo(event, metadata && metadata.sdk); -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); + const envelopeHeaders = utils.createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); + // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to + // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may + // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid + // of this `delete`, lest we miss putting it back in the next time the property is in use.) + delete event.sdkProcessingMetadata; -/***/ }), + const eventItem = [{ type: eventType }, event]; + return utils.createEnvelope(envelopeHeaders, [eventItem]); +} -/***/ 9561: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.createEventEnvelope = createEventEnvelope; +exports.createSessionEnvelope = createSessionEnvelope; +//# sourceMappingURL=envelope.js.map -"use strict"; +/***/ }), -var Type = __nccwpck_require__(57480); +/***/ 57155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day +Object.defineProperty(exports, "__esModule", ({ value: true })); -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; +/** + * Returns the global event processors. + * @deprecated Global event processors will be removed in v8. + */ +function getGlobalEventProcessors() { + return utils.getGlobalSingleton('globalEventProcessors', () => []); } -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); +/** + * Add a EventProcessor to be kept globally. + * @deprecated Use `addEventProcessor` instead. Global event processors will be removed in v8. + */ +function addGlobalEventProcessor(callback) { + // eslint-disable-next-line deprecation/deprecation + getGlobalEventProcessors().push(callback); +} - // match: [1] year [2] month [3] day +/** + * Process an array of event processors, returning the processed event (or `null` if the event was dropped). + */ +function notifyEventProcessors( + processors, + event, + hint, + index = 0, +) { + return new utils.SyncPromise((resolve, reject) => { + const processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } else { + const result = processor({ ...event }, hint) ; - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); + debugBuild.DEBUG_BUILD && processor.id && result === null && utils.logger.log(`Event processor "${processor.id}" dropped event`); - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } + if (utils.isThenable(result)) { + void result + .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) + .then(null, reject); + } else { + void notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } + }); +} - // match: [4] hour [5] minute [6] second [7] fraction +exports.addGlobalEventProcessor = addGlobalEventProcessor; +exports.getGlobalEventProcessors = getGlobalEventProcessors; +exports.notifyEventProcessors = notifyEventProcessors; +//# sourceMappingURL=eventProcessors.js.map - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } +/***/ }), - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute +/***/ 61117: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); +const utils = __nccwpck_require__(25304); +const constants = __nccwpck_require__(647); +const debugBuild = __nccwpck_require__(44220); +const hub = __nccwpck_require__(5553); +const session = __nccwpck_require__(8114); +const prepareEvent = __nccwpck_require__(64867); - if (delta) date.setTime(date.getTime() - delta); +/** + * Captures an exception event and sends it to Sentry. + * + * @param exception The exception to capture. + * @param hint Optional additional data to attach to the Sentry event. + * @returns the id of the captured Sentry event. + */ +function captureException( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + exception, + hint, +) { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().captureException(exception, prepareEvent.parseEventHintOrCaptureContext(hint)); +} - return date; +/** + * Captures a message event and sends it to Sentry. + * + * @param exception The exception to capture. + * @param captureContext Define the level of the message or pass in additional data to attach to the message. + * @returns the id of the captured message. + */ +function captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + captureContext, +) { + // This is necessary to provide explicit scopes upgrade, without changing the original + // arity of the `captureMessage(message, level)` method. + const level = typeof captureContext === 'string' ? captureContext : undefined; + const context = typeof captureContext !== 'string' ? { captureContext } : undefined; + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().captureMessage(message, level, context); } -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); +/** + * Captures a manually created event and sends it to Sentry. + * + * @param exception The event to send to Sentry. + * @param hint Optional additional data to attach to the Sentry event. + * @returns the id of the captured event. + */ +function captureEvent(event, hint) { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().captureEvent(event, hint); } -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); +/** + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. + * + * @deprecated Use getCurrentScope() directly. + */ +// eslint-disable-next-line deprecation/deprecation +function configureScope(callback) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().configureScope(callback); +} +/** + * Records a new breadcrumb which will be attached to future events. + * + * Breadcrumbs will be added to subsequent events to provide more context on + * user's actions prior to an error or crash. + * + * @param breadcrumb The breadcrumb to record. + */ +// eslint-disable-next-line deprecation/deprecation +function addBreadcrumb(breadcrumb, hint) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().addBreadcrumb(breadcrumb, hint); +} -/***/ }), +/** + * Sets context data with the given name. + * @param name of the context + * @param context Any kind of data. This data will be normalized. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any, deprecation/deprecation +function setContext(name, context) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setContext(name, context); +} -/***/ 39662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. + */ +// eslint-disable-next-line deprecation/deprecation +function setExtras(extras) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setExtras(extras); +} -module.exports = { getTransformStream }; +/** + * Set key:value that will be sent as extra data with the event. + * @param key String of extra + * @param extra Any kind of data. This data will be normalized. + */ +// eslint-disable-next-line deprecation/deprecation +function setExtra(key, extra) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setExtra(key, extra); +} -const { Transform } = __nccwpck_require__(51642); +/** + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. + */ +// eslint-disable-next-line deprecation/deprecation +function setTags(tags) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setTags(tags); +} -const prettyFactory = __nccwpck_require__(67362); -const Sentry = __nccwpck_require__(22783); +/** + * Set key:value that will be sent as tags data with the event. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key String key of tag + * @param value Value of tag + */ +// eslint-disable-next-line deprecation/deprecation +function setTag(key, value) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setTag(key, value); +} -const LEVEL_MAP = { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal", -}; +/** + * Updates user context information for future events. + * + * @param user User context object to be set in the current context. Pass `null` to unset the user. + */ +// eslint-disable-next-line deprecation/deprecation +function setUser(user) { + // eslint-disable-next-line deprecation/deprecation + hub.getCurrentHub().setUser(user); +} /** - * Implements Probot's default logging formatting and error captionaing using Sentry. + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. * - * @param {import("./").Options} options - * @returns Transform - * @see https://getpino.io/#/docs/transports + * This is essentially a convenience function for: + * + * pushScope(); + * callback(); + * popScope(); */ -function getTransformStream(options = {}) { - const formattingEnabled = options.logFormat !== "json"; - const levelAsString = options.logLevelInString; - const sentryEnabled = !!options.sentryDsn; +/** + * Either creates a new active scope, or sets the given scope as active scope in the given callback. + */ +function withScope( + ...rest +) { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); - if (sentryEnabled) { - Sentry.init({ - dsn: options.sentryDsn, - // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 - // 6 is enough to serialize the deepest property across all GitHub Event payloads - normalizeDepth: 6, + // If a scope is defined, we want to make this the active scope instead of the default one + if (rest.length === 2) { + const [scope, callback] = rest; + if (!scope) { + // eslint-disable-next-line deprecation/deprecation + return hub$1.withScope(callback); + } + + // eslint-disable-next-line deprecation/deprecation + return hub$1.withScope(() => { + // eslint-disable-next-line deprecation/deprecation + hub$1.getStackTop().scope = scope ; + return callback(scope ); }); } - const pretty = prettyFactory({ - ignore: [ - // default pino keys - "time", - "pid", - "hostname", - // remove keys from pino-http - "req", - "res", - "responseTime", - ].join(","), - errorProps: ["event", "status", "headers", "request", "sentryEventId"].join( - "," - ), - }); - - return new Transform({ - objectMode: true, - transform(chunk, enc, cb) { - const line = chunk.toString().trim(); - - /* istanbul ignore if */ - if (line === undefined) return cb(); + // eslint-disable-next-line deprecation/deprecation + return hub$1.withScope(rest[0]); +} - const data = sentryEnabled ? JSON.parse(line) : null; +/** + * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no + * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the + * case, for example, in the browser). + * + * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour. + * + * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in "normal" + * applications directly because it comes with pitfalls. Use at your own risk! + * + * @param callback The callback in which the passed isolation scope is active. (Note: In environments without async + * context strategy, the currently active isolation scope may change within execution of the callback.) + * @returns The same value that `callback` returns. + */ +function withIsolationScope(callback) { + return hub.runWithAsyncContext(() => { + return callback(hub.getIsolationScope()); + }); +} - if (!sentryEnabled || data.level < 50) { - if (formattingEnabled) { - return cb(null, pretty(line)); - } +/** + * Forks the current scope and sets the provided span as active span in the context of the provided callback. + * + * @param span Spans started in the context of the provided callback will be children of this span. + * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope. + * @returns the value returned from the provided callback function. + */ +function withActiveSpan(span, callback) { + return withScope(scope => { + // eslint-disable-next-line deprecation/deprecation + scope.setSpan(span); + return callback(scope); + }); +} - if (levelAsString) { - return cb(null, stringifyLogLevel(JSON.parse(line))); - } - - cb(null, line + "\n"); - return; - } - - Sentry.withScope(function (scope) { - const sentryLevelName = - data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; - scope.setLevel(sentryLevelName); - - for (const extra of ["event", "headers", "request", "status"]) { - if (!data[extra]) continue; - - scope.setExtra(extra, data[extra]); - } - - // set user id and username to installation ID and account login - if (data.event && data.event.payload) { - const { - // When GitHub App is installed organization wide - installation: { id, account: { login: account } = {} } = {}, - - // When the repository belongs to an organization - organization: { login: organization } = {}, - // When the repository belongs to a user - repository: { owner: { login: owner } = {} } = {}, - } = data.event.payload; +/** + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call + * `startTransaction` directly on the hub. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started + * + * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. + */ +function startTransaction( + context, + customSamplingContext, + // eslint-disable-next-line deprecation/deprecation +) { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().startTransaction({ ...context }, customSamplingContext); +} - scope.setUser({ - id: id, - username: account || organization || owner, - }); - } +/** + * Create a cron monitor check in and send it to Sentry. + * + * @param checkIn An object that describes a check in. + * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want + * to create a monitor automatically when sending a check in. + */ +function captureCheckIn(checkIn, upsertMonitorConfig) { + const scope = getCurrentScope(); + const client = getClient(); + if (!client) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot capture check-in. No client defined.'); + } else if (!client.captureCheckIn) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot capture check-in. Client does not support sending check-ins.'); + } else { + return client.captureCheckIn(checkIn, upsertMonitorConfig, scope); + } - const sentryEventId = Sentry.captureException(toSentryError(data)); + return utils.uuid4(); +} - // reduce logging data and add reference to sentry event instead - if (data.event) { - data.event = { id: data.event.id }; - } - if (data.request) { - data.request = { - method: data.request.method, - url: data.request.url, - }; - } - data.sentryEventId = sentryEventId; +/** + * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes. + * + * @param monitorSlug The distinct slug of the monitor. + * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want + * to create a monitor automatically when sending a check in. + */ +function withMonitor( + monitorSlug, + callback, + upsertMonitorConfig, +) { + const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig); + const now = utils.timestampInSeconds(); - if (formattingEnabled) { - return cb(null, pretty(data)); - } + function finishCheckIn(status) { + captureCheckIn({ monitorSlug, status, checkInId, duration: utils.timestampInSeconds() - now }); + } - // istanbul ignore if - if (levelAsString) { - return cb(null, stringifyLogLevel(data)); - } + let maybePromiseResult; + try { + maybePromiseResult = callback(); + } catch (e) { + finishCheckIn('error'); + throw e; + } - cb(null, JSON.stringify(data) + "\n"); - }); - }, - }); -} + if (utils.isThenable(maybePromiseResult)) { + Promise.resolve(maybePromiseResult).then( + () => { + finishCheckIn('ok'); + }, + () => { + finishCheckIn('error'); + }, + ); + } else { + finishCheckIn('ok'); + } -function stringifyLogLevel(data) { - data.level = LEVEL_MAP[data.level]; - return JSON.stringify(data) + "\n"; + return maybePromiseResult; } -function toSentryError(data) { - const error = new Error(data.msg); - error.name = data.type; - error.stack = data.stack; - return error; +/** + * Call `flush()` on the current client, if there is one. See {@link Client.flush}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause + * the client to wait until all events are sent before resolving the promise. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +async function flush(timeout) { + const client = getClient(); + if (client) { + return client.flush(timeout); + } + debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot flush events. No client defined.'); + return Promise.resolve(false); } - -/***/ }), - -/***/ 90785: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var SENTRY_API_VERSION = '7'; /** - * Helper class to provide urls, headers and metadata that can be used to form - * different types of requests to Sentry endpoints. - * Supports both envelopes and regular event requests. + * Call `close()` on the current client, if there is one. See {@link Client.close}. * - * @deprecated Please use APIDetails - **/ -var API = /** @class */ (function () { - /** Create a new instance of API */ - function API(dsn, metadata, tunnel) { - if (metadata === void 0) { metadata = {}; } - this.dsn = dsn; - this._dsnObject = utils_1.makeDsn(dsn); - this.metadata = metadata; - this._tunnel = tunnel; - } - /** Returns the Dsn object. */ - API.prototype.getDsn = function () { - return this._dsnObject; - }; - /** Does this transport force envelopes? */ - API.prototype.forceEnvelope = function () { - return !!this._tunnel; - }; - /** Returns the prefix to construct Sentry ingestion API endpoints. */ - API.prototype.getBaseApiEndpoint = function () { - return getBaseApiEndpoint(this._dsnObject); - }; - /** Returns the store endpoint URL. */ - API.prototype.getStoreEndpoint = function () { - return getStoreEndpoint(this._dsnObject); - }; - /** - * Returns the store endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { - return getStoreEndpointWithUrlEncodedAuth(this._dsnObject); - }; - /** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { - return getEnvelopeEndpointWithUrlEncodedAuth(this._dsnObject, this._tunnel); - }; - return API; -}()); -exports.API = API; -/** Initializes API Details */ -function initAPIDetails(dsn, metadata, tunnel) { - return { - initDsn: dsn, - metadata: metadata || {}, - dsn: utils_1.makeDsn(dsn), - tunnel: tunnel, - }; -} -exports.initAPIDetails = initAPIDetails; -/** Returns the prefix to construct Sentry ingestion API endpoints. */ -function getBaseApiEndpoint(dsn) { - var protocol = dsn.protocol ? dsn.protocol + ":" : ''; - var port = dsn.port ? ":" + dsn.port : ''; - return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; -} -/** Returns the ingest API endpoint for target. */ -function _getIngestEndpoint(dsn, target) { - return "" + getBaseApiEndpoint(dsn) + dsn.projectId + "/" + target + "/"; -} -/** Returns a URL-encoded string with auth config suitable for a query string. */ -function _encodedAuth(dsn) { - return utils_1.urlEncode({ - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - sentry_version: SENTRY_API_VERSION, - }); -} -/** Returns the store endpoint URL. */ -function getStoreEndpoint(dsn) { - return _getIngestEndpoint(dsn, 'store'); + * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this + * parameter will cause the client to wait until all events are sent before disabling itself. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +async function close(timeout) { + const client = getClient(); + if (client) { + return client.close(timeout); + } + debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot flush events and disable SDK. No client defined.'); + return Promise.resolve(false); } + /** - * Returns the store endpoint URL with auth in the query string. + * This is the getter for lastEventId. * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + * @returns The last event id of a captured event. */ -function getStoreEndpointWithUrlEncodedAuth(dsn) { - return getStoreEndpoint(dsn) + "?" + _encodedAuth(dsn); -} -exports.getStoreEndpointWithUrlEncodedAuth = getStoreEndpointWithUrlEncodedAuth; -/** Returns the envelope endpoint URL. */ -function _getEnvelopeEndpoint(dsn) { - return _getIngestEndpoint(dsn, 'envelope'); +function lastEventId() { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().lastEventId(); } + /** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + * Get the currently active client. */ -function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel) { - return tunnel ? tunnel : _getEnvelopeEndpoint(dsn) + "?" + _encodedAuth(dsn); +function getClient() { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().getClient(); } -exports.getEnvelopeEndpointWithUrlEncodedAuth = getEnvelopeEndpointWithUrlEncodedAuth; + /** - * Returns an object that can be used in request headers. - * This is needed for node and the old /store endpoint in sentry + * Returns true if Sentry has been properly initialized. */ -function getRequestHeaders(dsn, clientName, clientVersion) { - // CHANGE THIS to use metadata but keep clientName and clientVersion compatible - var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; - header.push("sentry_client=" + clientName + "/" + clientVersion); - header.push("sentry_key=" + dsn.publicKey); - if (dsn.pass) { - header.push("sentry_secret=" + dsn.pass); - } - return { - 'Content-Type': 'application/json', - 'X-Sentry-Auth': header.join(', '), - }; +function isInitialized() { + return !!getClient(); } -exports.getRequestHeaders = getRequestHeaders; -/** Returns the url to the report dialog endpoint. */ -function getReportDialogEndpoint(dsnLike, dialogOptions) { - var dsn = utils_1.makeDsn(dsnLike); - var endpoint = getBaseApiEndpoint(dsn) + "embed/error-page/"; - var encodedOptions = "dsn=" + utils_1.dsnToString(dsn); - for (var key in dialogOptions) { - if (key === 'dsn') { - continue; - } - if (key === 'user') { - if (!dialogOptions.user) { - continue; - } - if (dialogOptions.user.name) { - encodedOptions += "&name=" + encodeURIComponent(dialogOptions.user.name); - } - if (dialogOptions.user.email) { - encodedOptions += "&email=" + encodeURIComponent(dialogOptions.user.email); - } - } - else { - encodedOptions += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]); - } - } - return endpoint + "?" + encodedOptions; + +/** + * Get the currently active scope. + */ +function getCurrentScope() { + // eslint-disable-next-line deprecation/deprecation + return hub.getCurrentHub().getScope(); } -exports.getReportDialogEndpoint = getReportDialogEndpoint; -//# sourceMappingURL=api.js.map -/***/ }), +/** + * Start a session on the current isolation scope. + * + * @param context (optional) additional properties to be applied to the returned session object + * + * @returns the new active session + */ +function startSession(context) { + const client = getClient(); + const isolationScope = hub.getIsolationScope(); + const currentScope = getCurrentScope(); -/***/ 25886: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const { release, environment = constants.DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {}; + + // Will fetch userAgent if called from browser sdk + const { userAgent } = utils.GLOBAL_OBJ.navigator || {}; + + const session$1 = session.makeSession({ + release, + environment, + user: currentScope.getUser() || isolationScope.getUser(), + ...(userAgent && { userAgent }), + ...context, + }); + + // End existing session if there's one + const currentSession = isolationScope.getSession(); + if (currentSession && currentSession.status === 'ok') { + session.updateSession(currentSession, { status: 'exited' }); + } + + endSession(); + + // Afterwards we set the new session on the scope + isolationScope.setSession(session$1); + + // TODO (v8): Remove this and only use the isolation scope(?). + // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() + currentScope.setSession(session$1); + + return session$1; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var api_1 = __nccwpck_require__(90785); -var request_1 = __nccwpck_require__(1553); -var noop_1 = __nccwpck_require__(68641); /** - * This is the base implemention of a Backend. - * @hidden + * End the session on the current isolation scope. */ -var BaseBackend = /** @class */ (function () { - /** Creates a new backend instance. */ - function BaseBackend(options) { - this._options = options; - if (!this._options.dsn) { - utils_1.isDebugBuild() && utils_1.logger.warn('No DSN provided, backend will not do anything.'); - } - this._transport = this._setupTransport(); - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseBackend.prototype.eventFromException = function (_exception, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromException` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendEvent = function (event) { - // TODO(v7): Remove the if-else - if (this._newTransport && - this._options.dsn && - this._options._experiments && - this._options._experiments.newTransport) { - var api = api_1.initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel); - var env = request_1.createEventEnvelope(event, api); - void this._newTransport.send(env).then(null, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error('Error while sending event:', reason); - }); - } - else { - void this._transport.sendEvent(event).then(null, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error('Error while sending event:', reason); - }); - } - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendSession = function (session) { - if (!this._transport.sendSession) { - utils_1.isDebugBuild() && utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - // TODO(v7): Remove the if-else - if (this._newTransport && - this._options.dsn && - this._options._experiments && - this._options._experiments.newTransport) { - var api = api_1.initAPIDetails(this._options.dsn, this._options._metadata, this._options.tunnel); - var _a = tslib_1.__read(request_1.createSessionEnvelope(session, api), 1), env = _a[0]; - void this._newTransport.send(env).then(null, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error('Error while sending session:', reason); - }); - } - else { - void this._transport.sendSession(session).then(null, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error('Error while sending session:', reason); - }); - } - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.getTransport = function () { - return this._transport; - }; - /** - * Sets up the transport so it can be used later to send requests. - */ - BaseBackend.prototype._setupTransport = function () { - return new noop_1.NoopTransport(); - }; - return BaseBackend; -}()); -exports.BaseBackend = BaseBackend; -//# sourceMappingURL=basebackend.js.map +function endSession() { + const isolationScope = hub.getIsolationScope(); + const currentScope = getCurrentScope(); -/***/ }), + const session$1 = currentScope.getSession() || isolationScope.getSession(); + if (session$1) { + session.closeSession(session$1); + } + _sendSessionUpdate(); -/***/ 25684: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // the session is over; take it off of the scope + isolationScope.setSession(); + + // TODO (v8): Remove this and only use the isolation scope(?). + // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() + currentScope.setSession(); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var integration_1 = __nccwpck_require__(58500); -var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; /** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding backend constructor and options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. Also, the Backend instance is available via - * {@link Client.getBackend}. - * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. - * - * Before sending an event via the backend, it is passed through - * {@link BaseClient._prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. - * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. - * - * @example - * class NodeClient extends BaseClient { - * public constructor(options: NodeOptions) { - * super(NodeBackend, options); - * } - * - * // ... - * } + * Sends the current Session on the scope */ -var BaseClient = /** @class */ (function () { - /** - * Initializes this client instance. - * - * @param backendClass A constructor function to create the backend. - * @param options Options for the client. - */ - function BaseClient(backendClass, options) { - /** Array of used integrations. */ - this._integrations = {}; - /** Number of calls being processed */ - this._numProcessing = 0; - this._backend = new backendClass(options); - this._options = options; - if (options.dsn) { - this._dsn = utils_1.makeDsn(options.dsn); - } - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseClient.prototype.captureException = function (exception, hint, scope) { - var _this = this; - // ensure we haven't captured this very object before - if (utils_1.checkOrSetAlreadyCaught(exception)) { - utils_1.isDebugBuild() && utils_1.logger.log(ALREADY_SEEN_ERROR); - return; - } - var eventId = hint && hint.event_id; - this._process(this._getBackend() - .eventFromException(exception, hint) - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureMessage = function (message, level, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - var promisedEvent = utils_1.isPrimitive(message) - ? this._getBackend().eventFromMessage(String(message), level, hint) - : this._getBackend().eventFromException(message, hint); - this._process(promisedEvent - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureEvent = function (event, hint, scope) { - // ensure we haven't captured this very object before - if (hint && hint.originalException && utils_1.checkOrSetAlreadyCaught(hint.originalException)) { - utils_1.isDebugBuild() && utils_1.logger.log(ALREADY_SEEN_ERROR); - return; - } - var eventId = hint && hint.event_id; - this._process(this._captureEvent(event, hint, scope).then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureSession = function (session) { - if (!this._isEnabled()) { - utils_1.isDebugBuild() && utils_1.logger.warn('SDK not enabled, will not capture session.'); - return; - } - if (!(typeof session.release === 'string')) { - utils_1.isDebugBuild() && utils_1.logger.warn('Discarded session because of missing or non-string release'); - } - else { - this._sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - session.update({ init: false }); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getDsn = function () { - return this._dsn; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getOptions = function () { - return this._options; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getTransport = function () { - return this._getBackend().getTransport(); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.flush = function (timeout) { - var _this = this; - return this._isClientDoneProcessing(timeout).then(function (clientFinished) { - return _this.getTransport() - .close(timeout) - .then(function (transportFlushed) { return clientFinished && transportFlushed; }); - }); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.close = function (timeout) { - var _this = this; - return this.flush(timeout).then(function (result) { - _this.getOptions().enabled = false; - return result; - }); - }; - /** - * Sets up the integrations - */ - BaseClient.prototype.setupIntegrations = function () { - if (this._isEnabled() && !this._integrations.initialized) { - this._integrations = integration_1.setupIntegrations(this._options); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getIntegration = function (integration) { - try { - return this._integrations[integration.id] || null; - } - catch (_oO) { - utils_1.isDebugBuild() && utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); - return null; - } - }; - /** Updates existing session based on the provided event */ - BaseClient.prototype._updateSessionFromEvent = function (session, event) { - var e_1, _a; - var crashed = false; - var errored = false; - var exceptions = event.exception && event.exception.values; - if (exceptions) { - errored = true; - try { - for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { - var ex = exceptions_1_1.value; - var mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); - } - finally { if (e_1) throw e_1.error; } - } - } - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - var sessionNonTerminal = session.status === 'ok'; - var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); - if (shouldUpdateAndSend) { - session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: 'crashed' })), { errors: session.errors || Number(errored || crashed) })); - this.captureSession(session); - } - }; - /** Deliver captured session to Sentry */ - BaseClient.prototype._sendSession = function (session) { - this._getBackend().sendSession(session); - }; - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - BaseClient.prototype._isClientDoneProcessing = function (timeout) { - var _this = this; - return new utils_1.SyncPromise(function (resolve) { - var ticked = 0; - var tick = 1; - var interval = setInterval(function () { - if (_this._numProcessing == 0) { - clearInterval(interval); - resolve(true); - } - else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - }; - /** Returns the current backend. */ - BaseClient.prototype._getBackend = function () { - return this._backend; - }; - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - BaseClient.prototype._isEnabled = function () { - return this.getOptions().enabled !== false && this._dsn !== undefined; - }; - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - BaseClient.prototype._prepareEvent = function (event, scope, hint) { - var _this = this; - var _a = this.getOptions(), _b = _a.normalizeDepth, normalizeDepth = _b === void 0 ? 3 : _b, _c = _a.normalizeMaxBreadth, normalizeMaxBreadth = _c === void 0 ? 1000 : _c; - var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() }); - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - var finalScope = scope; - if (hint && hint.captureContext) { - finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext); - } - // We prepare the result here with a resolved Event. - var result = utils_1.resolvedSyncPromise(prepared); - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - if (finalScope) { - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - return result.then(function (evt) { - if (evt) { - // TODO this is more of the hack trying to solve https://github.com/getsentry/sentry-javascript/issues/2809 - // it is only attached as extra data to the event if the event somehow skips being normalized - evt.sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, evt.sdkProcessingMetadata), { normalizeDepth: utils_1.normalize(normalizeDepth) }); - } - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return _this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - return evt; - }); - }; - /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event - */ - BaseClient.prototype._normalizeEvent = function (event, depth, maxBreadth) { - if (!event) { - return null; - } - var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && { - data: utils_1.normalize(b.data, depth, maxBreadth), - }))); }), - })), (event.user && { - user: utils_1.normalize(event.user, depth, maxBreadth), - })), (event.contexts && { - contexts: utils_1.normalize(event.contexts, depth, maxBreadth), - })), (event.extra && { - extra: utils_1.normalize(event.extra, depth, maxBreadth), - })); - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - normalized.contexts.trace = event.contexts.trace; - } - normalized.sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, normalized.sdkProcessingMetadata), { baseClientNormalized: true }); - return normalized; - }; - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - BaseClient.prototype._applyClientOptions = function (event) { - var options = this.getOptions(); - var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; - } - if (event.release === undefined && release !== undefined) { - event.release = release; - } - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; - } - if (event.message) { - event.message = utils_1.truncate(event.message, maxValueLength); - } - var exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = utils_1.truncate(exception.value, maxValueLength); - } - var request = event.request; - if (request && request.url) { - request.url = utils_1.truncate(request.url, maxValueLength); - } - }; - /** - * This function adds all used integrations to the SDK info in the event. - * @param event The event that will be filled with all integrations. - */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), integrationsArray); - } - }; - /** - * Tells the backend to send this event - * @param event The Sentry event to send - */ - BaseClient.prototype._sendEvent = function (event) { - this._getBackend().sendEvent(event); - }; - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - BaseClient.prototype._captureEvent = function (event, hint, scope) { - return this._processEvent(event, hint, scope).then(function (finalEvent) { - return finalEvent.event_id; - }, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error(reason); - return undefined; - }); - }; - /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. - */ - BaseClient.prototype._processEvent = function (event, hint, scope) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; - var transport = this.getTransport(); - function recordLostEvent(outcome, category) { - if (transport.recordLostEvent) { - transport.recordLostEvent(outcome, category); - } - } - if (!this._isEnabled()) { - return utils_1.rejectedSyncPromise(new utils_1.SentryError('SDK not enabled, will not capture event.')); - } - var isTransaction = event.type === 'transaction'; - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - recordLostEvent('sample_rate', 'event'); - return utils_1.rejectedSyncPromise(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")")); - } - return this._prepareEvent(event, scope, hint) - .then(function (prepared) { - if (prepared === null) { - recordLostEvent('event_processor', event.type || 'event'); - throw new utils_1.SentryError('An event processor returned null, will not send event.'); - } - var isInternalException = hint && hint.data && hint.data.__sentry__ === true; - if (isInternalException || isTransaction || !beforeSend) { - return prepared; - } - var beforeSendResult = beforeSend(prepared, hint); - return _ensureBeforeSendRv(beforeSendResult); - }) - .then(function (processedEvent) { - if (processedEvent === null) { - recordLostEvent('before_send', event.type || 'event'); - throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.'); - } - var session = scope && scope.getSession && scope.getSession(); - if (!isTransaction && session) { - _this._updateSessionFromEvent(session, processedEvent); - } - _this._sendEvent(processedEvent); - return processedEvent; - }) - .then(null, function (reason) { - if (reason instanceof utils_1.SentryError) { - throw reason; - } - _this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason, - }); - throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); - }); - }; - /** - * Occupies the client with processing and event - */ - BaseClient.prototype._process = function (promise) { - var _this = this; - this._numProcessing += 1; - void promise.then(function (value) { - _this._numProcessing -= 1; - return value; - }, function (reason) { - _this._numProcessing -= 1; - return reason; - }); - }; - return BaseClient; -}()); -exports.BaseClient = BaseClient; +function _sendSessionUpdate() { + const isolationScope = hub.getIsolationScope(); + const currentScope = getCurrentScope(); + const client = getClient(); + // TODO (v8): Remove currentScope and only use the isolation scope(?). + // For v7 though, we can't "soft-break" people using getCurrentHub().getScope().setSession() + const session = currentScope.getSession() || isolationScope.getSession(); + if (session && client && client.captureSession) { + client.captureSession(session); + } +} + /** - * Verifies that return value of configured `beforeSend` is of expected type. + * Sends the current session on the scope to Sentry + * + * @param end If set the session will be marked as exited and removed from the scope. + * Defaults to `false`. */ -function _ensureBeforeSendRv(rv) { - var nullErr = '`beforeSend` method has to return `null` or a valid event.'; - if (utils_1.isThenable(rv)) { - return rv.then(function (event) { - if (!(utils_1.isPlainObject(event) || event === null)) { - throw new utils_1.SentryError(nullErr); - } - return event; - }, function (e) { - throw new utils_1.SentryError("beforeSend rejected with " + e); - }); - } - else if (!(utils_1.isPlainObject(rv) || rv === null)) { - throw new utils_1.SentryError(nullErr); - } - return rv; +function captureSession(end = false) { + // both send the update and pull the session from the scope + if (end) { + endSession(); + return; + } + + // only send the update + _sendSessionUpdate(); } -//# sourceMappingURL=baseclient.js.map + +exports.addBreadcrumb = addBreadcrumb; +exports.captureCheckIn = captureCheckIn; +exports.captureEvent = captureEvent; +exports.captureException = captureException; +exports.captureMessage = captureMessage; +exports.captureSession = captureSession; +exports.close = close; +exports.configureScope = configureScope; +exports.endSession = endSession; +exports.flush = flush; +exports.getClient = getClient; +exports.getCurrentScope = getCurrentScope; +exports.isInitialized = isInitialized; +exports.lastEventId = lastEventId; +exports.setContext = setContext; +exports.setExtra = setExtra; +exports.setExtras = setExtras; +exports.setTag = setTag; +exports.setTags = setTags; +exports.setUser = setUser; +exports.startSession = startSession; +exports.startTransaction = startTransaction; +exports.withActiveSpan = withActiveSpan; +exports.withIsolationScope = withIsolationScope; +exports.withMonitor = withMonitor; +exports.withScope = withScope; +//# sourceMappingURL=exports.js.map + /***/ }), -/***/ 79212: +/***/ 5553: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var minimal_1 = __nccwpck_require__(88455); -exports.addBreadcrumb = minimal_1.addBreadcrumb; -exports.captureException = minimal_1.captureException; -exports.captureEvent = minimal_1.captureEvent; -exports.captureMessage = minimal_1.captureMessage; -exports.configureScope = minimal_1.configureScope; -exports.startTransaction = minimal_1.startTransaction; -exports.setContext = minimal_1.setContext; -exports.setExtra = minimal_1.setExtra; -exports.setExtras = minimal_1.setExtras; -exports.setTag = minimal_1.setTag; -exports.setTags = minimal_1.setTags; -exports.setUser = minimal_1.setUser; -exports.withScope = minimal_1.withScope; -var hub_1 = __nccwpck_require__(6393); -exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.Scope = hub_1.Scope; -exports.Session = hub_1.Session; -var api_1 = __nccwpck_require__(90785); -// eslint-disable-next-line deprecation/deprecation -exports.API = api_1.API; -exports.getEnvelopeEndpointWithUrlEncodedAuth = api_1.getEnvelopeEndpointWithUrlEncodedAuth; -exports.getStoreEndpointWithUrlEncodedAuth = api_1.getStoreEndpointWithUrlEncodedAuth; -exports.getRequestHeaders = api_1.getRequestHeaders; -exports.initAPIDetails = api_1.initAPIDetails; -exports.getReportDialogEndpoint = api_1.getReportDialogEndpoint; -var baseclient_1 = __nccwpck_require__(25684); -exports.BaseClient = baseclient_1.BaseClient; -var basebackend_1 = __nccwpck_require__(25886); -exports.BaseBackend = basebackend_1.BaseBackend; -var request_1 = __nccwpck_require__(1553); -exports.eventToSentryRequest = request_1.eventToSentryRequest; -exports.sessionToSentryRequest = request_1.sessionToSentryRequest; -var sdk_1 = __nccwpck_require__(46406); -exports.initAndBind = sdk_1.initAndBind; -var noop_1 = __nccwpck_require__(68641); -exports.NoopTransport = noop_1.NoopTransport; -var base_1 = __nccwpck_require__(309); -exports.createTransport = base_1.createTransport; -var version_1 = __nccwpck_require__(33493); -exports.SDK_VERSION = version_1.SDK_VERSION; -var Integrations = __nccwpck_require__(96727); -exports.Integrations = Integrations; -//# sourceMappingURL=index.js.map -/***/ }), +const utils = __nccwpck_require__(25304); +const constants = __nccwpck_require__(647); +const debugBuild = __nccwpck_require__(44220); +const scope = __nccwpck_require__(80022); +const session = __nccwpck_require__(8114); +const version = __nccwpck_require__(53986); -/***/ 58500: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * API compatibility version of this hub. + * + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * + * @hidden + */ +const API_VERSION = parseFloat(version.SDK_VERSION); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -exports.installedIntegrations = []; /** - * @private + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. */ -function filterDuplicates(integrations) { - return integrations.reduce(function (acc, integrations) { - if (acc.every(function (accIntegration) { return integrations.name !== accIntegration.name; })) { - acc.push(integrations); - } - return acc; - }, []); -} -/** Gets integration to install */ -function getIntegrationsToSetup(options) { - var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; - var userIntegrations = options.integrations; - var integrations = tslib_1.__spread(filterDuplicates(defaultIntegrations)); - if (Array.isArray(userIntegrations)) { - // Filter out integrations that are also included in user options - integrations = tslib_1.__spread(integrations.filter(function (integrations) { - return userIntegrations.every(function (userIntegration) { return userIntegration.name !== integrations.name; }); - }), filterDuplicates(userIntegrations)); - } - else if (typeof userIntegrations === 'function') { - integrations = userIntegrations(integrations); - integrations = Array.isArray(integrations) ? integrations : [integrations]; - } - // Make sure that if present, `Debug` integration will always run last - var integrationsNames = integrations.map(function (i) { return i.name; }); - var alwaysLastToRun = 'Debug'; - if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { - integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); - } - return integrations; -} -exports.getIntegrationsToSetup = getIntegrationsToSetup; -/** Setup given integration */ -function setupIntegration(integration) { - if (exports.installedIntegrations.indexOf(integration.name) !== -1) { - return; - } - integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); - exports.installedIntegrations.push(integration.name); - utils_1.isDebugBuild() && utils_1.logger.log("Integration installed: " + integration.name); -} -exports.setupIntegration = setupIntegration; +const DEFAULT_BREADCRUMBS = 100; + /** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations + * @deprecated The `Hub` class will be removed in version 8 of the SDK in favour of `Scope` and `Client` objects. + * + * If you previously used the `Hub` class directly, replace it with `Scope` and `Client` objects. More information: + * - [Multiple Sentry Instances](https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/) + * - [Browser Extensions](https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/) + * + * Some of our APIs are typed with the Hub class instead of the interface (e.g. `getCurrentHub`). Most of them are deprecated + * themselves and will also be removed in version 8. More information: + * - [Migration Guide](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub) */ -function setupIntegrations(options) { - var integrations = {}; - getIntegrationsToSetup(options).forEach(function (integration) { - integrations[integration.name] = integration; - setupIntegration(integration); - }); - // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty` - // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be - // considered a member of the index the way the actual integrations are - utils_1.addNonEnumerableProperty(integrations, 'initialized', true); - return integrations; -} -exports.setupIntegrations = setupIntegrations; -//# sourceMappingURL=integration.js.map +// eslint-disable-next-line deprecation/deprecation +class Hub { + /** Is a {@link Layer}[] containing the client and scope */ -/***/ }), + /** Contains the last event id of a captured event. */ -/***/ 87349: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. + * + * @deprecated Instantiation of Hub objects is deprecated and the constructor will be removed in version 8 of the SDK. + * + * If you are currently using the Hub for multi-client use like so: + * + * ``` + * // OLD + * const hub = new Hub(); + * hub.bindClient(client); + * makeMain(hub) + * ``` + * + * instead initialize the client as follows: + * + * ``` + * // NEW + * Sentry.withIsolationScope(() => { + * Sentry.setCurrentClient(client); + * client.init(); + * }); + * ``` + * + * If you are using the Hub to capture events like so: + * + * ``` + * // OLD + * const client = new Client(); + * const hub = new Hub(client); + * hub.captureException() + * ``` + * + * instead capture isolated events as follows: + * + * ``` + * // NEW + * const client = new Client(); + * const scope = new Scope(); + * scope.setClient(client); + * scope.captureException(); + * ``` + */ + constructor( + client, + scope$1, + isolationScope, + _version = API_VERSION, + ) {this._version = _version; + let assignedScope; + if (!scope$1) { + assignedScope = new scope.Scope(); + assignedScope.setClient(client); + } else { + assignedScope = scope$1; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var originalFunctionToString; -/** Patch toString calls to return proper name for wrapped functions */ -var FunctionToString = /** @class */ (function () { - function FunctionToString() { - /** - * @inheritDoc - */ - this.name = FunctionToString.id; + let assignedIsolationScope; + if (!isolationScope) { + assignedIsolationScope = new scope.Scope(); + assignedIsolationScope.setClient(client); + } else { + assignedIsolationScope = isolationScope; } - /** - * @inheritDoc - */ - FunctionToString.prototype.setupOnce = function () { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = utils_1.getOriginalFunction(this) || this; - return originalFunctionToString.apply(context, args); - }; - }; - /** - * @inheritDoc - */ - FunctionToString.id = 'FunctionToString'; - return FunctionToString; -}()); -exports.FunctionToString = FunctionToString; -//# sourceMappingURL=functiontostring.js.map -/***/ }), + this._stack = [{ scope: assignedScope }]; -/***/ 54838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -/** Inbound filters configurable by the user */ -var InboundFilters = /** @class */ (function () { - function InboundFilters(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = InboundFilters.id; - } - /** - * @inheritDoc - */ - InboundFilters.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { - addGlobalEventProcessor(function (event) { - var hub = getCurrentHub(); - if (hub) { - var self_1 = hub.getIntegration(InboundFilters); - if (self_1) { - var client = hub.getClient(); - var clientOptions = client ? client.getOptions() : {}; - var options = _mergeOptions(self_1._options, clientOptions); - return _shouldDropEvent(event, options) ? null : event; - } - } - return event; - }); - }; - /** - * @inheritDoc - */ - InboundFilters.id = 'InboundFilters'; - return InboundFilters; -}()); -exports.InboundFilters = InboundFilters; -/** JSDoc */ -function _mergeOptions(internalOptions, clientOptions) { - if (internalOptions === void 0) { internalOptions = {}; } - if (clientOptions === void 0) { clientOptions = {}; } - return { - allowUrls: tslib_1.__spread((internalOptions.whitelistUrls || []), (internalOptions.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), - denyUrls: tslib_1.__spread((internalOptions.blacklistUrls || []), (internalOptions.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), - ignoreErrors: tslib_1.__spread((internalOptions.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), - ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, - }; -} -exports._mergeOptions = _mergeOptions; -/** JSDoc */ -function _shouldDropEvent(event, options) { - if (options.ignoreInternal && _isSentryError(event)) { - utils_1.isDebugBuild() && - utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); - return true; + if (client) { + // eslint-disable-next-line deprecation/deprecation + this.bindClient(client); } - if (_isIgnoredError(event, options.ignoreErrors)) { - utils_1.isDebugBuild() && - utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); - return true; - } - if (_isDeniedUrl(event, options.denyUrls)) { - utils_1.isDebugBuild() && - utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + _getEventFilterUrl(event)); - return true; - } - if (!_isAllowedUrl(event, options.allowUrls)) { - utils_1.isDebugBuild() && - utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + _getEventFilterUrl(event)); - return true; + + this._isolationScope = assignedIsolationScope; + } + + /** + * Checks if this hub's version is older than the given version. + * + * @param version A version number to compare to. + * @return True if the given version is newer; otherwise false. + * + * @deprecated This will be removed in v8. + */ + isOlderThan(version) { + return this._version < version; + } + + /** + * This binds the given client to the current scope. + * @param client An SDK client (client) instance. + * + * @deprecated Use `initAndBind()` directly, or `setCurrentClient()` and/or `client.init()` instead. + */ + bindClient(client) { + // eslint-disable-next-line deprecation/deprecation + const top = this.getStackTop(); + top.client = client; + top.scope.setClient(client); + // eslint-disable-next-line deprecation/deprecation + if (client && client.setupIntegrations) { + // eslint-disable-next-line deprecation/deprecation + client.setupIntegrations(); } - return false; -} -exports._shouldDropEvent = _shouldDropEvent; -function _isIgnoredError(event, ignoreErrors) { - if (!ignoreErrors || !ignoreErrors.length) { - return false; + } + + /** + * @inheritDoc + * + * @deprecated Use `withScope` instead. + */ + pushScope() { + // We want to clone the content of prev scope + // eslint-disable-next-line deprecation/deprecation + const scope = this.getScope().clone(); + // eslint-disable-next-line deprecation/deprecation + this.getStack().push({ + // eslint-disable-next-line deprecation/deprecation + client: this.getClient(), + scope, + }); + return scope; + } + + /** + * @inheritDoc + * + * @deprecated Use `withScope` instead. + */ + popScope() { + // eslint-disable-next-line deprecation/deprecation + if (this.getStack().length <= 1) return false; + // eslint-disable-next-line deprecation/deprecation + return !!this.getStack().pop(); + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.withScope()` instead. + */ + withScope(callback) { + // eslint-disable-next-line deprecation/deprecation + const scope = this.pushScope(); + + let maybePromiseResult; + try { + maybePromiseResult = callback(scope); + } catch (e) { + // eslint-disable-next-line deprecation/deprecation + this.popScope(); + throw e; + } + + if (utils.isThenable(maybePromiseResult)) { + // @ts-expect-error - isThenable returns the wrong type + return maybePromiseResult.then( + res => { + // eslint-disable-next-line deprecation/deprecation + this.popScope(); + return res; + }, + e => { + // eslint-disable-next-line deprecation/deprecation + this.popScope(); + throw e; + }, + ); } - return _getPossibleEventMessages(event).some(function (message) { - return ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); + + // eslint-disable-next-line deprecation/deprecation + this.popScope(); + return maybePromiseResult; + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.getClient()` instead. + */ + getClient() { + // eslint-disable-next-line deprecation/deprecation + return this.getStackTop().client ; + } + + /** + * Returns the scope of the top stack. + * + * @deprecated Use `Sentry.getCurrentScope()` instead. + */ + getScope() { + // eslint-disable-next-line deprecation/deprecation + return this.getStackTop().scope; + } + + /** + * @deprecated Use `Sentry.getIsolationScope()` instead. + */ + getIsolationScope() { + return this._isolationScope; + } + + /** + * Returns the scope stack for domains or the process. + * @deprecated This will be removed in v8. + */ + getStack() { + return this._stack; + } + + /** + * Returns the topmost scope layer in the order domain > local > process. + * @deprecated This will be removed in v8. + */ + getStackTop() { + return this._stack[this._stack.length - 1]; + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.captureException()` instead. + */ + captureException(exception, hint) { + const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4()); + const syntheticException = new Error('Sentry syntheticException'); + // eslint-disable-next-line deprecation/deprecation + this.getScope().captureException(exception, { + originalException: exception, + syntheticException, + ...hint, + event_id: eventId, }); -} -function _isDeniedUrl(event, denyUrls) { - // TODO: Use Glob instead? - if (!denyUrls || !denyUrls.length) { - return false; + + return eventId; + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.captureMessage()` instead. + */ + captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level, + hint, + ) { + const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils.uuid4()); + const syntheticException = new Error(message); + // eslint-disable-next-line deprecation/deprecation + this.getScope().captureMessage(message, level, { + originalException: message, + syntheticException, + ...hint, + event_id: eventId, + }); + + return eventId; + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.captureEvent()` instead. + */ + captureEvent(event, hint) { + const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4(); + if (!event.type) { + this._lastEventId = eventId; } - var url = _getEventFilterUrl(event); - return !url ? false : denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); -} -function _isAllowedUrl(event, allowUrls) { - // TODO: Use Glob instead? - if (!allowUrls || !allowUrls.length) { - return true; + // eslint-disable-next-line deprecation/deprecation + this.getScope().captureEvent(event, { ...hint, event_id: eventId }); + return eventId; + } + + /** + * @inheritDoc + * + * @deprecated This will be removed in v8. + */ + lastEventId() { + return this._lastEventId; + } + + /** + * @inheritDoc + * + * @deprecated Use `Sentry.addBreadcrumb()` instead. + */ + addBreadcrumb(breadcrumb, hint) { + // eslint-disable-next-line deprecation/deprecation + const { scope, client } = this.getStackTop(); + + if (!client) return; + + const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = + (client.getOptions && client.getOptions()) || {}; + + if (maxBreadcrumbs <= 0) return; + + const timestamp = utils.dateTimestampInSeconds(); + const mergedBreadcrumb = { timestamp, ...breadcrumb }; + const finalBreadcrumb = beforeBreadcrumb + ? (utils.consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) + : mergedBreadcrumb; + + if (finalBreadcrumb === null) return; + + if (client.emit) { + client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint); } - var url = _getEventFilterUrl(event); - return !url ? true : allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); -} -function _getPossibleEventMessages(event) { - if (event.message) { - return [event.message]; + + // TODO(v8): I know this comment doesn't make much sense because the hub will be deprecated but I still wanted to + // write it down. In theory, we would have to add the breadcrumbs to the isolation scope here, however, that would + // duplicate all of the breadcrumbs. There was the possibility of adding breadcrumbs to both, the isolation scope + // and the normal scope, and deduplicating it down the line in the event processing pipeline. However, that would + // have been very fragile, because the breadcrumb objects would have needed to keep their identity all throughout + // the event processing pipeline. + // In the new implementation, the top level `Sentry.addBreadcrumb()` should ONLY write to the isolation scope. + + scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setUser()` instead. + */ + setUser(user) { + // TODO(v8): The top level `Sentry.setUser()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setUser(user); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setUser(user); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setTags()` instead. + */ + setTags(tags) { + // TODO(v8): The top level `Sentry.setTags()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setTags(tags); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setTags(tags); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setExtras()` instead. + */ + setExtras(extras) { + // TODO(v8): The top level `Sentry.setExtras()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setExtras(extras); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setExtras(extras); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setTag()` instead. + */ + setTag(key, value) { + // TODO(v8): The top level `Sentry.setTag()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setTag(key, value); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setTag(key, value); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setExtra()` instead. + */ + setExtra(key, extra) { + // TODO(v8): The top level `Sentry.setExtra()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setExtra(key, extra); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setExtra(key, extra); + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.setContext()` instead. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setContext(name, context) { + // TODO(v8): The top level `Sentry.setContext()` function should write ONLY to the isolation scope. + // eslint-disable-next-line deprecation/deprecation + this.getScope().setContext(name, context); + // eslint-disable-next-line deprecation/deprecation + this.getIsolationScope().setContext(name, context); + } + + /** + * @inheritDoc + * + * @deprecated Use `getScope()` directly. + */ + configureScope(callback) { + // eslint-disable-next-line deprecation/deprecation + const { scope, client } = this.getStackTop(); + if (client) { + callback(scope); } - if (event.exception) { - try { - var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; - return ["" + value, type + ": " + value]; - } - catch (oO) { - utils_1.isDebugBuild() && utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); - return []; - } + } + + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + run(callback) { + // eslint-disable-next-line deprecation/deprecation + const oldHub = makeMain(this); + try { + callback(this); + } finally { + // eslint-disable-next-line deprecation/deprecation + makeMain(oldHub); } - return []; -} -function _isSentryError(event) { + } + + /** + * @inheritDoc + * @deprecated Use `Sentry.getClient().getIntegrationByName()` instead. + */ + getIntegration(integration) { + // eslint-disable-next-line deprecation/deprecation + const client = this.getClient(); + if (!client) return null; try { - // @ts-ignore can't be a sentry error if undefined - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return event.exception.values[0].type === 'SentryError'; + // eslint-disable-next-line deprecation/deprecation + return client.getIntegration(integration); + } catch (_oO) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); + return null; } - catch (e) { - // ignore + } + + /** + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.end()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started + * + * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. + */ + startTransaction(context, customSamplingContext) { + const result = this._callExtensionMethod('startTransaction', context, customSamplingContext); + + if (debugBuild.DEBUG_BUILD && !result) { + // eslint-disable-next-line deprecation/deprecation + const client = this.getClient(); + if (!client) { + utils.logger.warn( + "Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'", + ); + } else { + utils.logger.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init': +Sentry.addTracingExtensions(); +Sentry.init({...}); +`); + } } - return false; -} -function _getLastValidUrl(frames) { - if (frames === void 0) { frames = []; } - for (var i = frames.length - 1; i >= 0; i--) { - var frame = frames[i]; - if (frame && frame.filename !== '' && frame.filename !== '[native code]') { - return frame.filename || null; - } + + return result; + } + + /** + * @inheritDoc + * @deprecated Use `spanToTraceHeader()` instead. + */ + traceHeaders() { + return this._callExtensionMethod('traceHeaders'); + } + + /** + * @inheritDoc + * + * @deprecated Use top level `captureSession` instead. + */ + captureSession(endSession = false) { + // both send the update and pull the session from the scope + if (endSession) { + // eslint-disable-next-line deprecation/deprecation + return this.endSession(); } - return null; -} -function _getEventFilterUrl(event) { - try { - if (event.stacktrace) { - return _getLastValidUrl(event.stacktrace.frames); - } - var frames_1; - try { - // @ts-ignore we only care about frames if the whole thing here is defined - frames_1 = event.exception.values[0].stacktrace.frames; - } - catch (e) { - // ignore - } - return frames_1 ? _getLastValidUrl(frames_1) : null; + + // only send the update + this._sendSessionUpdate(); + } + + /** + * @inheritDoc + * @deprecated Use top level `endSession` instead. + */ + endSession() { + // eslint-disable-next-line deprecation/deprecation + const layer = this.getStackTop(); + const scope = layer.scope; + const session$1 = scope.getSession(); + if (session$1) { + session.closeSession(session$1); } - catch (oO) { - utils_1.isDebugBuild() && utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); - return null; + this._sendSessionUpdate(); + + // the session is over; take it off of the scope + scope.setSession(); + } + + /** + * @inheritDoc + * @deprecated Use top level `startSession` instead. + */ + startSession(context) { + // eslint-disable-next-line deprecation/deprecation + const { scope, client } = this.getStackTop(); + const { release, environment = constants.DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {}; + + // Will fetch userAgent if called from browser sdk + const { userAgent } = utils.GLOBAL_OBJ.navigator || {}; + + const session$1 = session.makeSession({ + release, + environment, + user: scope.getUser(), + ...(userAgent && { userAgent }), + ...context, + }); + + // End existing session if there's one + const currentSession = scope.getSession && scope.getSession(); + if (currentSession && currentSession.status === 'ok') { + session.updateSession(currentSession, { status: 'exited' }); } -} -//# sourceMappingURL=inboundfilters.js.map + // eslint-disable-next-line deprecation/deprecation + this.endSession(); -/***/ }), + // Afterwards we set the new session on the scope + scope.setSession(session$1); -/***/ 96727: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return session$1; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var functiontostring_1 = __nccwpck_require__(87349); -exports.FunctionToString = functiontostring_1.FunctionToString; -var inboundfilters_1 = __nccwpck_require__(54838); -exports.InboundFilters = inboundfilters_1.InboundFilters; -//# sourceMappingURL=index.js.map + /** + * Returns if default PII should be sent to Sentry and propagated in ourgoing requests + * when Tracing is used. + * + * @deprecated Use top-level `getClient().getOptions().sendDefaultPii` instead. This function + * only unnecessarily increased API surface but only wrapped accessing the option. + */ + shouldSendDefaultPii() { + // eslint-disable-next-line deprecation/deprecation + const client = this.getClient(); + const options = client && client.getOptions(); + return Boolean(options && options.sendDefaultPii); + } -/***/ }), + /** + * Sends the current Session on the scope + */ + _sendSessionUpdate() { + // eslint-disable-next-line deprecation/deprecation + const { scope, client } = this.getStackTop(); -/***/ 1553: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const session = scope.getSession(); + if (session && client && client.captureSession) { + client.captureSession(session); + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var api_1 = __nccwpck_require__(90785); -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(api) { - if (!api.metadata || !api.metadata.sdk) { - return; + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _callExtensionMethod(method, ...args) { + const carrier = getMainCarrier(); + const sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); } - var _a = api.metadata.sdk, name = _a.name, version = _a.version; - return { name: name, version: version }; + debugBuild.DEBUG_BUILD && utils.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); + } } + /** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. + * Returns the global shim registry. + * + * FIXME: This function is problematic, because despite always returning a valid Carrier, + * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check + * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; - } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), (sdkInfo.integrations || [])); - event.sdk.packages = tslib_1.__spread((event.sdk.packages || []), (sdkInfo.packages || [])); - return event; -} -/** Creates an envelope from a Session */ -function createSessionEnvelope(session, api) { - var sdkInfo = getSdkMetadataForEnvelopeHeader(api); - var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) })); - // I know this is hacky but we don't want to add `sessions` to request type since it's never rate limited - var type = 'aggregates' in session ? 'sessions' : 'session'; - // TODO (v7) Have to cast type because envelope items do not accept a `SentryRequestType` - var envelopeItem = [{ type: type }, session]; - var envelope = utils_1.createEnvelope(envelopeHeaders, [envelopeItem]); - return [envelope, type]; -} -exports.createSessionEnvelope = createSessionEnvelope; -/** Creates a SentryRequest from a Session. */ -function sessionToSentryRequest(session, api) { - var _a = tslib_1.__read(createSessionEnvelope(session, api), 2), envelope = _a[0], type = _a[1]; - return { - body: utils_1.serializeEnvelope(envelope), - type: type, - url: api_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel), - }; +function getMainCarrier() { + utils.GLOBAL_OBJ.__SENTRY__ = utils.GLOBAL_OBJ.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return utils.GLOBAL_OBJ; } -exports.sessionToSentryRequest = sessionToSentryRequest; + /** - * Create an Envelope from an event. Note that this is duplicated from below, - * but on purpose as this will be refactored in v7. + * Replaces the current main hub with the passed one on the global object + * + * @returns The old replaced hub + * + * @deprecated Use `setCurrentClient()` instead. */ -function createEventEnvelope(event, api) { - var sdkInfo = getSdkMetadataForEnvelopeHeader(api); - var eventType = event.type || 'event'; - var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling; - var _a = transactionSampling || {}, samplingMethod = _a.method, sampleRate = _a.rate; - // TODO: Below is a temporary hack in order to debug a serialization error - see - // https://github.com/getsentry/sentry-javascript/issues/2809, - // https://github.com/getsentry/sentry-javascript/pull/4425, and - // https://github.com/getsentry/sentry-javascript/pull/4574. - // - // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to - // throw a circular reference error. - // - // When it's time to remove it: - // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting - // `sdkProcessingMetadata` - // 2. Restore the original version of the request body, which is commented out - // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the - // baseClient tests in this package - enhanceEventWithSdkInfo(event, api.metadata.sdk); - event.tags = event.tags || {}; - event.extra = event.extra || {}; - // In theory, all events should be marked as having gone through normalization and so - // we should never set this tag/extra data - if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) { - event.tags.skippedNormalization = true; - event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset'; - } - // prevent this data from being sent to sentry - // TODO: This is NOT part of the hack - DO NOT DELETE - delete event.sdkProcessingMetadata; - var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) })); - var eventItem = [ - { - type: eventType, - sample_rates: [{ id: samplingMethod, rate: sampleRate }], - }, - event, - ]; - return utils_1.createEnvelope(envelopeHeaders, [eventItem]); +// eslint-disable-next-line deprecation/deprecation +function makeMain(hub) { + const registry = getMainCarrier(); + const oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; } -exports.createEventEnvelope = createEventEnvelope; -/** Creates a SentryRequest from an event. */ -function eventToSentryRequest(event, api) { - var sdkInfo = getSdkMetadataForEnvelopeHeader(api); - var eventType = event.type || 'event'; - var useEnvelope = eventType === 'transaction' || !!api.tunnel; - var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling; - var _a = transactionSampling || {}, samplingMethod = _a.method, sampleRate = _a.rate; - // TODO: Below is a temporary hack in order to debug a serialization error - see - // https://github.com/getsentry/sentry-javascript/issues/2809, - // https://github.com/getsentry/sentry-javascript/pull/4425, and - // https://github.com/getsentry/sentry-javascript/pull/4574. - // - // TL; DR: even though we normalize all events (which should prevent this), something is causing `JSON.stringify` to - // throw a circular reference error. - // - // When it's time to remove it: - // 1. Delete everything between here and where the request object `req` is created, EXCEPT the line deleting - // `sdkProcessingMetadata` - // 2. Restore the original version of the request body, which is commented out - // 3. Search for either of the PR URLs above and pull out the companion hacks in the browser playwright tests and the - // baseClient tests in this package - enhanceEventWithSdkInfo(event, api.metadata.sdk); - event.tags = event.tags || {}; - event.extra = event.extra || {}; - // In theory, all events should be marked as having gone through normalization and so - // we should never set this tag/extra data - if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) { - event.tags.skippedNormalization = true; - event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : 'unset'; - } - // prevent this data from being sent to sentry - // TODO: This is NOT part of the hack - DO NOT DELETE - delete event.sdkProcessingMetadata; - var body; - try { - // 99.9% of events should get through just fine - no change in behavior for them - body = JSON.stringify(event); - } - catch (err) { - // Record data about the error without replacing original event data, then force renormalization - event.tags.JSONStringifyError = true; - event.extra.JSONStringifyError = err; - try { - body = JSON.stringify(utils_1.normalize(event)); - } - catch (newErr) { - // At this point even renormalization hasn't worked, meaning something about the event data has gone very wrong. - // Time to cut our losses and record only the new error. With luck, even in the problematic cases we're trying to - // debug with this hack, we won't ever land here. - var innerErr = newErr; - body = JSON.stringify({ - message: 'JSON.stringify error after renormalization', - // setting `extra: { innerErr }` here for some reason results in an empty object, so unpack manually - extra: { message: innerErr.message, stack: innerErr.stack }, - }); - } - } - var req = { - // this is the relevant line of code before the hack was added, to make it easy to undo said hack once we've solved - // the mystery - // body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event), - body: body, - type: eventType, - url: useEnvelope - ? api_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel) - : api_1.getStoreEndpointWithUrlEncodedAuth(api.dsn), - }; - // https://develop.sentry.dev/sdk/envelopes/ - // Since we don't need to manipulate envelopes nor store them, there is no - // exported concept of an Envelope with operations including serialization and - // deserialization. Instead, we only implement a minimal subset of the spec to - // serialize events inline here. - if (useEnvelope) { - var envelopeHeaders = tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (!!api.tunnel && { dsn: utils_1.dsnToString(api.dsn) })); - var eventItem = [ - { - type: eventType, - sample_rates: [{ id: samplingMethod, rate: sampleRate }], - }, - req.body, - ]; - var envelope = utils_1.createEnvelope(envelopeHeaders, [eventItem]); - req.body = utils_1.serializeEnvelope(envelope); + +/** + * Returns the default hub instance. + * + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. + * + * @deprecated Use the respective replacement method directly instead. + */ +// eslint-disable-next-line deprecation/deprecation +function getCurrentHub() { + // Get main carrier (global for every environment) + const registry = getMainCarrier(); + + if (registry.__SENTRY__ && registry.__SENTRY__.acs) { + const hub = registry.__SENTRY__.acs.getCurrentHub(); + + if (hub) { + return hub; } - return req; + } + + // Return hub that lives on a global object + return getGlobalHub(registry); } -exports.eventToSentryRequest = eventToSentryRequest; -//# sourceMappingURL=request.js.map -/***/ }), +/** + * Get the currently active isolation scope. + * The isolation scope is active for the current exection context, + * meaning that it will remain stable for the same Hub. + */ +function getIsolationScope() { + // eslint-disable-next-line deprecation/deprecation + return getCurrentHub().getIsolationScope(); +} -/***/ 46406: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// eslint-disable-next-line deprecation/deprecation +function getGlobalHub(registry = getMainCarrier()) { + // If there's no hub, or its an old API, assign a new one + + if ( + !hasHubOnCarrier(registry) || + // eslint-disable-next-line deprecation/deprecation + getHubFromCarrier(registry).isOlderThan(API_VERSION) + ) { + // eslint-disable-next-line deprecation/deprecation + setHubOnCarrier(registry, new Hub()); + } + + // Return hub that lives on a global object + return getHubFromCarrier(registry); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); /** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. + * @private Private API with no semver guarantees! * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. + * If the carrier does not contain a hub, a new hub is created with the global hub client and scope. */ -function initAndBind(clientClass, options) { - if (options.debug === true) { - if (utils_1.isDebugBuild()) { - utils_1.logger.enable(); - } - else { - // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped - // eslint-disable-next-line no-console - console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); - } - } - var hub = hub_1.getCurrentHub(); - var scope = hub.getScope(); - if (scope) { - scope.update(options.initialScope); - } - var client = new clientClass(options); - hub.bindClient(client); +// eslint-disable-next-line deprecation/deprecation +function ensureHubOnCarrier(carrier, parent = getGlobalHub()) { + // If there's no hub on current domain, or it's an old API, assign a new one + if ( + !hasHubOnCarrier(carrier) || + // eslint-disable-next-line deprecation/deprecation + getHubFromCarrier(carrier).isOlderThan(API_VERSION) + ) { + // eslint-disable-next-line deprecation/deprecation + const client = parent.getClient(); + // eslint-disable-next-line deprecation/deprecation + const scope = parent.getScope(); + // eslint-disable-next-line deprecation/deprecation + const isolationScope = parent.getIsolationScope(); + // eslint-disable-next-line deprecation/deprecation + setHubOnCarrier(carrier, new Hub(client, scope.clone(), isolationScope.clone())); + } } -exports.initAndBind = initAndBind; -//# sourceMappingURL=sdk.js.map - -/***/ }), -/***/ 309: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * @private Private API with no semver guarantees! + * + * Sets the global async context strategy + */ +function setAsyncContextStrategy(strategy) { + // Get main carrier (global for every environment) + const registry = getMainCarrier(); + registry.__SENTRY__ = registry.__SENTRY__ || {}; + registry.__SENTRY__.acs = strategy; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -exports.ERROR_TRANSPORT_CATEGORY = 'error'; -exports.TRANSACTION_TRANSPORT_CATEGORY = 'transaction'; -exports.ATTACHMENT_TRANSPORT_CATEGORY = 'attachment'; -exports.SESSION_TRANSPORT_CATEGORY = 'session'; -exports.DEFAULT_TRANSPORT_BUFFER_SIZE = 30; /** - * Creates a `NewTransport` + * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK. * - * @param options - * @param makeRequest + * @param callback The callback to run in its own async context + * @param options Options to pass to the async context strategy + * @returns The result of the callback */ -function createTransport(options, makeRequest, buffer) { - if (buffer === void 0) { buffer = utils_1.makePromiseBuffer(options.bufferSize || exports.DEFAULT_TRANSPORT_BUFFER_SIZE); } - var rateLimits = {}; - var flush = function (timeout) { return buffer.drain(timeout); }; - function send(envelope) { - var envCategory = utils_1.getEnvelopeType(envelope); - var category = envCategory === 'event' ? 'error' : envCategory; - var request = { - category: category, - body: utils_1.serializeEnvelope(envelope), - }; - // Don't add to buffer if transport is already rate-limited - if (utils_1.isRateLimited(rateLimits, category)) { - return utils_1.rejectedSyncPromise({ - status: 'rate_limit', - reason: getRateLimitReason(rateLimits, category), - }); - } - var requestTask = function () { - return makeRequest(request).then(function (_a) { - var body = _a.body, headers = _a.headers, reason = _a.reason, statusCode = _a.statusCode; - var status = utils_1.eventStatusFromHttpCode(statusCode); - if (headers) { - rateLimits = utils_1.updateRateLimits(rateLimits, headers); - } - if (status === 'success') { - return utils_1.resolvedSyncPromise({ status: status, reason: reason }); - } - return utils_1.rejectedSyncPromise({ - status: status, - reason: reason || - body || - (status === 'rate_limit' ? getRateLimitReason(rateLimits, category) : 'Unknown transport error'), - }); - }); - }; - return buffer.add(requestTask); - } - return { - send: send, - flush: flush, - }; +function runWithAsyncContext(callback, options = {}) { + const registry = getMainCarrier(); + + if (registry.__SENTRY__ && registry.__SENTRY__.acs) { + return registry.__SENTRY__.acs.runWithAsyncContext(callback, options); + } + + // if there was no strategy, fallback to just calling the callback + return callback(); } -exports.createTransport = createTransport; -function getRateLimitReason(rateLimits, category) { - return "Too many " + category + " requests, backing off until: " + new Date(utils_1.disabledUntil(rateLimits, category)).toISOString(); + +/** + * This will tell whether a carrier has a hub on it or not + * @param carrier object + */ +function hasHubOnCarrier(carrier) { + return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); } -//# sourceMappingURL=base.js.map -/***/ }), +/** + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden + */ +// eslint-disable-next-line deprecation/deprecation +function getHubFromCarrier(carrier) { + // eslint-disable-next-line deprecation/deprecation + return utils.getGlobalSingleton('hub', () => new Hub(), carrier); +} -/***/ 68641: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + * @returns A boolean indicating success or failure + */ +// eslint-disable-next-line deprecation/deprecation +function setHubOnCarrier(carrier, hub) { + if (!carrier) return false; + const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); + __SENTRY__.hub = hub; + return true; +} + +exports.API_VERSION = API_VERSION; +exports.Hub = Hub; +exports.ensureHubOnCarrier = ensureHubOnCarrier; +exports.getCurrentHub = getCurrentHub; +exports.getHubFromCarrier = getHubFromCarrier; +exports.getIsolationScope = getIsolationScope; +exports.getMainCarrier = getMainCarrier; +exports.makeMain = makeMain; +exports.runWithAsyncContext = runWithAsyncContext; +exports.setAsyncContextStrategy = setAsyncContextStrategy; +exports.setHubOnCarrier = setHubOnCarrier; +//# sourceMappingURL=hub.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Noop transport */ -var NoopTransport = /** @class */ (function () { - function NoopTransport() { - } - /** - * @inheritDoc - */ - NoopTransport.prototype.sendEvent = function (_) { - return utils_1.resolvedSyncPromise({ - reason: 'NoopTransport: Event has been skipped because no Dsn is configured.', - status: 'skipped', - }); - }; - /** - * @inheritDoc - */ - NoopTransport.prototype.close = function (_) { - return utils_1.resolvedSyncPromise(true); - }; - return NoopTransport; -}()); -exports.NoopTransport = NoopTransport; -//# sourceMappingURL=noop.js.map /***/ }), -/***/ 33493: -/***/ ((__unused_webpack_module, exports) => { +/***/ 75062: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SDK_VERSION = '6.19.4'; -//# sourceMappingURL=version.js.map + +const hubextensions = __nccwpck_require__(69866); +const idletransaction = __nccwpck_require__(58753); +const span$1 = __nccwpck_require__(41223); +const transaction = __nccwpck_require__(85111); +const utils = __nccwpck_require__(29406); +const spanstatus = __nccwpck_require__(13973); +const trace = __nccwpck_require__(16474); +const dynamicSamplingContext = __nccwpck_require__(65372); +const measurement = __nccwpck_require__(94259); +const sampling = __nccwpck_require__(45606); +const semanticAttributes = __nccwpck_require__(52781); +const envelope = __nccwpck_require__(30528); +const exports$1 = __nccwpck_require__(61117); +const hub = __nccwpck_require__(5553); +const session = __nccwpck_require__(8114); +const sessionflusher = __nccwpck_require__(27749); +const scope = __nccwpck_require__(80022); +const eventProcessors = __nccwpck_require__(57155); +const api = __nccwpck_require__(28494); +const baseclient = __nccwpck_require__(35746); +const serverRuntimeClient = __nccwpck_require__(99508); +const sdk = __nccwpck_require__(60954); +const base = __nccwpck_require__(6424); +const offline = __nccwpck_require__(91386); +const multiplexed = __nccwpck_require__(36228); +const version = __nccwpck_require__(53986); +const integration = __nccwpck_require__(51212); +const applyScopeDataToEvent = __nccwpck_require__(47103); +const prepareEvent = __nccwpck_require__(64867); +const checkin = __nccwpck_require__(74109); +const span = __nccwpck_require__(67704); +const hasTracingEnabled = __nccwpck_require__(1295); +const isSentryRequestUrl = __nccwpck_require__(27687); +const handleCallbackErrors = __nccwpck_require__(46544); +const parameterize = __nccwpck_require__(98877); +const spanUtils = __nccwpck_require__(19925); +const getRootSpan = __nccwpck_require__(55660); +const sdkMetadata = __nccwpck_require__(30169); +const constants = __nccwpck_require__(647); +const metadata = __nccwpck_require__(20123); +const requestdata = __nccwpck_require__(95697); +const inboundfilters = __nccwpck_require__(30974); +const functiontostring = __nccwpck_require__(5094); +const linkederrors = __nccwpck_require__(51064); +const index = __nccwpck_require__(25132); +const exports$2 = __nccwpck_require__(39543); + +/** @deprecated Import the integration function directly, e.g. `inboundFiltersIntegration()` instead of `new Integrations.InboundFilter(). */ +const Integrations = index; + +exports.addTracingExtensions = hubextensions.addTracingExtensions; +exports.startIdleTransaction = hubextensions.startIdleTransaction; +exports.IdleTransaction = idletransaction.IdleTransaction; +exports.TRACING_DEFAULTS = idletransaction.TRACING_DEFAULTS; +exports.Span = span$1.Span; +exports.Transaction = transaction.Transaction; +exports.extractTraceparentData = utils.extractTraceparentData; +exports.getActiveTransaction = utils.getActiveTransaction; +Object.defineProperty(exports, "SpanStatus", ({ + enumerable: true, + get: () => spanstatus.SpanStatus +})); +exports.getSpanStatusFromHttpCode = spanstatus.getSpanStatusFromHttpCode; +exports.setHttpStatus = spanstatus.setHttpStatus; +exports.spanStatusfromHttpCode = spanstatus.spanStatusfromHttpCode; +exports.continueTrace = trace.continueTrace; +exports.getActiveSpan = trace.getActiveSpan; +exports.startActiveSpan = trace.startActiveSpan; +exports.startInactiveSpan = trace.startInactiveSpan; +exports.startSpan = trace.startSpan; +exports.startSpanManual = trace.startSpanManual; +exports.trace = trace.trace; +exports.getDynamicSamplingContextFromClient = dynamicSamplingContext.getDynamicSamplingContextFromClient; +exports.getDynamicSamplingContextFromSpan = dynamicSamplingContext.getDynamicSamplingContextFromSpan; +exports.setMeasurement = measurement.setMeasurement; +exports.isValidSampleRate = sampling.isValidSampleRate; +exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = semanticAttributes.SEMANTIC_ATTRIBUTE_PROFILE_ID; +exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP; +exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE; +exports.createEventEnvelope = envelope.createEventEnvelope; +exports.createSessionEnvelope = envelope.createSessionEnvelope; +exports.addBreadcrumb = exports$1.addBreadcrumb; +exports.captureCheckIn = exports$1.captureCheckIn; +exports.captureEvent = exports$1.captureEvent; +exports.captureException = exports$1.captureException; +exports.captureMessage = exports$1.captureMessage; +exports.captureSession = exports$1.captureSession; +exports.close = exports$1.close; +exports.configureScope = exports$1.configureScope; +exports.endSession = exports$1.endSession; +exports.flush = exports$1.flush; +exports.getClient = exports$1.getClient; +exports.getCurrentScope = exports$1.getCurrentScope; +exports.isInitialized = exports$1.isInitialized; +exports.lastEventId = exports$1.lastEventId; +exports.setContext = exports$1.setContext; +exports.setExtra = exports$1.setExtra; +exports.setExtras = exports$1.setExtras; +exports.setTag = exports$1.setTag; +exports.setTags = exports$1.setTags; +exports.setUser = exports$1.setUser; +exports.startSession = exports$1.startSession; +exports.startTransaction = exports$1.startTransaction; +exports.withActiveSpan = exports$1.withActiveSpan; +exports.withIsolationScope = exports$1.withIsolationScope; +exports.withMonitor = exports$1.withMonitor; +exports.withScope = exports$1.withScope; +exports.Hub = hub.Hub; +exports.ensureHubOnCarrier = hub.ensureHubOnCarrier; +exports.getCurrentHub = hub.getCurrentHub; +exports.getHubFromCarrier = hub.getHubFromCarrier; +exports.getIsolationScope = hub.getIsolationScope; +exports.getMainCarrier = hub.getMainCarrier; +exports.makeMain = hub.makeMain; +exports.runWithAsyncContext = hub.runWithAsyncContext; +exports.setAsyncContextStrategy = hub.setAsyncContextStrategy; +exports.setHubOnCarrier = hub.setHubOnCarrier; +exports.closeSession = session.closeSession; +exports.makeSession = session.makeSession; +exports.updateSession = session.updateSession; +exports.SessionFlusher = sessionflusher.SessionFlusher; +exports.Scope = scope.Scope; +exports.getGlobalScope = scope.getGlobalScope; +exports.setGlobalScope = scope.setGlobalScope; +exports.addGlobalEventProcessor = eventProcessors.addGlobalEventProcessor; +exports.notifyEventProcessors = eventProcessors.notifyEventProcessors; +exports.getEnvelopeEndpointWithUrlEncodedAuth = api.getEnvelopeEndpointWithUrlEncodedAuth; +exports.getReportDialogEndpoint = api.getReportDialogEndpoint; +exports.BaseClient = baseclient.BaseClient; +exports.addEventProcessor = baseclient.addEventProcessor; +exports.ServerRuntimeClient = serverRuntimeClient.ServerRuntimeClient; +exports.initAndBind = sdk.initAndBind; +exports.setCurrentClient = sdk.setCurrentClient; +exports.createTransport = base.createTransport; +exports.makeOfflineTransport = offline.makeOfflineTransport; +exports.makeMultiplexedTransport = multiplexed.makeMultiplexedTransport; +exports.SDK_VERSION = version.SDK_VERSION; +exports.addIntegration = integration.addIntegration; +exports.convertIntegrationFnToClass = integration.convertIntegrationFnToClass; +exports.defineIntegration = integration.defineIntegration; +exports.getIntegrationsToSetup = integration.getIntegrationsToSetup; +exports.applyScopeDataToEvent = applyScopeDataToEvent.applyScopeDataToEvent; +exports.mergeScopeData = applyScopeDataToEvent.mergeScopeData; +exports.prepareEvent = prepareEvent.prepareEvent; +exports.createCheckInEnvelope = checkin.createCheckInEnvelope; +exports.createSpanEnvelope = span.createSpanEnvelope; +exports.hasTracingEnabled = hasTracingEnabled.hasTracingEnabled; +exports.isSentryRequestUrl = isSentryRequestUrl.isSentryRequestUrl; +exports.handleCallbackErrors = handleCallbackErrors.handleCallbackErrors; +exports.parameterize = parameterize.parameterize; +exports.spanIsSampled = spanUtils.spanIsSampled; +exports.spanToJSON = spanUtils.spanToJSON; +exports.spanToTraceContext = spanUtils.spanToTraceContext; +exports.spanToTraceHeader = spanUtils.spanToTraceHeader; +exports.getRootSpan = getRootSpan.getRootSpan; +exports.applySdkMetadata = sdkMetadata.applySdkMetadata; +exports.DEFAULT_ENVIRONMENT = constants.DEFAULT_ENVIRONMENT; +exports.ModuleMetadata = metadata.ModuleMetadata; +exports.moduleMetadataIntegration = metadata.moduleMetadataIntegration; +exports.RequestData = requestdata.RequestData; +exports.requestDataIntegration = requestdata.requestDataIntegration; +exports.InboundFilters = inboundfilters.InboundFilters; +exports.inboundFiltersIntegration = inboundfilters.inboundFiltersIntegration; +exports.FunctionToString = functiontostring.FunctionToString; +exports.functionToStringIntegration = functiontostring.functionToStringIntegration; +exports.LinkedErrors = linkederrors.LinkedErrors; +exports.linkedErrorsIntegration = linkederrors.linkedErrorsIntegration; +exports.metrics = exports$2.metrics; +exports.Integrations = Integrations; +//# sourceMappingURL=index.js.map + /***/ }), -/***/ 53536: +/***/ 51212: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var scope_1 = __nccwpck_require__(4213); -var session_1 = __nccwpck_require__(12474); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const eventProcessors = __nccwpck_require__(57155); +const exports$1 = __nccwpck_require__(61117); +const hub = __nccwpck_require__(5553); + +const installedIntegrations = []; + +/** Map of integrations assigned to a client */ + /** - * API compatibility version of this hub. + * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to + * preseve the order of integrations in the array. * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -exports.API_VERSION = 4; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. + * @private */ -var DEFAULT_BREADCRUMBS = 100; +function filterDuplicates(integrations) { + const integrationsByName = {}; + + integrations.forEach(currentInstance => { + const { name } = currentInstance; + + const existingInstance = integrationsByName[name]; + + // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a + // default instance to overwrite an existing user instance + if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { + return; + } + + integrationsByName[name] = currentInstance; + }); + + return Object.keys(integrationsByName).map(k => integrationsByName[k]); +} + +/** Gets integrations to install */ +function getIntegrationsToSetup(options) { + const defaultIntegrations = options.defaultIntegrations || []; + const userIntegrations = options.integrations; + + // We flag default instances, so that later we can tell them apart from any user-created instances of the same class + defaultIntegrations.forEach(integration => { + integration.isDefaultInstance = true; + }); + + let integrations; + + if (Array.isArray(userIntegrations)) { + integrations = [...defaultIntegrations, ...userIntegrations]; + } else if (typeof userIntegrations === 'function') { + integrations = utils.arrayify(userIntegrations(defaultIntegrations)); + } else { + integrations = defaultIntegrations; + } + + const finalIntegrations = filterDuplicates(integrations); + + // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or + // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event + // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore + // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. + const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug'); + if (debugIndex !== -1) { + const [debugInstance] = finalIntegrations.splice(debugIndex, 1); + finalIntegrations.push(debugInstance); + } + + return finalIntegrations; +} + /** - * @inheritDoc + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations */ -var Hub = /** @class */ (function () { - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - function Hub(client, scope, _version) { - if (scope === void 0) { scope = new scope_1.Scope(); } - if (_version === void 0) { _version = exports.API_VERSION; } - this._version = _version; - /** Is a {@link Layer}[] containing the client and scope */ - this._stack = [{}]; - this.getStackTop().scope = scope; - if (client) { - this.bindClient(client); - } +function setupIntegrations(client, integrations) { + const integrationIndex = {}; + + integrations.forEach(integration => { + // guard against empty provided integrations + if (integration) { + setupIntegration(client, integration, integrationIndex); } - /** - * @inheritDoc - */ - Hub.prototype.isOlderThan = function (version) { - return this._version < version; - }; - /** - * @inheritDoc - */ - Hub.prototype.bindClient = function (client) { - var top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.pushScope = function () { - // We want to clone the content of prev scope - var scope = scope_1.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope: scope, - }); - return scope; - }; - /** - * @inheritDoc - */ - Hub.prototype.popScope = function () { - if (this.getStack().length <= 1) - return false; - return !!this.getStack().pop(); - }; - /** - * @inheritDoc - */ - Hub.prototype.withScope = function (callback) { - var scope = this.pushScope(); - try { - callback(scope); - } - finally { - this.popScope(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getClient = function () { - return this.getStackTop().client; - }; - /** Returns the scope of the top stack. */ - Hub.prototype.getScope = function () { - return this.getStackTop().scope; - }; - /** Returns the scope stack for domains or the process. */ - Hub.prototype.getStack = function () { - return this._stack; - }; - /** Returns the topmost scope layer in the order domain > local > process. */ - Hub.prototype.getStackTop = function () { - return this._stack[this._stack.length - 1]; - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Hub.prototype.captureException = function (exception, hint) { - var eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimic the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: exception, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureMessage = function (message, level, hint) { - var eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimic the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error(message); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: message, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureEvent = function (event, hint) { - var eventId = hint && hint.event_id ? hint.event_id : utils_1.uuid4(); - if (event.type !== 'transaction') { - this._lastEventId = eventId; - } - this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.lastEventId = function () { - return this._lastEventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope || !client) - return; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; - if (maxBreadcrumbs <= 0) - return; - var timestamp = utils_1.dateTimestampInSeconds(); - var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); - var finalBreadcrumb = beforeBreadcrumb - ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) - : mergedBreadcrumb; - if (finalBreadcrumb === null) - return; - scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); - }; - /** - * @inheritDoc - */ - Hub.prototype.setUser = function (user) { - var scope = this.getScope(); - if (scope) - scope.setUser(user); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTags = function (tags) { - var scope = this.getScope(); - if (scope) - scope.setTags(tags); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtras = function (extras) { - var scope = this.getScope(); - if (scope) - scope.setExtras(extras); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTag = function (key, value) { - var scope = this.getScope(); - if (scope) - scope.setTag(key, value); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtra = function (key, extra) { - var scope = this.getScope(); - if (scope) - scope.setExtra(key, extra); - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype.setContext = function (name, context) { - var scope = this.getScope(); - if (scope) - scope.setContext(name, context); - }; - /** - * @inheritDoc - */ - Hub.prototype.configureScope = function (callback) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (scope && client) { - callback(scope); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.run = function (callback) { - var oldHub = makeMain(this); - try { - callback(this); - } - finally { - makeMain(oldHub); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getIntegration = function (integration) { - var client = this.getClient(); - if (!client) - return null; - try { - return client.getIntegration(integration); - } - catch (_oO) { - utils_1.isDebugBuild() && utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); - return null; - } - }; - /** - * @inheritDoc - */ - Hub.prototype.startSpan = function (context) { - return this._callExtensionMethod('startSpan', context); - }; - /** - * @inheritDoc - */ - Hub.prototype.startTransaction = function (context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - }; - /** - * @inheritDoc - */ - Hub.prototype.traceHeaders = function () { - return this._callExtensionMethod('traceHeaders'); - }; - /** - * @inheritDoc - */ - Hub.prototype.captureSession = function (endSession) { - if (endSession === void 0) { endSession = false; } - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); - } - // only send the update - this._sendSessionUpdate(); - }; - /** - * @inheritDoc - */ - Hub.prototype.endSession = function () { - var layer = this.getStackTop(); - var scope = layer && layer.scope; - var session = scope && scope.getSession(); - if (session) { - session.close(); - } - this._sendSessionUpdate(); - // the session is over; take it off of the scope - if (scope) { - scope.setSession(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.startSession = function (context) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; - // Will fetch userAgent if called from browser sdk - var global = utils_1.getGlobalObject(); - var userAgent = (global.navigator || {}).userAgent; - var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ release: release, - environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context)); - if (scope) { - // End existing session if there's one - var currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === 'ok') { - currentSession.update({ status: 'exited' }); - } - this.endSession(); - // Afterwards we set the new session on the scope - scope.setSession(session); - } - return session; - }; - /** - * Sends the current Session on the scope - */ - Hub.prototype._sendSessionUpdate = function () { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope) - return; - var session = scope.getSession && scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); - } - } - }; - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._invokeClient = function (method) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _b = this.getStackTop(), scope = _b.scope, client = _b.client; - if (client && client[method]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); - } - }; - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._callExtensionMethod = function (method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var carrier = getMainCarrier(); - var sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); - } - utils_1.isDebugBuild() && utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); - }; - return Hub; -}()); -exports.Hub = Hub; -/** - * Returns the global shim registry. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -function getMainCarrier() { - var carrier = utils_1.getGlobalObject(); - carrier.__SENTRY__ = carrier.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return carrier; -} -exports.getMainCarrier = getMainCarrier; -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - var registry = getMainCarrier(); - var oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; + }); + + return integrationIndex; } -exports.makeMain = makeMain; + /** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. + * Execute the `afterAllSetup` hooks of the given integrations. */ -function getCurrentHub() { - // Get main carrier (global for every environment) - var registry = getMainCarrier(); - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { - setHubOnCarrier(registry, new Hub()); - } - // Prefer domains over global if they are there (applicable only to Node environment) - if (utils_1.isNodeEnv()) { - return getHubFromActiveDomain(registry); +function afterSetupIntegrations(client, integrations) { + for (const integration of integrations) { + // guard against empty provided integrations + if (integration && integration.afterAllSetup) { + integration.afterAllSetup(client); } - // Return hub that lives on a global object - return getHubFromCarrier(registry); + } } -exports.getCurrentHub = getCurrentHub; -/** - * Returns the active domain, if one exists - * @deprecated No longer used; remove in v7 - * @returns The domain, or undefined if there is no active domain - */ -// eslint-disable-next-line deprecation/deprecation -function getActiveDomain() { - utils_1.isDebugBuild() && utils_1.logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); - var sentry = getMainCarrier().__SENTRY__; - return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; + +/** Setup a single integration. */ +function setupIntegration(client, integration, integrationIndex) { + if (integrationIndex[integration.name]) { + debugBuild.DEBUG_BUILD && utils.logger.log(`Integration skipped because it was already installed: ${integration.name}`); + return; + } + integrationIndex[integration.name] = integration; + + // `setupOnce` is only called the first time + if (installedIntegrations.indexOf(integration.name) === -1) { + // eslint-disable-next-line deprecation/deprecation + integration.setupOnce(eventProcessors.addGlobalEventProcessor, hub.getCurrentHub); + installedIntegrations.push(integration.name); + } + + // `setup` is run for each client + if (integration.setup && typeof integration.setup === 'function') { + integration.setup(client); + } + + if (client.on && typeof integration.preprocessEvent === 'function') { + const callback = integration.preprocessEvent.bind(integration) ; + client.on('preprocessEvent', (event, hint) => callback(event, hint, client)); + } + + if (client.addEventProcessor && typeof integration.processEvent === 'function') { + const callback = integration.processEvent.bind(integration) ; + + const processor = Object.assign((event, hint) => callback(event, hint, client), { + id: integration.name, + }); + + client.addEventProcessor(processor); + } + + debugBuild.DEBUG_BUILD && utils.logger.log(`Integration installed: ${integration.name}`); } -exports.getActiveDomain = getActiveDomain; -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - var sentry = getMainCarrier().__SENTRY__; - var activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); - } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { - var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); - } - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } - catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); - } + +/** Add an integration to the current hub's client. */ +function addIntegration(integration) { + const client = exports$1.getClient(); + + if (!client || !client.addIntegration) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`Cannot add integration "${integration.name}" because no SDK Client is available.`); + return; + } + + client.addIntegration(integration); } -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); + +// Polyfill for Array.findIndex(), which is not supported in ES5 +function findIndex(arr, callback) { + for (let i = 0; i < arr.length; i++) { + if (callback(arr[i]) === true) { + return i; + } + } + + return -1; } + /** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden + * Convert a new integration function to the legacy class syntax. + * In v8, we can remove this and instead export the integration functions directly. + * + * @deprecated This will be removed in v8! */ -function getHubFromCarrier(carrier) { - if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) - return carrier.__SENTRY__.hub; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = new Hub(); - return carrier.__SENTRY__.hub; +function convertIntegrationFnToClass( + name, + fn, +) { + return Object.assign( + function ConvertedIntegration(...args) { + return fn(...args); + }, + { id: name }, + ) ; } -exports.getHubFromCarrier = getHubFromCarrier; + /** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - * @returns A boolean indicating success or failure + * Define an integration function that can be used to create an integration instance. + * Note that this by design hides the implementation details of the integration, as they are considered internal. */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) - return false; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = hub; - return true; +function defineIntegration(fn) { + return fn; } -exports.setHubOnCarrier = setHubOnCarrier; -//# sourceMappingURL=hub.js.map + +exports.addIntegration = addIntegration; +exports.afterSetupIntegrations = afterSetupIntegrations; +exports.convertIntegrationFnToClass = convertIntegrationFnToClass; +exports.defineIntegration = defineIntegration; +exports.getIntegrationsToSetup = getIntegrationsToSetup; +exports.installedIntegrations = installedIntegrations; +exports.setupIntegration = setupIntegration; +exports.setupIntegrations = setupIntegrations; +//# sourceMappingURL=integration.js.map + /***/ }), -/***/ 6393: +/***/ 5094: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var scope_1 = __nccwpck_require__(4213); -exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor; -exports.Scope = scope_1.Scope; -var session_1 = __nccwpck_require__(12474); -exports.Session = session_1.Session; -var sessionflusher_1 = __nccwpck_require__(99695); -exports.SessionFlusher = sessionflusher_1.SessionFlusher; -var hub_1 = __nccwpck_require__(53536); -// eslint-disable-next-line deprecation/deprecation -exports.getActiveDomain = hub_1.getActiveDomain; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.getMainCarrier = hub_1.getMainCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.setHubOnCarrier = hub_1.setHubOnCarrier; -//# sourceMappingURL=index.js.map -/***/ }), +const utils = __nccwpck_require__(25304); +const exports$1 = __nccwpck_require__(61117); +const integration = __nccwpck_require__(51212); -/***/ 4213: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +let originalFunctionToString; + +const INTEGRATION_NAME = 'FunctionToString'; + +const SETUP_CLIENTS = new WeakMap(); + +const _functionToStringIntegration = (() => { + return { + name: INTEGRATION_NAME, + setupOnce() { + // eslint-disable-next-line @typescript-eslint/unbound-method + originalFunctionToString = Function.prototype.toString; + + // intrinsics (like Function.prototype) might be immutable in some environments + // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal) + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Function.prototype.toString = function ( ...args) { + const originalFunction = utils.getOriginalFunction(this); + const context = + SETUP_CLIENTS.has(exports$1.getClient() ) && originalFunction !== undefined ? originalFunction : this; + return originalFunctionToString.apply(context, args); + }; + } catch (e) { + // ignore errors here, just don't patch this + } + }, + setup(client) { + SETUP_CLIENTS.set(client, true); + }, + }; +}) ; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -/** - * Absolute maximum number of breadcrumbs added to an event. - * The `maxBreadcrumbs` option cannot be higher than this value. - */ -var MAX_BREADCRUMBS = 100; -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -var Scope = /** @class */ (function () { - function Scope() { - /** Flag if notifying is happening. */ - this._notifyingListeners = false; - /** Callback for client to receive scope changes. */ - this._scopeListeners = []; - /** Callback list that will be called after {@link applyToEvent}. */ - this._eventProcessors = []; - /** Array of breadcrumbs. */ - this._breadcrumbs = []; - /** User */ - this._user = {}; - /** Tags */ - this._tags = {}; - /** Extra */ - this._extra = {}; - /** Contexts */ - this._contexts = {}; - /** - * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get - * sent to Sentry - */ - this._sdkProcessingMetadata = {}; - } - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - Scope.clone = function (scope) { - var newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); - newScope._tags = tslib_1.__assign({}, scope._tags); - newScope._extra = tslib_1.__assign({}, scope._extra); - newScope._contexts = tslib_1.__assign({}, scope._contexts); - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); - newScope._requestSession = scope._requestSession; - } - return newScope; - }; - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - Scope.prototype.addScopeListener = function (callback) { - this._scopeListeners.push(callback); - }; - /** - * @inheritDoc - */ - Scope.prototype.addEventProcessor = function (callback) { - this._eventProcessors.push(callback); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setUser = function (user) { - this._user = user || {}; - if (this._session) { - this._session.update({ user: user }); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getUser = function () { - return this._user; - }; - /** - * @inheritDoc - */ - Scope.prototype.getRequestSession = function () { - return this._requestSession; - }; - /** - * @inheritDoc - */ - Scope.prototype.setRequestSession = function (requestSession) { - this._requestSession = requestSession; - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTags = function (tags) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTag = function (key, value) { - var _a; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtras = function (extras) { - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtra = function (key, extra) { - var _a; - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setFingerprint = function (fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setLevel = function (level) { - this._level = level; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTransactionName = function (name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - }; - /** - * Can be removed in major version. - * @deprecated in favor of {@link this.setTransactionName} - */ - Scope.prototype.setTransaction = function (name) { - return this.setTransactionName(name); - }; - /** - * @inheritDoc - */ - Scope.prototype.setContext = function (key, context) { - var _a; - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } - else { - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSpan = function (span) { - this._span = span; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSpan = function () { - return this._span; - }; - /** - * @inheritDoc - */ - Scope.prototype.getTransaction = function () { - // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will - // have a pointer to the currently-active transaction. - var span = this.getSpan(); - return span && span.transaction; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSession = function (session) { - if (!session) { - delete this._session; - } - else { - this._session = session; - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSession = function () { - return this._session; - }; - /** - * @inheritDoc - */ - Scope.prototype.update = function (captureContext) { - if (!captureContext) { - return this; - } - if (typeof captureContext === 'function') { - var updatedScope = captureContext(this); - return updatedScope instanceof Scope ? updatedScope : this; - } - if (captureContext instanceof Scope) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; - } - if (captureContext._level) { - this._level = captureContext._level; - } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } - else if (utils_1.isPlainObject(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } - } - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clear = function () { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { - var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS; - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; - } - var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); - this._breadcrumbs = tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clearBreadcrumbs = function () { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - }; - /** - * Applies the current context and fingerprint to the event. - * Note that breadcrumbs will be added by the client. - * Also if the event has already breadcrumbs on it, we do not merge them. - * @param event Event - * @param hint May contain additional information about the original exception. - * @hidden - */ - Scope.prototype.applyToEvent = function (event, hint) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); - } - if (this._user && Object.keys(this._user).length) { - event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); - } - if (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; - } - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relies on that. - if (this._span) { - event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); - var transactionName = this._span.transaction && this._span.transaction.name; - if (transactionName) { - event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags); - } - } - this._applyFingerprint(event); - event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - event.sdkProcessingMetadata = this._sdkProcessingMetadata; - return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); - }; - /** - * Add data which will be accessible during event processing but won't get sent to Sentry - */ - Scope.prototype.setSDKProcessingMetadata = function (newData) { - this._sdkProcessingMetadata = tslib_1.__assign(tslib_1.__assign({}, this._sdkProcessingMetadata), newData); - return this; - }; - /** - * This will be called after {@link applyToEvent} is finished. - */ - Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { - var _this = this; - if (index === void 0) { index = 0; } - return new utils_1.SyncPromise(function (resolve, reject) { - var processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } - else { - var result = processor(tslib_1.__assign({}, event), hint); - if (utils_1.isThenable(result)) { - void result - .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) - .then(null, reject); - } - else { - void _this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - }; - /** - * This will be called on every set call. - */ - Scope.prototype._notifyScopeListeners = function () { - var _this = this; - // We need this check for this._notifyingListeners to be able to work on scope during updates - // If this check is not here we'll produce endless recursion when something is done with the scope - // during the callback. - if (!this._notifyingListeners) { - this._notifyingListeners = true; - this._scopeListeners.forEach(function (callback) { - callback(_this); - }); - this._notifyingListeners = false; - } - }; - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - Scope.prototype._applyFingerprint = function (event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint - ? Array.isArray(event.fingerprint) - ? event.fingerprint - : [event.fingerprint] - : []; - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); - } - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; - } - }; - return Scope; -}()); -exports.Scope = Scope; /** - * Returns the global event processors. + * Patch toString calls to return proper name for wrapped functions. + * + * ```js + * Sentry.init({ + * integrations: [ + * functionToStringIntegration(), + * ], + * }); + * ``` */ -function getGlobalEventProcessors() { - /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ - var global = utils_1.getGlobalObject(); - global.__SENTRY__ = global.__SENTRY__ || {}; - global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; - return global.__SENTRY__.globalEventProcessors; - /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ -} +const functionToStringIntegration = integration.defineIntegration(_functionToStringIntegration); + /** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add + * Patch toString calls to return proper name for wrapped functions. + * + * @deprecated Use `functionToStringIntegration()` instead. */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} -exports.addGlobalEventProcessor = addGlobalEventProcessor; -//# sourceMappingURL=scope.js.map +// eslint-disable-next-line deprecation/deprecation +const FunctionToString = integration.convertIntegrationFnToClass( + INTEGRATION_NAME, + functionToStringIntegration, +) ; -/***/ }), +// eslint-disable-next-line deprecation/deprecation -/***/ 12474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports.FunctionToString = FunctionToString; +exports.functionToStringIntegration = functionToStringIntegration; +//# sourceMappingURL=functiontostring.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** - * @inheritdoc - */ -var Session = /** @class */ (function () { - function Session(context) { - this.errors = 0; - this.sid = utils_1.uuid4(); - this.duration = 0; - this.status = 'ok'; - this.init = true; - this.ignoreDuration = false; - // Both timestamp and started are in seconds since the UNIX epoch. - var startingTime = utils_1.timestampInSeconds(); - this.timestamp = startingTime; - this.started = startingTime; - if (context) { - this.update(context); - } - } - /** JSDoc */ - // eslint-disable-next-line complexity - Session.prototype.update = function (context) { - if (context === void 0) { context = {}; } - if (context.user) { - if (!this.ipAddress && context.user.ip_address) { - this.ipAddress = context.user.ip_address; - } - if (!this.did && !context.did) { - this.did = context.user.id || context.user.email || context.user.username; - } - } - this.timestamp = context.timestamp || utils_1.timestampInSeconds(); - if (context.ignoreDuration) { - this.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); - } - if (context.init !== undefined) { - this.init = context.init; - } - if (!this.did && context.did) { - this.did = "" + context.did; - } - if (typeof context.started === 'number') { - this.started = context.started; - } - if (this.ignoreDuration) { - this.duration = undefined; - } - else if (typeof context.duration === 'number') { - this.duration = context.duration; - } - else { - var duration = this.timestamp - this.started; - this.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - this.release = context.release; - } - if (context.environment) { - this.environment = context.environment; - } - if (!this.ipAddress && context.ipAddress) { - this.ipAddress = context.ipAddress; - } - if (!this.userAgent && context.userAgent) { - this.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - this.errors = context.errors; - } - if (context.status) { - this.status = context.status; - } - }; - /** JSDoc */ - Session.prototype.close = function (status) { - if (status) { - this.update({ status: status }); - } - else if (this.status === 'ok') { - this.update({ status: 'exited' }); - } - else { - this.update(); - } - }; - /** JSDoc */ - Session.prototype.toJSON = function () { - return utils_1.dropUndefinedKeys({ - sid: "" + this.sid, - init: this.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(this.started * 1000).toISOString(), - timestamp: new Date(this.timestamp * 1000).toISOString(), - status: this.status, - errors: this.errors, - did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, - duration: this.duration, - attrs: { - release: this.release, - environment: this.environment, - ip_address: this.ipAddress, - user_agent: this.userAgent, - }, - }); - }; - return Session; -}()); -exports.Session = Session; -//# sourceMappingURL=session.js.map /***/ }), -/***/ 99695: +/***/ 30974: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var hub_1 = __nccwpck_require__(53536); -/** - * @inheritdoc - */ -var SessionFlusher = /** @class */ (function () { - function SessionFlusher(transport, attrs) { - var _this = this; - this.flushTimeout = 60; - this._pendingAggregates = {}; - this._isEnabled = true; - this._transport = transport; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(function () { return _this.flush(); }, this.flushTimeout * 1000); - this._sessionAttrs = attrs; - } - /** Sends session aggregates to Transport */ - SessionFlusher.prototype.sendSessionAggregates = function (sessionAggregates) { - if (!this._transport.sendSession) { - utils_1.isDebugBuild() && utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - void this._transport.sendSession(sessionAggregates).then(null, function (reason) { - utils_1.isDebugBuild() && utils_1.logger.error('Error while sending session:', reason); - }); - }; - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */ - SessionFlusher.prototype.flush = function () { - var sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; - } - this._pendingAggregates = {}; - this.sendSessionAggregates(sessionAggregates); - }; - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - SessionFlusher.prototype.getSessionAggregates = function () { - var _this = this; - var aggregates = Object.keys(this._pendingAggregates).map(function (key) { - return _this._pendingAggregates[parseInt(key)]; - }); - var sessionAggregates = { - attrs: this._sessionAttrs, - aggregates: aggregates, - }; - return utils_1.dropUndefinedKeys(sessionAggregates); - }; - /** JSDoc */ - SessionFlusher.prototype.close = function () { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); - }; - /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date - */ - SessionFlusher.prototype.incrementSessionStatusCount = function () { - if (!this._isEnabled) { - return; - } - var scope = hub_1.getCurrentHub().getScope(); - var requestSession = scope && scope.getRequestSession(); - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - if (scope) { - scope.setRequestSession(undefined); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - } - }; - /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received - */ - SessionFlusher.prototype._incrementSessionStatusCount = function (status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - var sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - var aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); - } - switch (status) { - case 'errored': - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case 'ok': - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - default: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; - } - }; - return SessionFlusher; -}()); -exports.SessionFlusher = SessionFlusher; -//# sourceMappingURL=sessionflusher.js.map -/***/ }), +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const integration = __nccwpck_require__(51212); -/***/ 88455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +const DEFAULT_IGNORE_ERRORS = [ + /^Script error\.?$/, + /^Javascript error: Script error\.? on line 0$/, + /^ResizeObserver loop completed with undelivered notifications.$/, + /^Cannot redefine property: googletag$/, +]; + +const DEFAULT_IGNORE_TRANSACTIONS = [ + /^.*\/healthcheck$/, + /^.*\/healthy$/, + /^.*\/live$/, + /^.*\/ready$/, + /^.*\/heartbeat$/, + /^.*\/health$/, + /^.*\/healthz$/, +]; + +/** Options for the InboundFilters integration */ + +const INTEGRATION_NAME = 'InboundFilters'; +const _inboundFiltersIntegration = ((options = {}) => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event, _hint, client) { + const clientOptions = client.getOptions(); + const mergedOptions = _mergeOptions(options, clientOptions); + return _shouldDropEvent(event, mergedOptions) ? null : event; + }, + }; +}) ; + +const inboundFiltersIntegration = integration.defineIntegration(_inboundFiltersIntegration); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -/** - * This calls a function on the current hub. - * @param method function to call on hub. - * @param args to pass to function. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function callOnHub(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var hub = hub_1.getCurrentHub(); - if (hub && hub[method]) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return hub[method].apply(hub, tslib_1.__spread(args)); - } - throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); -} -/** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @returns The generated eventId. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - var syntheticException = new Error('Sentry syntheticException'); - return callOnHub('captureException', exception, { - captureContext: captureContext, - originalException: exception, - syntheticException: syntheticException, - }); -} -exports.captureException = captureException; -/** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param Severity Define the level of the message. - * @returns The generated eventId. - */ -function captureMessage(message, captureContext) { - var syntheticException = new Error(message); - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - var level = typeof captureContext === 'string' ? captureContext : undefined; - var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; - return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context)); -} -exports.captureMessage = captureMessage; -/** - * Captures a manually created event and sends it to Sentry. - * - * @param event The event to send to Sentry. - * @returns The generated eventId. - */ -function captureEvent(event) { - return callOnHub('captureEvent', event); -} -exports.captureEvent = captureEvent; -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - callOnHub('configureScope', callback); -} -exports.configureScope = configureScope; /** - * Records a new breadcrumb which will be attached to future events. - * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. - * - * @param breadcrumb The breadcrumb to record. + * Inbound filters configurable by the user. + * @deprecated Use `inboundFiltersIntegration()` instead. */ -function addBreadcrumb(breadcrumb) { - callOnHub('addBreadcrumb', breadcrumb); +// eslint-disable-next-line deprecation/deprecation +const InboundFilters = integration.convertIntegrationFnToClass( + INTEGRATION_NAME, + inboundFiltersIntegration, +) + +; + +function _mergeOptions( + internalOptions = {}, + clientOptions = {}, +) { + return { + allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], + denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], + ignoreErrors: [ + ...(internalOptions.ignoreErrors || []), + ...(clientOptions.ignoreErrors || []), + ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS), + ], + ignoreTransactions: [ + ...(internalOptions.ignoreTransactions || []), + ...(clientOptions.ignoreTransactions || []), + ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS), + ], + ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, + }; } -exports.addBreadcrumb = addBreadcrumb; -/** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - callOnHub('setContext', name, context); + +function _shouldDropEvent(event, options) { + if (options.ignoreInternal && _isSentryError(event)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${utils.getEventDescription(event)}`); + return true; + } + if (_isIgnoredError(event, options.ignoreErrors)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${utils.getEventDescription(event)}`, + ); + return true; + } + if (_isIgnoredTransaction(event, options.ignoreTransactions)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `Event dropped due to being matched by \`ignoreTransactions\` option.\nEvent: ${utils.getEventDescription(event)}`, + ); + return true; + } + if (_isDeniedUrl(event, options.denyUrls)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${utils.getEventDescription( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + if (!_isAllowedUrl(event, options.allowUrls)) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${utils.getEventDescription( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + return false; } -exports.setContext = setContext; -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - callOnHub('setExtras', extras); + +function _isIgnoredError(event, ignoreErrors) { + // If event.type, this is not an error + if (event.type || !ignoreErrors || !ignoreErrors.length) { + return false; + } + + return _getPossibleEventMessages(event).some(message => utils.stringMatchesSomePattern(message, ignoreErrors)); } -exports.setExtras = setExtras; -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - callOnHub('setTags', tags); + +function _isIgnoredTransaction(event, ignoreTransactions) { + if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) { + return false; + } + + const name = event.transaction; + return name ? utils.stringMatchesSomePattern(name, ignoreTransactions) : false; } -exports.setTags = setTags; -/** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. - */ -function setExtra(key, extra) { - callOnHub('setExtra', key, extra); + +function _isDeniedUrl(event, denyUrls) { + // TODO: Use Glob instead? + if (!denyUrls || !denyUrls.length) { + return false; + } + const url = _getEventFilterUrl(event); + return !url ? false : utils.stringMatchesSomePattern(url, denyUrls); } -exports.setExtra = setExtra; -/** - * Set key:value that will be sent as tags data with the event. - * - * Can also be used to unset a tag, by passing `undefined`. - * - * @param key String key of tag - * @param value Value of tag - */ -function setTag(key, value) { - callOnHub('setTag', key, value); + +function _isAllowedUrl(event, allowUrls) { + // TODO: Use Glob instead? + if (!allowUrls || !allowUrls.length) { + return true; + } + const url = _getEventFilterUrl(event); + return !url ? true : utils.stringMatchesSomePattern(url, allowUrls); } -exports.setTag = setTag; -/** - * Updates user context information for future events. - * - * @param user User context object to be set in the current context. Pass `null` to unset the user. - */ -function setUser(user) { - callOnHub('setUser', user); + +function _getPossibleEventMessages(event) { + const possibleMessages = []; + + if (event.message) { + possibleMessages.push(event.message); + } + + let lastException; + try { + // @ts-expect-error Try catching to save bundle size + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + lastException = event.exception.values[event.exception.values.length - 1]; + } catch (e) { + // try catching to save bundle size checking existence of variables + } + + if (lastException) { + if (lastException.value) { + possibleMessages.push(lastException.value); + if (lastException.type) { + possibleMessages.push(`${lastException.type}: ${lastException.value}`); + } + } + } + + if (debugBuild.DEBUG_BUILD && possibleMessages.length === 0) { + utils.logger.error(`Could not extract message for event ${utils.getEventDescription(event)}`); + } + + return possibleMessages; } -exports.setUser = setUser; -/** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); - * - * @param callback that will be enclosed into push/popScope. - */ -function withScope(callback) { - callOnHub('withScope', callback); + +function _isSentryError(event) { + try { + // @ts-expect-error can't be a sentry error if undefined + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return event.exception.values[0].type === 'SentryError'; + } catch (e) { + // ignore + } + return false; } -exports.withScope = withScope; -/** - * Calls a function on the latest client. Use this with caution, it's meant as - * in "internal" helper so we don't need to expose every possible function in - * the shim. It is not guaranteed that the client actually implements the - * function. - * - * @param method The method to call on the client/client. - * @param args Arguments to pass to the client/fontend. - * @hidden - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _callOnClient(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + +function _getLastValidUrl(frames = []) { + for (let i = frames.length - 1; i >= 0; i--) { + const frame = frames[i]; + + if (frame && frame.filename !== '' && frame.filename !== '[native code]') { + return frame.filename || null; } - callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); + } + + return null; } -exports._callOnClient = _callOnClient; -/** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. - * - * @returns The transaction which was just started - */ -function startTransaction(context, customSamplingContext) { - return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); + +function _getEventFilterUrl(event) { + try { + let frames; + try { + // @ts-expect-error we only care about frames if the whole thing here is defined + frames = event.exception.values[0].stacktrace.frames; + } catch (e) { + // ignore + } + return frames ? _getLastValidUrl(frames) : null; + } catch (oO) { + debugBuild.DEBUG_BUILD && utils.logger.error(`Cannot extract url for event ${utils.getEventDescription(event)}`); + return null; + } } -exports.startTransaction = startTransaction; + +exports.InboundFilters = InboundFilters; +exports.inboundFiltersIntegration = inboundFiltersIntegration; +//# sourceMappingURL=inboundfilters.js.map + + +/***/ }), + +/***/ 25132: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const functiontostring = __nccwpck_require__(5094); +const inboundfilters = __nccwpck_require__(30974); +const linkederrors = __nccwpck_require__(51064); + +/* eslint-disable deprecation/deprecation */ + +exports.FunctionToString = functiontostring.FunctionToString; +exports.InboundFilters = inboundfilters.InboundFilters; +exports.LinkedErrors = linkederrors.LinkedErrors; //# sourceMappingURL=index.js.map + /***/ }), -/***/ 40508: +/***/ 51064: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var eventbuilder_1 = __nccwpck_require__(79287); -var transports_1 = __nccwpck_require__(21437); -/** - * The Sentry Node SDK Backend. - * @hidden + +const utils = __nccwpck_require__(25304); +const integration = __nccwpck_require__(51212); + +const DEFAULT_KEY = 'cause'; +const DEFAULT_LIMIT = 5; + +const INTEGRATION_NAME = 'LinkedErrors'; + +const _linkedErrorsIntegration = ((options = {}) => { + const limit = options.limit || DEFAULT_LIMIT; + const key = options.key || DEFAULT_KEY; + + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + preprocessEvent(event, hint, client) { + const options = client.getOptions(); + + utils.applyAggregateErrorsToEvent( + utils.exceptionFromError, + options.stackParser, + options.maxValueLength, + key, + limit, + event, + hint, + ); + }, + }; +}) ; + +const linkedErrorsIntegration = integration.defineIntegration(_linkedErrorsIntegration); + +/** + * Adds SDK info to an event. + * @deprecated Use `linkedErrorsIntegration()` instead. */ -var NodeBackend = /** @class */ (function (_super) { - tslib_1.__extends(NodeBackend, _super); - function NodeBackend() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - NodeBackend.prototype.eventFromException = function (exception, hint) { - return utils_1.resolvedSyncPromise(eventbuilder_1.eventFromUnknownInput(exception, hint)); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype.eventFromMessage = function (message, level, hint) { - if (level === void 0) { level = types_1.Severity.Info; } - return utils_1.resolvedSyncPromise(eventbuilder_1.eventFromMessage(message, level, hint, this._options.attachStacktrace)); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype._setupTransport = function () { - if (!this._options.dsn) { - // We return the noop transport here in case there is no Dsn. - return _super.prototype._setupTransport.call(this); - } - var dsn = utils_1.makeDsn(this._options.dsn); - var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn, tunnel: this._options.tunnel, _metadata: this._options._metadata }); - if (this._options.transport) { - return new this._options.transport(transportOptions); - } - var api = core_1.initAPIDetails(transportOptions.dsn, transportOptions._metadata, transportOptions.tunnel); - var url = core_1.getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel); - this._newTransport = transports_1.makeNodeTransport({ - url: url, - headers: transportOptions.headers, - proxy: transportOptions.httpProxy, - caCerts: transportOptions.caCerts, - }); - if (dsn.protocol === 'http') { - return new transports_1.HTTPTransport(transportOptions); - } - return new transports_1.HTTPSTransport(transportOptions); - }; - return NodeBackend; -}(core_1.BaseBackend)); -exports.NodeBackend = NodeBackend; -//# sourceMappingURL=backend.js.map +// eslint-disable-next-line deprecation/deprecation +const LinkedErrors = integration.convertIntegrationFnToClass(INTEGRATION_NAME, linkedErrorsIntegration) + +; + +exports.LinkedErrors = LinkedErrors; +exports.linkedErrorsIntegration = linkedErrorsIntegration; +//# sourceMappingURL=linkederrors.js.map + /***/ }), -/***/ 86147: +/***/ 20123: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var backend_1 = __nccwpck_require__(40508); + +const utils = __nccwpck_require__(25304); +const integration = __nccwpck_require__(51212); +const metadata = __nccwpck_require__(35389); + +const INTEGRATION_NAME = 'ModuleMetadata'; + +const _moduleMetadataIntegration = (() => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + if (typeof client.on !== 'function') { + return; + } + + // We need to strip metadata from stack frames before sending them to Sentry since these are client side only. + client.on('beforeEnvelope', envelope => { + utils.forEachEnvelopeItem(envelope, (item, type) => { + if (type === 'event') { + const event = Array.isArray(item) ? (item )[1] : undefined; + + if (event) { + metadata.stripMetadataFromStackFrames(event); + item[1] = event; + } + } + }); + }); + }, + + processEvent(event, _hint, client) { + const stackParser = client.getOptions().stackParser; + metadata.addMetadataToStackFrames(stackParser, event); + return event; + }, + }; +}) ; + +const moduleMetadataIntegration = integration.defineIntegration(_moduleMetadataIntegration); + /** - * The Sentry Node SDK Client. + * Adds module metadata to stack frames. * - * @see NodeOptions for documentation on configuration options. - * @see SentryClient for usage documentation. + * Metadata can be injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option. + * + * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events + * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams + * our sources + * + * @deprecated Use `moduleMetadataIntegration()` instead. */ -var NodeClient = /** @class */ (function (_super) { - tslib_1.__extends(NodeClient, _super); - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - function NodeClient(options) { - var _this = this; - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: core_1.SDK_VERSION, - }, - ], - version: core_1.SDK_VERSION, - }; - _this = _super.call(this, backend_1.NodeBackend, options) || this; - return _this; - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - NodeClient.prototype.captureException = function (exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - var requestSession = scope.getRequestSession(); - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - return _super.prototype.captureException.call(this, exception, hint, scope); - }; - /** - * @inheritDoc - */ - NodeClient.prototype.captureEvent = function (event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - var eventType = event.type || 'exception'; - var isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - // If the event is of type Exception, then a request session should be captured - if (isException) { - var requestSession = scope.getRequestSession(); - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - } - return _super.prototype.captureEvent.call(this, event, hint, scope); - }; - /** - * - * @inheritdoc - */ - NodeClient.prototype.close = function (timeout) { - var _a; - (_a = this._sessionFlusher) === null || _a === void 0 ? void 0 : _a.close(); - return _super.prototype.close.call(this, timeout); - }; - /** Method that initialises an instance of SessionFlusher on Client */ - NodeClient.prototype.initSessionFlusher = function () { - var _a = this._options, release = _a.release, environment = _a.environment; - if (!release) { - utils_1.isDebugBuild() && utils_1.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } - else { - this._sessionFlusher = new hub_1.SessionFlusher(this.getTransport(), { - release: release, - environment: environment, - }); - } - }; - /** - * @inheritDoc - */ - NodeClient.prototype._prepareEvent = function (event, scope, hint) { - event.platform = event.platform || 'node'; - if (this.getOptions().serverName) { - event.server_name = this.getOptions().serverName; - } - return _super.prototype._prepareEvent.call(this, event, scope, hint); - }; - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - NodeClient.prototype._captureRequestSession = function () { - if (!this._sessionFlusher) { - utils_1.isDebugBuild() && utils_1.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } - else { - this._sessionFlusher.incrementSessionStatusCount(); - } - }; - return NodeClient; -}(core_1.BaseClient)); -exports.NodeClient = NodeClient; -//# sourceMappingURL=client.js.map +// eslint-disable-next-line deprecation/deprecation +const ModuleMetadata = integration.convertIntegrationFnToClass( + INTEGRATION_NAME, + moduleMetadataIntegration, +) + +; + +exports.ModuleMetadata = ModuleMetadata; +exports.moduleMetadataIntegration = moduleMetadataIntegration; +//# sourceMappingURL=metadata.js.map + /***/ }), -/***/ 79287: +/***/ 95697: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var stack_parser_1 = __nccwpck_require__(94854); -/** - * Extracts stack frames from the error.stack string - */ -function parseStackFrames(error) { - return utils_1.createStackParser(stack_parser_1.nodeStackParser)(error.stack || '', 1); -} -exports.parseStackFrames = parseStackFrames; + +const utils = __nccwpck_require__(25304); +const integration = __nccwpck_require__(51212); +const spanUtils = __nccwpck_require__(19925); + +const DEFAULT_OPTIONS = { + include: { + cookies: true, + data: true, + headers: true, + ip: false, + query_string: true, + url: true, + user: { + id: true, + username: true, + email: true, + }, + }, + transactionNamingScheme: 'methodPath', +}; + +const INTEGRATION_NAME = 'RequestData'; + +const _requestDataIntegration = ((options = {}) => { + const _addRequestData = utils.addRequestDataToEvent; + const _options = { + ...DEFAULT_OPTIONS, + ...options, + include: { + // @ts-expect-error It's mad because `method` isn't a known `include` key. (It's only here and not set by default in + // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) + method: true, + ...DEFAULT_OPTIONS.include, + ...options.include, + user: + options.include && typeof options.include.user === 'boolean' + ? options.include.user + : { + ...DEFAULT_OPTIONS.include.user, + // Unclear why TS still thinks `options.include.user` could be a boolean at this point + ...((options.include || {}).user ), + }, + }, + }; + + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event, _hint, client) { + // Note: In the long run, most of the logic here should probably move into the request data utility functions. For + // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. + // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once + // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) + const { transactionNamingScheme } = _options; + + const { sdkProcessingMetadata = {} } = event; + const req = sdkProcessingMetadata.request; + + if (!req) { + return event; + } + + // The Express request handler takes a similar `include` option to that which can be passed to this integration. + // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this + // integration, so that all of this passing and conversion isn't necessary + const addRequestDataOptions = + sdkProcessingMetadata.requestDataOptionsFromExpressHandler || + sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || + convertReqDataIntegrationOptsToAddReqDataOpts(_options); + + const processedEvent = _addRequestData(event, req, addRequestDataOptions); + + // Transaction events already have the right `transaction` value + if (event.type === 'transaction' || transactionNamingScheme === 'handler') { + return processedEvent; + } + + // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` + // value with a high-quality one + const reqWithTransaction = req ; + const transaction = reqWithTransaction._sentryTransaction; + if (transaction) { + const name = spanUtils.spanToJSON(transaction).description || ''; + + // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to + // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential + // to break things like alert rules.) + const shouldIncludeMethodInTransactionName = + getSDKName(client) === 'sentry.javascript.nextjs' + ? name.startsWith('/api') + : transactionNamingScheme !== 'path'; + + const [transactionValue] = utils.extractPathForTransaction(req, { + path: true, + method: shouldIncludeMethodInTransactionName, + customRoute: name, + }); + + processedEvent.transaction = transactionValue; + } + + return processedEvent; + }, + }; +}) ; + +const requestDataIntegration = integration.defineIntegration(_requestDataIntegration); + /** - * Extracts stack frames from the error and builds a Sentry Exception + * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` + * so it can be used in cross-platform SDKs like `@sentry/nextjs`. + * @deprecated Use `requestDataIntegration()` instead. */ -function exceptionFromError(error) { - var exception = { - type: error.name || error.constructor.name, - value: error.message, - }; - var frames = parseStackFrames(error); - if (frames.length) { - exception.stacktrace = { frames: frames }; +// eslint-disable-next-line deprecation/deprecation +const RequestData = integration.convertIntegrationFnToClass(INTEGRATION_NAME, requestDataIntegration) + +; + +/** Convert this integration's options to match what `addRequestDataToEvent` expects */ +/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ +function convertReqDataIntegrationOptsToAddReqDataOpts( + integrationOptions, +) { + const { + transactionNamingScheme, + include: { ip, user, ...requestOptions }, + } = integrationOptions; + + const requestIncludeKeys = []; + for (const [key, value] of Object.entries(requestOptions)) { + if (value) { + requestIncludeKeys.push(key); } - return exception; -} -exports.exceptionFromError = exceptionFromError; -/** - * Builds and Event from a Exception - * @hidden - */ -function eventFromUnknownInput(exception, hint) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var ex = exception; - var providedMechanism = hint && hint.data && hint.data.mechanism; - var mechanism = providedMechanism || { - handled: true, - type: 'generic', - }; - if (!utils_1.isError(exception)) { - if (utils_1.isPlainObject(exception)) { - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception); - hub_1.getCurrentHub().configureScope(function (scope) { - scope.setExtra('__serialized__', utils_1.normalizeToSize(exception)); - }); - ex = (hint && hint.syntheticException) || new Error(message); - ex.message = message; - } - else { - // This handles when someone does: `throw "something awesome";` - // We use synthesized Error here so we can extract a (rough) stack trace. - ex = (hint && hint.syntheticException) || new Error(exception); - ex.message = exception; - } - mechanism.synthetic = true; + } + + let addReqDataUserOpt; + if (user === undefined) { + addReqDataUserOpt = true; + } else if (typeof user === 'boolean') { + addReqDataUserOpt = user; + } else { + const userIncludeKeys = []; + for (const [key, value] of Object.entries(user)) { + if (value) { + userIncludeKeys.push(key); + } } - var event = { - exception: { - values: [exceptionFromError(ex)], - }, - }; - utils_1.addExceptionTypeValue(event, undefined, undefined); - utils_1.addExceptionMechanism(event, mechanism); - return tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id }); + addReqDataUserOpt = userIncludeKeys; + } + + return { + include: { + ip, + user: addReqDataUserOpt, + request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, + transaction: transactionNamingScheme, + }, + }; } -exports.eventFromUnknownInput = eventFromUnknownInput; -/** - * Builds and Event from a Message - * @hidden - */ -function eventFromMessage(message, level, hint, attachStacktrace) { - if (level === void 0) { level = types_1.Severity.Info; } - var event = { - event_id: hint && hint.event_id, - level: level, - message: message, - }; - if (attachStacktrace && hint && hint.syntheticException) { - var frames_1 = parseStackFrames(hint.syntheticException); - if (frames_1.length) { - event.stacktrace = { frames: frames_1 }; - } - } - return event; + +function getSDKName(client) { + try { + // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to + // write out a long chain of `a && a.b && a.b.c && ...` + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return client.getOptions()._metadata.sdk.name; + } catch (err) { + // In theory we should never get here + return undefined; + } } -exports.eventFromMessage = eventFromMessage; -//# sourceMappingURL=eventbuilder.js.map + +exports.RequestData = RequestData; +exports.requestDataIntegration = requestDataIntegration; +//# sourceMappingURL=requestdata.js.map + /***/ }), -/***/ 45400: +/***/ 35389: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var cookie = __nccwpck_require__(93658); -var domain = __nccwpck_require__(13639); -var os = __nccwpck_require__(22037); -var url = __nccwpck_require__(57310); -var sdk_1 = __nccwpck_require__(38836); -/** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` - */ -function tracingHandler() { - return function sentryTracingMiddleware(req, res, next) { - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - var traceparentData; - if (req.headers && utils_1.isString(req.headers['sentry-trace'])) { - traceparentData = utils_1.extractTraceparentData(req.headers['sentry-trace']); - } - var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData), - // extra context passed to the tracesSampler - { request: extractRequestData(req) }); - // We put the transaction on the scope so users can attach children to it - core_1.getCurrentHub().configureScope(function (scope) { - scope.setSpan(transaction); - }); - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.__sentry_transaction = transaction; - res.once('finish', function () { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(function () { - addExpressReqToTransaction(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - next(); - }; + +const utils = __nccwpck_require__(25304); + +/** Keys are source filename/url, values are metadata objects. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const filenameMetadataMap = new Map(); +/** Set of stack strings that have already been parsed. */ +const parsedStacks = new Set(); + +function ensureMetadataStacksAreParsed(parser) { + if (!utils.GLOBAL_OBJ._sentryModuleMetadata) { + return; + } + + for (const stack of Object.keys(utils.GLOBAL_OBJ._sentryModuleMetadata)) { + const metadata = utils.GLOBAL_OBJ._sentryModuleMetadata[stack]; + + if (parsedStacks.has(stack)) { + continue; + } + + // Ensure this stack doesn't get parsed again + parsedStacks.add(stack); + + const frames = parser(stack); + + // Go through the frames starting from the top of the stack and find the first one with a filename + for (const frame of frames.reverse()) { + if (frame.filename) { + // Save the metadata for this filename + filenameMetadataMap.set(frame.filename, metadata); + break; + } + } + } } -exports.tracingHandler = tracingHandler; + /** - * Set parameterized as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request + * Retrieve metadata for a specific JavaScript file URL. + * + * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option. */ -function addExpressReqToTransaction(transaction, req) { - if (!transaction) - return; - transaction.name = extractExpressTransactionName(req, { path: true, method: true }); - transaction.setData('url', req.originalUrl); - transaction.setData('baseUrl', req.baseUrl); - transaction.setData('query', req.query); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getMetadataForUrl(parser, filename) { + ensureMetadataStacksAreParsed(parser); + return filenameMetadataMap.get(filename); } + /** - * Extracts complete generalized path from the request object and uses it to construct transaction name. + * Adds metadata to stack frames. * - * eg. GET /mountpoint/user/:id - * - * @param req The ExpressRequest object - * @param options What to include in the transaction name (method, path, or both) - * - * @returns The fully constructed transaction name + * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option. */ -function extractExpressTransactionName(req, options) { - if (options === void 0) { options = {}; } - var _a; - var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(); - var path = ''; - if (req.route) { - path = "" + (req.baseUrl || '') + req.route.path; - } - else if (req.originalUrl || req.url) { - path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); - } - var info = ''; - if (options.method && method) { - info += method; - } - if (options.method && options.path) { - info += ' '; - } - if (options.path && path) { - info += path; - } - return info; -} -/** JSDoc */ -function extractTransaction(req, type) { - var _a; - switch (type) { - case 'path': { - return extractExpressTransactionName(req, { path: true }); - } - case 'handler': { - return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || ''; - } - case 'methodPath': - default: { - return extractExpressTransactionName(req, { path: true, method: true }); +function addMetadataToStackFrames(parser, event) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values.forEach(exception => { + if (!exception.stacktrace) { + return; + } + + for (const frame of exception.stacktrace.frames || []) { + if (!frame.filename) { + continue; } - } -} -/** Default user keys that'll be used to extract data from the request */ -var DEFAULT_USER_KEYS = ['id', 'username', 'email']; -/** JSDoc */ -function extractUserData(user, keys) { - var extractedUser = {}; - var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS; - attributes.forEach(function (key) { - if (user && key in user) { - extractedUser[key] = user[key]; + + const metadata = getMetadataForUrl(parser, frame.filename); + + if (metadata) { + frame.module_metadata = metadata; } + } }); - return extractedUser; + } catch (_) { + // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. + } } -/** Default request keys that'll be used to extract data from the request */ -var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; + /** - * Normalizes data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not - * provided. - * @returns An object containing normalized request data + * Strips metadata from stack frames. */ -function extractRequestData(req, keys) { - if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } - var requestData = {}; - // headers: - // node, express, nextjs: req.headers - // koa: req.header - var headers = (req.headers || req.header || {}); - // method: - // node, express, koa, nextjs: req.method - var method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - var host = req.hostname || req.host || headers.host || ''; - // protocol: - // node, nextjs: - // express, koa: req.protocol - var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted - ? 'https' - : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - var originalUrl = (req.originalUrl || req.url || ''); - // absolute url - var absoluteUrl = protocol + "://" + host + originalUrl; - keys.forEach(function (key) { - switch (key) { - case 'headers': - requestData.headers = headers; - break; - case 'method': - requestData.method = method; - break; - case 'url': - requestData.url = absoluteUrl; - break; - case 'cookies': - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || cookie.parse(headers.cookie || ''); - break; - case 'query_string': - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = req.query || url.parse(originalUrl || '', false).query; - break; - case 'data': - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = utils_1.isString(req.body) ? req.body : JSON.stringify(utils_1.normalize(req.body)); - } - break; - default: - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = req[key]; - } - } +function stripMetadataFromStackFrames(event) { + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values.forEach(exception => { + if (!exception.stacktrace) { + return; + } + + for (const frame of exception.stacktrace.frames || []) { + delete frame.module_metadata; + } }); - return requestData; + } catch (_) { + // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. + } } -exports.extractRequestData = extractRequestData; + +exports.addMetadataToStackFrames = addMetadataToStackFrames; +exports.getMetadataForUrl = getMetadataForUrl; +exports.stripMetadataFromStackFrames = stripMetadataFromStackFrames; +//# sourceMappingURL=metadata.js.map + + +/***/ }), + +/***/ 456: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils$1 = __nccwpck_require__(25304); +const constants = __nccwpck_require__(36861); +const instance = __nccwpck_require__(1709); +const metricSummary = __nccwpck_require__(3875); +const utils = __nccwpck_require__(57873); + /** - * Enriches passed event with request data. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden + * A metrics aggregator that aggregates metrics in memory and flushes them periodically. */ -function parseRequest(event, req, options) { - // eslint-disable-next-line no-param-reassign - options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options); - if (options.version) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: { - name: 'node', - version: global.process.version, - } }); - } - if (options.request) { - // if the option value is `true`, use the default set of keys by not passing anything to `extractRequestData()` - var extractedRequestData = Array.isArray(options.request) - ? extractRequestData(req, options.request) - : extractRequestData(req); - event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData); - } - if (options.serverName && !event.server_name) { - event.server_name = global.process.env.SENTRY_NAME || os.hostname(); - } - if (options.user) { - var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {}; - if (Object.keys(extractedUser)) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser); - } - } - // client ip: - // node, nextjs: req.connection.remoteAddress - // express, koa: req.ip - if (options.ip) { - var ip = req.ip || (req.connection && req.connection.remoteAddress); - if (ip) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip }); - } - } - if (options.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, options.transaction); +class MetricsAggregator { + // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets + // when the aggregator is garbage collected. + // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + + // Different metrics have different weights. We use this to limit the number of metrics + // that we store in memory. + + // Cast to any so that it can use Node.js timeout + // eslint-disable-next-line @typescript-eslint/no-explicit-any + + // SDKs are required to shift the flush interval by random() * rollup_in_seconds. + // That shift is determined once per startup to create jittering. + + // An SDK is required to perform force flushing ahead of scheduled time if the memory + // pressure is too high. There is no rule for this other than that SDKs should be tracking + // abstract aggregation complexity (eg: a counter only carries a single float, whereas a + // distribution is a float per emission). + // + // Force flush is used on either shutdown, flush() or when we exceed the max weight. + + constructor( _client) {this._client = _client; + this._buckets = new Map(); + this._bucketsTotalWeight = 0; + + this._interval = setInterval(() => this._flush(), constants.DEFAULT_FLUSH_INTERVAL) ; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (this._interval.unref) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this._interval.unref(); } - return event; -} -exports.parseRequest = parseRequest; -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler(options) { - var currentHub = core_1.getCurrentHub(); - var client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { - client.initSessionFlusher(); - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - var scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } - } - return function sentryRequestMiddleware(req, res, next) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var _end_1 = res.end; - res.end = function (chunk, encoding, cb) { - var _this = this; - void sdk_1.flush(options.flushTimeout) - .then(function () { - _end_1.call(_this, chunk, encoding, cb); - }) - .then(null, function (e) { - utils_1.isDebugBuild() && utils_1.logger.error(e); - _end_1.call(_this, chunk, encoding, cb); - }); - }; - } - var local = domain.create(); - local.add(req); - local.add(res); - local.on('error', next); - local.run(function () { - var currentHub = core_1.getCurrentHub(); - currentHub.configureScope(function (scope) { - scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); - var client = currentHub.getClient(); - if (sdk_1.isAutoSessionTrackingEnabled(client)) { - var scope_1 = currentHub.getScope(); - if (scope_1) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope_1.setRequestSession({ status: 'ok' }); - } - } - }); - res.once('finish', function () { - var client = currentHub.getClient(); - if (sdk_1.isAutoSessionTrackingEnabled(client)) { - setImmediate(function () { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && client._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - client._captureRequestSession(); - } - }); - } - }); - next(); - }); - }; -} -exports.requestHandler = requestHandler; -/** JSDoc */ -function getStatusCodeFromResponse(error) { - var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode, 10) : 500; -} -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - var status = getStatusCodeFromResponse(error); - return status >= 500; + + this._flushShift = Math.floor((Math.random() * constants.DEFAULT_FLUSH_INTERVAL) / 1000); + this._forceFlush = false; + } + + /** + * @inheritDoc + */ + add( + metricType, + unsanitizedName, + value, + unsanitizedUnit = 'none', + unsanitizedTags = {}, + maybeFloatTimestamp = utils$1.timestampInSeconds(), + ) { + const timestamp = Math.floor(maybeFloatTimestamp); + const name = utils.sanitizeMetricKey(unsanitizedName); + const tags = utils.sanitizeTags(unsanitizedTags); + const unit = utils.sanitizeUnit(unsanitizedUnit ); + + const bucketKey = utils.getBucketKey(metricType, name, unit, tags); + + let bucketItem = this._buckets.get(bucketKey); + // If this is a set metric, we need to calculate the delta from the previous weight. + const previousWeight = bucketItem && metricType === constants.SET_METRIC_TYPE ? bucketItem.metric.weight : 0; + + if (bucketItem) { + bucketItem.metric.add(value); + // TODO(abhi): Do we need this check? + if (bucketItem.timestamp < timestamp) { + bucketItem.timestamp = timestamp; + } + } else { + bucketItem = { + // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. + metric: new instance.METRIC_MAP[metricType](value), + timestamp, + metricType, + name, + unit, + tags, + }; + this._buckets.set(bucketKey, bucketItem); + } + + // If value is a string, it's a set metric so calculate the delta from the previous weight. + const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value; + metricSummary.updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey); + + // We need to keep track of the total weight of the buckets so that we can + // flush them when we exceed the max weight. + this._bucketsTotalWeight += bucketItem.metric.weight; + + if (this._bucketsTotalWeight >= constants.MAX_WEIGHT) { + this.flush(); + } + } + + /** + * Flushes the current metrics to the transport via the transport. + */ + flush() { + this._forceFlush = true; + this._flush(); + } + + /** + * Shuts down metrics aggregator and clears all metrics. + */ + close() { + this._forceFlush = true; + clearInterval(this._interval); + this._flush(); + } + + /** + * Flushes the buckets according to the internal state of the aggregator. + * If it is a force flush, which happens on shutdown, it will flush all buckets. + * Otherwise, it will only flush buckets that are older than the flush interval, + * and according to the flush shift. + * + * This function mutates `_forceFlush` and `_bucketsTotalWeight` properties. + */ + _flush() { + // TODO(@anonrig): Add Atomics for locking to avoid having force flush and regular flush + // running at the same time. + // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics + + // This path eliminates the need for checking for timestamps since we're forcing a flush. + // Remember to reset the flag, or it will always flush all metrics. + if (this._forceFlush) { + this._forceFlush = false; + this._bucketsTotalWeight = 0; + this._captureMetrics(this._buckets); + this._buckets.clear(); + return; + } + const cutoffSeconds = Math.floor(utils$1.timestampInSeconds()) - constants.DEFAULT_FLUSH_INTERVAL / 1000 - this._flushShift; + // TODO(@anonrig): Optimization opportunity. + // Convert this map to an array and store key in the bucketItem. + const flushedBuckets = new Map(); + for (const [key, bucket] of this._buckets) { + if (bucket.timestamp <= cutoffSeconds) { + flushedBuckets.set(key, bucket); + this._bucketsTotalWeight -= bucket.metric.weight; + } + } + + for (const [key] of flushedBuckets) { + this._buckets.delete(key); + } + + this._captureMetrics(flushedBuckets); + } + + /** + * Only captures a subset of the buckets passed to this function. + * @param flushedBuckets + */ + _captureMetrics(flushedBuckets) { + if (flushedBuckets.size > 0 && this._client.captureAggregateMetrics) { + // TODO(@anonrig): Optimization opportunity. + // This copy operation can be avoided if we store the key in the bucketItem. + const buckets = Array.from(flushedBuckets).map(([, bucketItem]) => bucketItem); + this._client.captureAggregateMetrics(buckets); + } + } } + +exports.MetricsAggregator = MetricsAggregator; +//# sourceMappingURL=aggregator.js.map + + +/***/ }), + +/***/ 24044: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils$1 = __nccwpck_require__(25304); +const constants = __nccwpck_require__(36861); +const instance = __nccwpck_require__(1709); +const metricSummary = __nccwpck_require__(3875); +const utils = __nccwpck_require__(57873); + /** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` + * A simple metrics aggregator that aggregates metrics in memory and flushes them periodically. + * Default flush interval is 5 seconds. + * + * @experimental This API is experimental and might change in the future. */ -function errorHandler(options) { - return function sentryErrorMiddleware(error, _req, res, next) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; - if (shouldHandleError(error)) { - core_1.withScope(function (_scope) { - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var transaction = res.__sentry_transaction; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } - var client = core_1.getCurrentHub().getClient(); - if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var isSessionAggregatesMode = client._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - var requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) { - requestSession.status = 'crashed'; - } - } - } - var eventId = core_1.captureException(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.sentry = eventId; - next(error); - }); - return; - } - next(error); - }; +class BrowserMetricsAggregator { + // TODO(@anonrig): Use FinalizationRegistry to have a proper way of flushing the buckets + // when the aggregator is garbage collected. + // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + + constructor( _client) {this._client = _client; + this._buckets = new Map(); + this._interval = setInterval(() => this.flush(), constants.DEFAULT_BROWSER_FLUSH_INTERVAL); + } + + /** + * @inheritDoc + */ + add( + metricType, + unsanitizedName, + value, + unsanitizedUnit = 'none', + unsanitizedTags = {}, + maybeFloatTimestamp = utils$1.timestampInSeconds(), + ) { + const timestamp = Math.floor(maybeFloatTimestamp); + const name = utils.sanitizeMetricKey(unsanitizedName); + const tags = utils.sanitizeTags(unsanitizedTags); + const unit = utils.sanitizeUnit(unsanitizedUnit ); + + const bucketKey = utils.getBucketKey(metricType, name, unit, tags); + + let bucketItem = this._buckets.get(bucketKey); + // If this is a set metric, we need to calculate the delta from the previous weight. + const previousWeight = bucketItem && metricType === constants.SET_METRIC_TYPE ? bucketItem.metric.weight : 0; + + if (bucketItem) { + bucketItem.metric.add(value); + // TODO(abhi): Do we need this check? + if (bucketItem.timestamp < timestamp) { + bucketItem.timestamp = timestamp; + } + } else { + bucketItem = { + // @ts-expect-error we don't need to narrow down the type of value here, saves bundle size. + metric: new instance.METRIC_MAP[metricType](value), + timestamp, + metricType, + name, + unit, + tags, + }; + this._buckets.set(bucketKey, bucketItem); + } + + // If value is a string, it's a set metric so calculate the delta from the previous weight. + const val = typeof value === 'string' ? bucketItem.metric.weight - previousWeight : value; + metricSummary.updateMetricSummaryOnActiveSpan(metricType, name, val, unit, unsanitizedTags, bucketKey); + } + + /** + * @inheritDoc + */ + flush() { + // short circuit if buckets are empty. + if (this._buckets.size === 0) { + return; + } + + if (this._client.captureAggregateMetrics) { + // TODO(@anonrig): Use Object.values() when we support ES6+ + const metricBuckets = Array.from(this._buckets).map(([, bucketItem]) => bucketItem); + this._client.captureAggregateMetrics(metricBuckets); + } + + this._buckets.clear(); + } + + /** + * @inheritDoc + */ + close() { + clearInterval(this._interval); + this.flush(); + } } -exports.errorHandler = errorHandler; -//# sourceMappingURL=handlers.js.map + +exports.BrowserMetricsAggregator = BrowserMetricsAggregator; +//# sourceMappingURL=browser-aggregator.js.map + /***/ }), -/***/ 22783: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 36861: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var types_1 = __nccwpck_require__(83789); -exports.Severity = types_1.Severity; -var core_1 = __nccwpck_require__(79212); -exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; -exports.addBreadcrumb = core_1.addBreadcrumb; -exports.captureException = core_1.captureException; -exports.captureEvent = core_1.captureEvent; -exports.captureMessage = core_1.captureMessage; -exports.configureScope = core_1.configureScope; -exports.getHubFromCarrier = core_1.getHubFromCarrier; -exports.getCurrentHub = core_1.getCurrentHub; -exports.Hub = core_1.Hub; -exports.makeMain = core_1.makeMain; -exports.Scope = core_1.Scope; -exports.Session = core_1.Session; -exports.startTransaction = core_1.startTransaction; -exports.SDK_VERSION = core_1.SDK_VERSION; -exports.setContext = core_1.setContext; -exports.setExtra = core_1.setExtra; -exports.setExtras = core_1.setExtras; -exports.setTag = core_1.setTag; -exports.setTags = core_1.setTags; -exports.setUser = core_1.setUser; -exports.withScope = core_1.withScope; -var backend_1 = __nccwpck_require__(40508); -exports.NodeBackend = backend_1.NodeBackend; -var client_1 = __nccwpck_require__(86147); -exports.NodeClient = client_1.NodeClient; -var sdk_1 = __nccwpck_require__(38836); -exports.defaultIntegrations = sdk_1.defaultIntegrations; -exports.init = sdk_1.init; -exports.lastEventId = sdk_1.lastEventId; -exports.flush = sdk_1.flush; -exports.close = sdk_1.close; -exports.getSentryRelease = sdk_1.getSentryRelease; -var utils_1 = __nccwpck_require__(27937); -exports.deepReadDirSync = utils_1.deepReadDirSync; -var version_1 = __nccwpck_require__(31271); -exports.SDK_NAME = version_1.SDK_NAME; -var core_2 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var domain = __nccwpck_require__(13639); -var Handlers = __nccwpck_require__(45400); -exports.Handlers = Handlers; -var NodeIntegrations = __nccwpck_require__(72310); -var Transports = __nccwpck_require__(21437); -exports.Transports = Transports; -var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); -exports.Integrations = INTEGRATIONS; -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -var carrier = hub_1.getMainCarrier(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; -} -//# sourceMappingURL=index.js.map + +const COUNTER_METRIC_TYPE = 'c' ; +const GAUGE_METRIC_TYPE = 'g' ; +const SET_METRIC_TYPE = 's' ; +const DISTRIBUTION_METRIC_TYPE = 'd' ; + +/** + * This does not match spec in https://develop.sentry.dev/sdk/metrics + * but was chosen to optimize for the most common case in browser environments. + */ +const DEFAULT_BROWSER_FLUSH_INTERVAL = 5000; + +/** + * SDKs are required to bucket into 10 second intervals (rollup in seconds) + * which is the current lower bound of metric accuracy. + */ +const DEFAULT_FLUSH_INTERVAL = 10000; + +/** + * The maximum number of metrics that should be stored in memory. + */ +const MAX_WEIGHT = 10000; + +exports.COUNTER_METRIC_TYPE = COUNTER_METRIC_TYPE; +exports.DEFAULT_BROWSER_FLUSH_INTERVAL = DEFAULT_BROWSER_FLUSH_INTERVAL; +exports.DEFAULT_FLUSH_INTERVAL = DEFAULT_FLUSH_INTERVAL; +exports.DISTRIBUTION_METRIC_TYPE = DISTRIBUTION_METRIC_TYPE; +exports.GAUGE_METRIC_TYPE = GAUGE_METRIC_TYPE; +exports.MAX_WEIGHT = MAX_WEIGHT; +exports.SET_METRIC_TYPE = SET_METRIC_TYPE; +//# sourceMappingURL=constants.js.map + /***/ }), -/***/ 29552: +/***/ 98438: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var util = __nccwpck_require__(73837); -/** Console module integration */ -var Console = /** @class */ (function () { - function Console() { - /** - * @inheritDoc - */ - this.name = Console.id; - } - /** - * @inheritDoc - */ - Console.prototype.setupOnce = function () { - var e_1, _a; - try { - for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) { - var level = _c.value; - utils_1.fill(console, level, createConsoleWrapper(level)); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - }; - /** - * @inheritDoc - */ - Console.id = 'Console'; - return Console; -}()); -exports.Console = Console; + +const utils = __nccwpck_require__(25304); +const utils$1 = __nccwpck_require__(57873); + /** - * Wrapper function that'll be used for every console level - */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - var sentryLevel = utils_1.severityFromString(level); - /* eslint-disable prefer-rest-params */ - return function () { - if (core_1.getCurrentHub().getIntegration(Console)) { - core_1.getCurrentHub().addBreadcrumb({ - category: 'console', - level: sentryLevel, - message: util.format.apply(undefined, arguments), - }, { - input: tslib_1.__spread(arguments), - level: level, - }); - } - originalConsoleMethod.apply(this, arguments); - }; - /* eslint-enable prefer-rest-params */ + * Create envelope from a metric aggregate. + */ +function createMetricEnvelope( + metricBucketItems, + dsn, + metadata, + tunnel, +) { + const headers = { + sent_at: new Date().toISOString(), + }; + + if (metadata && metadata.sdk) { + headers.sdk = { + name: metadata.sdk.name, + version: metadata.sdk.version, }; + } + + if (!!tunnel && dsn) { + headers.dsn = utils.dsnToString(dsn); + } + + const item = createMetricEnvelopeItem(metricBucketItems); + return utils.createEnvelope(headers, [item]); } -//# sourceMappingURL=console.js.map + +function createMetricEnvelopeItem(metricBucketItems) { + const payload = utils$1.serializeMetricBuckets(metricBucketItems); + const metricHeaders = { + type: 'statsd', + length: payload.length, + }; + return [metricHeaders, payload]; +} + +exports.createMetricEnvelope = createMetricEnvelope; +//# sourceMappingURL=envelope.js.map + /***/ }), -/***/ 27797: +/***/ 39543: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var fs_1 = __nccwpck_require__(57147); -var lru_map_1 = __nccwpck_require__(18424); -var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); -var DEFAULT_LINES_OF_CONTEXT = 7; -// TODO: Replace with promisify when minimum supported node >= v8 -function readTextFileAsync(path) { - return new Promise(function (resolve, reject) { - fs_1.readFile(path, 'utf8', function (err, data) { - if (err) - reject(err); - else - resolve(data); - }); - }); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const exports$1 = __nccwpck_require__(61117); +const spanUtils = __nccwpck_require__(19925); +const constants = __nccwpck_require__(36861); +const integration = __nccwpck_require__(83286); + +function addToMetricsAggregator( + metricType, + name, + value, + data = {}, +) { + const client = exports$1.getClient(); + const scope = exports$1.getCurrentScope(); + if (client) { + if (!client.metricsAggregator) { + debugBuild.DEBUG_BUILD && + utils.logger.warn('No metrics aggregator enabled. Please add the MetricsAggregator integration to use metrics APIs'); + return; + } + const { unit, tags, timestamp } = data; + const { release, environment } = client.getOptions(); + // eslint-disable-next-line deprecation/deprecation + const transaction = scope.getTransaction(); + const metricTags = {}; + if (release) { + metricTags.release = release; + } + if (environment) { + metricTags.environment = environment; + } + if (transaction) { + metricTags.transaction = spanUtils.spanToJSON(transaction).description || ''; + } + + debugBuild.DEBUG_BUILD && utils.logger.log(`Adding value of ${value} to ${metricType} metric ${name}`); + client.metricsAggregator.add(metricType, name, value, unit, { ...metricTags, ...tags }, timestamp); + } } + /** - * Resets the file cache. Exists for testing purposes. - * @hidden + * Adds a value to a counter metric + * + * @experimental This API is experimental and might have breaking changes in the future. */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); +function increment(name, value = 1, data) { + addToMetricsAggregator(constants.COUNTER_METRIC_TYPE, name, value, data); } -exports.resetFileContentCache = resetFileContentCache; -/** Add node modules / packages to the event */ -var ContextLines = /** @class */ (function () { - function ContextLines(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = ContextLines.id; - } - Object.defineProperty(ContextLines.prototype, "_contextLines", { - /** Get's the number of context lines to add */ - get: function () { - var _a, _b; - // This is only here to copy frameContextLines from init options if it hasn't - // been set via this integrations constructor. - // - // TODO: Remove on next major! - if (this._options.frameContextLines === undefined) { - var initOptions = (_a = core_1.getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); - // eslint-disable-next-line deprecation/deprecation - this._options.frameContextLines = (_b = initOptions) === null || _b === void 0 ? void 0 : _b.frameContextLines; - } - return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - }, - enumerable: true, - configurable: true - }); - /** - * @inheritDoc - */ - ContextLines.prototype.setupOnce = function (addGlobalEventProcessor) { - var _this = this; - addGlobalEventProcessor(function (event) { return _this.addSourceContext(event); }); - }; - /** Processes an event and adds context lines */ - ContextLines.prototype.addSourceContext = function (event) { - var _a, _b; - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _c, _d, exception, e_1_1; - var e_1, _e; - return tslib_1.__generator(this, function (_f) { - switch (_f.label) { - case 0: - if (!(this._contextLines > 0 && ((_a = event.exception) === null || _a === void 0 ? void 0 : _a.values))) return [3 /*break*/, 8]; - _f.label = 1; - case 1: - _f.trys.push([1, 6, 7, 8]); - _c = tslib_1.__values(event.exception.values), _d = _c.next(); - _f.label = 2; - case 2: - if (!!_d.done) return [3 /*break*/, 5]; - exception = _d.value; - if (!((_b = exception.stacktrace) === null || _b === void 0 ? void 0 : _b.frames)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.addSourceContextToFrames(exception.stacktrace.frames)]; - case 3: - _f.sent(); - _f.label = 4; - case 4: - _d = _c.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_1_1 = _f.sent(); - e_1 = { error: e_1_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (_d && !_d.done && (_e = _c.return)) _e.call(_c); - } - finally { if (e_1) throw e_1.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/, event]; - } - }); - }); - }; - /** Adds context lines to frames */ - ContextLines.prototype.addSourceContextToFrames = function (frames) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var contextLines, frames_1, frames_1_1, frame, sourceFile, lines, e_2_1; - var e_2, _a; - return tslib_1.__generator(this, function (_b) { - switch (_b.label) { - case 0: - contextLines = this._contextLines; - _b.label = 1; - case 1: - _b.trys.push([1, 6, 7, 8]); - frames_1 = tslib_1.__values(frames), frames_1_1 = frames_1.next(); - _b.label = 2; - case 2: - if (!!frames_1_1.done) return [3 /*break*/, 5]; - frame = frames_1_1.value; - if (!(frame.filename && frame.context_line === undefined)) return [3 /*break*/, 4]; - return [4 /*yield*/, _readSourceFile(frame.filename)]; - case 3: - sourceFile = _b.sent(); - if (sourceFile) { - try { - lines = sourceFile.split('\n'); - utils_1.addContextToFrame(lines, frame, contextLines); - } - catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - _b.label = 4; - case 4: - frames_1_1 = frames_1.next(); - return [3 /*break*/, 2]; - case 5: return [3 /*break*/, 8]; - case 6: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3 /*break*/, 8]; - case 7: - try { - if (frames_1_1 && !frames_1_1.done && (_a = frames_1.return)) _a.call(frames_1); - } - finally { if (e_2) throw e_2.error; } - return [7 /*endfinally*/]; - case 8: return [2 /*return*/]; - } - }); - }); - }; - /** - * @inheritDoc - */ - ContextLines.id = 'ContextLines'; - return ContextLines; -}()); -exports.ContextLines = ContextLines; + /** - * Reads file contents and caches them in a global LRU cache. + * Adds a value to a distribution metric * - * @param filename filepath to read content from. + * @experimental This API is experimental and might have breaking changes in the future. */ -function _readSourceFile(filename) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var cachedFile, content, _1; - return tslib_1.__generator(this, function (_a) { - switch (_a.label) { - case 0: - cachedFile = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cachedFile !== undefined) { - return [2 /*return*/, cachedFile]; - } - content = null; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, readTextFileAsync(filename)]; - case 2: - content = _a.sent(); - return [3 /*break*/, 4]; - case 3: - _1 = _a.sent(); - return [3 /*break*/, 4]; - case 4: - FILE_CONTENT_CACHE.set(filename, content); - return [2 /*return*/, content]; - } - }); - }); +function distribution(name, value, data) { + addToMetricsAggregator(constants.DISTRIBUTION_METRIC_TYPE, name, value, data); } -//# sourceMappingURL=contextlines.js.map - -/***/ }), - -/***/ 76280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var http_1 = __nccwpck_require__(84103); -var NODE_VERSION = utils_1.parseSemver(process.versions.node); -/** http module integration */ -var Http = /** @class */ (function () { - /** - * @inheritDoc - */ - function Http(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Http.id; - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; - } - /** - * @inheritDoc - */ - Http.prototype.setupOnce = function () { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); - // eslint-disable-next-line @typescript-eslint/no-var-requires - var httpModule = __nccwpck_require__(13685); - utils_1.fill(httpModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpModule, 'request', wrappedHandlerMaker); - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - var httpsModule = __nccwpck_require__(95687); - utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); - } - }; - /** - * @inheritDoc - */ - Http.id = 'Http'; - return Http; -}()); -exports.Http = Http; /** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * Adds a value to a set metric. Value must be a string or integer. * - * @returns A function which accepts the exiting handler and returns a wrapped handler + * @experimental This API is experimental and might have breaking changes in the future. */ -function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var httpModule = this; - var requestArgs = http_1.normalizeRequestArgs(this, args); - var requestOptions = requestArgs[0]; - var requestUrl = http_1.extractUrl(requestOptions); - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if (http_1.isSentryRequest(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } - var span; - var parentSpan; - var scope = core_1.getCurrentHub().getScope(); - if (scope && tracingEnabled) { - parentSpan = scope.getSpan(); - if (parentSpan) { - span = parentSpan.startChild({ - description: (requestOptions.method || 'GET') + " " + requestUrl, - op: 'http.client', - }); - var sentryTraceHeader = span.toTraceparent(); - utils_1.isDebugBuild() && - utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": "); - requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); - } - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function (res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (tracingEnabled && span) { - if (res.statusCode) { - span.setHttpStatus(res.statusCode); - } - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (tracingEnabled && span) { - span.setHttpStatus(500); - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }); - }; - }; +function set(name, value, data) { + addToMetricsAggregator(constants.SET_METRIC_TYPE, name, value, data); } + /** - * Captures Breadcrumb based on provided request/response pair + * Adds a value to a gauge metric + * + * @experimental This API is experimental and might have breaking changes in the future. */ -function addRequestBreadcrumb(event, url, req, res) { - if (!core_1.getCurrentHub().getIntegration(Http)) { - return; - } - core_1.getCurrentHub().addBreadcrumb({ - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url: url, - }, - type: 'http', - }, { - event: event, - request: req, - response: res, - }); +function gauge(name, value, data) { + addToMetricsAggregator(constants.GAUGE_METRIC_TYPE, name, value, data); } -//# sourceMappingURL=http.js.map -/***/ }), +const metrics = { + increment, + distribution, + set, + gauge, + /** @deprecated Use `metrics.metricsAggregratorIntegration()` instead. */ + // eslint-disable-next-line deprecation/deprecation + MetricsAggregator: integration.MetricsAggregator, + metricsAggregatorIntegration: integration.metricsAggregatorIntegration, +}; -/***/ 72310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports.distribution = distribution; +exports.gauge = gauge; +exports.increment = increment; +exports.metrics = metrics; +exports.set = set; +//# sourceMappingURL=exports.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var console_1 = __nccwpck_require__(29552); -exports.Console = console_1.Console; -var http_1 = __nccwpck_require__(76280); -exports.Http = http_1.Http; -var onuncaughtexception_1 = __nccwpck_require__(50443); -exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; -var onunhandledrejection_1 = __nccwpck_require__(87344); -exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; -var linkederrors_1 = __nccwpck_require__(70208); -exports.LinkedErrors = linkederrors_1.LinkedErrors; -var modules_1 = __nccwpck_require__(90046); -exports.Modules = modules_1.Modules; -var contextlines_1 = __nccwpck_require__(27797); -exports.ContextLines = contextlines_1.ContextLines; -//# sourceMappingURL=index.js.map /***/ }), -/***/ 70208: +/***/ 1709: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var eventbuilder_1 = __nccwpck_require__(79287); -var contextlines_1 = __nccwpck_require__(27797); -var DEFAULT_KEY = 'cause'; -var DEFAULT_LIMIT = 5; -/** Adds SDK info to an event. */ -var LinkedErrors = /** @class */ (function () { - /** - * @inheritDoc - */ - function LinkedErrors(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = LinkedErrors.id; - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; - } - /** - * @inheritDoc - */ - LinkedErrors.prototype.setupOnce = function () { - core_1.addGlobalEventProcessor(function (event, hint) { - var self = core_1.getCurrentHub().getIntegration(LinkedErrors); - if (self) { - var handler = self._handler && self._handler.bind(self); - return typeof handler === 'function' ? handler(event, hint) : event; - } - return event; - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._handler = function (event, hint) { - var _this = this; - if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) { - return utils_1.resolvedSyncPromise(event); - } - return new utils_1.SyncPromise(function (resolve) { - void _this._walkErrorTree(hint.originalException, _this._key) - .then(function (linkedErrors) { - if (event && event.exception && event.exception.values) { - event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values); - } - resolve(event); - }) - .then(null, function () { - resolve(event); - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { - if (stack === void 0) { stack = []; } - var _a; - return tslib_1.__awaiter(this, void 0, void 0, function () { - var exception, contextLines; - var _this = this; - return tslib_1.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { - return [2 /*return*/, Promise.resolve(stack)]; - } - exception = eventbuilder_1.exceptionFromError(error[key]); - contextLines = core_1.getCurrentHub().getIntegration(contextlines_1.ContextLines); - if (!(contextLines && ((_a = exception.stacktrace) === null || _a === void 0 ? void 0 : _a.frames))) return [3 /*break*/, 2]; - return [4 /*yield*/, contextLines.addSourceContextToFrames(exception.stacktrace.frames)]; - case 1: - _b.sent(); - _b.label = 2; - case 2: return [2 /*return*/, new Promise(function (resolve, reject) { - void _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack)) - .then(resolve) - .then(null, function () { - reject(); - }); - })]; - } - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.id = 'LinkedErrors'; - return LinkedErrors; -}()); -exports.LinkedErrors = LinkedErrors; -//# sourceMappingURL=linkederrors.js.map -/***/ }), +const constants = __nccwpck_require__(36861); +const utils = __nccwpck_require__(57873); -/***/ 90046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * A metric instance representing a counter. + */ +class CounterMetric { + constructor( _value) {this._value = _value;} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var fs_1 = __nccwpck_require__(57147); -var path_1 = __nccwpck_require__(71017); -var moduleCache; -/** Extract information about paths */ -function getPaths() { - try { - return require.cache ? Object.keys(require.cache) : []; + /** @inheritDoc */ + get weight() { + return 1; + } + + /** @inheritdoc */ + add(value) { + this._value += value; + } + + /** @inheritdoc */ + toString() { + return `${this._value}`; + } +} + +/** + * A metric instance representing a gauge. + */ +class GaugeMetric { + + constructor(value) { + this._last = value; + this._min = value; + this._max = value; + this._sum = value; + this._count = 1; + } + + /** @inheritDoc */ + get weight() { + return 5; + } + + /** @inheritdoc */ + add(value) { + this._last = value; + if (value < this._min) { + this._min = value; } - catch (e) { - return []; + if (value > this._max) { + this._max = value; } + this._sum += value; + this._count++; + } + + /** @inheritdoc */ + toString() { + return `${this._last}:${this._min}:${this._max}:${this._sum}:${this._count}`; + } } -/** Extract information about package.json modules */ -function collectModules() { - var mainPaths = (require.main && require.main.paths) || []; - var paths = getPaths(); - var infos = {}; - var seen = {}; - paths.forEach(function (path) { - var dir = path; - /** Traverse directories upward in the search of package.json file */ - var updir = function () { - var orig = dir; - dir = path_1.dirname(orig); - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } - var pkgfile = path_1.join(orig, 'package.json'); - seen[orig] = true; - if (!fs_1.existsSync(pkgfile)) { - return updir(); - } - try { - var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8')); - infos[info.name] = info.version; - } - catch (_oO) { - // no-empty - } - }; - updir(); - }); - return infos; + +/** + * A metric instance representing a distribution. + */ +class DistributionMetric { + + constructor(first) { + this._value = [first]; + } + + /** @inheritDoc */ + get weight() { + return this._value.length; + } + + /** @inheritdoc */ + add(value) { + this._value.push(value); + } + + /** @inheritdoc */ + toString() { + return this._value.join(':'); + } } -/** Add node modules / packages to the event */ -var Modules = /** @class */ (function () { - function Modules() { - /** - * @inheritDoc - */ - this.name = Modules.id; - } - /** - * @inheritDoc - */ - Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { - var _this = this; - addGlobalEventProcessor(function (event) { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() }); - }); - }; - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - Modules.prototype._getModules = function () { - if (!moduleCache) { - moduleCache = collectModules(); - } - return moduleCache; - }; - /** - * @inheritDoc - */ - Modules.id = 'Modules'; - return Modules; -}()); -exports.Modules = Modules; -//# sourceMappingURL=modules.js.map -/***/ }), +/** + * A metric instance representing a set. + */ +class SetMetric { -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + constructor( first) {this.first = first; + this._value = new Set([first]); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var errorhandling_1 = __nccwpck_require__(5635); -/** Global Promise Rejection handler */ -var OnUncaughtException = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUncaughtException(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUncaughtException.id; - /** - * @inheritDoc - */ - this.handler = this._makeErrorHandler(); - } - /** - * @inheritDoc - */ - OnUncaughtException.prototype.setupOnce = function () { - global.process.on('uncaughtException', this.handler.bind(this)); - }; - /** - * @hidden - */ - OnUncaughtException.prototype._makeErrorHandler = function () { - var _this = this; - var timeout = 2000; - var caughtFirstError = false; - var caughtSecondError = false; - var calledFatalError = false; - var firstError; - return function (error) { - var onFatalError = errorhandling_1.logAndExitProcess; - var client = core_1.getCurrentHub().getClient(); - if (_this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = _this._options.onFatalError; - } - else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError; - } - if (!caughtFirstError) { - var hub_1 = core_1.getCurrentHub(); - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; - if (hub_1.getIntegration(OnUncaughtException)) { - hub_1.withScope(function (scope) { - scope.setLevel(types_1.Severity.Fatal); - hub_1.captureException(error, { - originalException: error, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - }); - } - else { - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - } - } - else if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - utils_1.isDebugBuild() && - utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); - errorhandling_1.logAndExitProcess(error); - } - else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(function () { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } - else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - }; - }; - /** - * @inheritDoc - */ - OnUncaughtException.id = 'OnUncaughtException'; - return OnUncaughtException; -}()); -exports.OnUncaughtException = OnUncaughtException; -//# sourceMappingURL=onuncaughtexception.js.map + /** @inheritDoc */ + get weight() { + return this._value.size; + } -/***/ }), + /** @inheritdoc */ + add(value) { + this._value.add(value); + } -/***/ 87344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** @inheritdoc */ + toString() { + return Array.from(this._value) + .map(val => (typeof val === 'string' ? utils.simpleHash(val) : val)) + .join(':'); + } +} + +const METRIC_MAP = { + [constants.COUNTER_METRIC_TYPE]: CounterMetric, + [constants.GAUGE_METRIC_TYPE]: GaugeMetric, + [constants.DISTRIBUTION_METRIC_TYPE]: DistributionMetric, + [constants.SET_METRIC_TYPE]: SetMetric, +}; + +exports.CounterMetric = CounterMetric; +exports.DistributionMetric = DistributionMetric; +exports.GaugeMetric = GaugeMetric; +exports.METRIC_MAP = METRIC_MAP; +exports.SetMetric = SetMetric; +//# sourceMappingURL=instance.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var errorhandling_1 = __nccwpck_require__(5635); -/** Global Promise Rejection handler */ -var OnUnhandledRejection = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUnhandledRejection(_options) { - if (_options === void 0) { _options = { mode: 'warn' }; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUnhandledRejection.id; - } - /** - * @inheritDoc - */ - OnUnhandledRejection.prototype.setupOnce = function () { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - }; - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { - var hub = core_1.getCurrentHub(); - if (!hub.getIntegration(OnUnhandledRejection)) { - this._handleRejection(reason); - return; - } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var context = (promise.domain && promise.domain.sentryContext) || {}; - hub.withScope(function (scope) { - scope.setExtra('unhandledPromiseRejection', true); - // Preserve backwards compatibility with raven-node for now - if (context.user) { - scope.setUser(context.user); - } - if (context.tags) { - scope.setTags(context.tags); - } - if (context.extra) { - scope.setExtras(context.extra); - } - hub.captureException(reason, { - originalException: promise, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); - }); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - this._handleRejection(reason); - }; - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype._handleRejection = function (reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - var rejectionWarning = 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } - else if (this._options.mode === 'strict') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - }); - errorhandling_1.logAndExitProcess(reason); - } - /* eslint-enable no-console */ - }; - /** - * @inheritDoc - */ - OnUnhandledRejection.id = 'OnUnhandledRejection'; - return OnUnhandledRejection; -}()); -exports.OnUnhandledRejection = OnUnhandledRejection; -//# sourceMappingURL=onunhandledrejection.js.map /***/ }), -/***/ 5635: +/***/ 83286: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var DEFAULT_SHUTDOWN_TIMEOUT = 2000; + +const integration = __nccwpck_require__(51212); +const browserAggregator = __nccwpck_require__(24044); + +const INTEGRATION_NAME = 'MetricsAggregator'; + +const _metricsAggregatorIntegration = (() => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + client.metricsAggregator = new browserAggregator.BrowserMetricsAggregator(client); + }, + }; +}) ; + +const metricsAggregatorIntegration = integration.defineIntegration(_metricsAggregatorIntegration); + /** - * @hidden + * Enables Sentry metrics monitoring. + * + * @experimental This API is experimental and might having breaking changes in the future. + * @deprecated Use `metricsAggegratorIntegration()` instead. */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); - var client = core_1.getCurrentHub().getClient(); - if (client === undefined) { - utils_1.isDebugBuild() && utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); - } - var options = client.getOptions(); - var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - utils_1.forget(client.close(timeout).then(function (result) { - if (!result) { - utils_1.isDebugBuild() && utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - })); -} -exports.logAndExitProcess = logAndExitProcess; -//# sourceMappingURL=errorhandling.js.map +// eslint-disable-next-line deprecation/deprecation +const MetricsAggregator = integration.convertIntegrationFnToClass( + INTEGRATION_NAME, + metricsAggregatorIntegration, +) ; + +exports.MetricsAggregator = MetricsAggregator; +exports.metricsAggregatorIntegration = metricsAggregatorIntegration; +//# sourceMappingURL=integration.js.map + /***/ }), -/***/ 84103: +/***/ 3875: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var url_1 = __nccwpck_require__(57310); -var NODE_VERSION = utils_1.parseSemver(process.versions.node); + +const utils = __nccwpck_require__(25304); +__nccwpck_require__(44220); +__nccwpck_require__(64332); +__nccwpck_require__(13973); +const trace = __nccwpck_require__(16474); + /** - * Checks whether given url points to Sentry server - * @param url url to verify + * key: bucketKey + * value: [exportKey, MetricSummary] */ -function isSentryRequest(url) { - var _a; - var dsn = (_a = core_1.getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getDsn(); - return dsn ? url.includes(dsn.host) : false; + +let SPAN_METRIC_SUMMARY; + +function getMetricStorageForSpan(span) { + return SPAN_METRIC_SUMMARY ? SPAN_METRIC_SUMMARY.get(span) : undefined; } -exports.isSentryRequest = isSentryRequest; + /** - * Assemble a URL to be used for breadcrumbs and spans. - * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL + * Fetches the metric summary if it exists for the passed span */ -function extractUrl(requestOptions) { - var protocol = requestOptions.protocol || ''; - var hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port; - var path = requestOptions.path ? requestOptions.path : '/'; - return protocol + "//" + hostname + port + path; +function getMetricSummaryJsonForSpan(span) { + const storage = getMetricStorageForSpan(span); + + if (!storage) { + return undefined; + } + const output = {}; + + for (const [, [exportKey, summary]] of storage) { + if (!output[exportKey]) { + output[exportKey] = []; + } + + output[exportKey].push(utils.dropUndefinedKeys(summary)); + } + + return output; } -exports.extractUrl = extractUrl; + /** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object - * - * @returns The cleaned description - */ -function cleanSpanDescription(description, requestOptions, request) { - var _a, _b, _c; - // nothing to clean - if (!description) { - return description; - } - // eslint-disable-next-line prefer-const - var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1]; - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } - // internal routes can end up starting with a triple slash rather than a single one - if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) { - requestUrl = requestUrl.slice(2); - } - return method + " " + requestUrl; -} -exports.cleanSpanDescription = cleanSpanDescription; -/** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. - * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. - */ -function urlToOptions(url) { - var options = { - protocol: url.protocol, - hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: "" + (url.pathname || '') + (url.search || ''), - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = url.username + ":" + url.password; - } - return options; -} -exports.urlToOptions = urlToOptions; -/** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. - * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + * Updates the metric summary on the currently active span */ -function normalizeRequestArgs(httpModule, requestArgs) { - var _a, _b, _c, _d, _e, _f, _g, _h; - var callback, requestOptions; - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop(); - } - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); - } - else if (requestArgs[0] instanceof url_1.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } - else { - requestOptions = requestArgs[0]; - } - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]); - } - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - ((_b = (_a = httpModule) === null || _a === void 0 ? void 0 : _a.globalAgent) === null || _b === void 0 ? void 0 : _b.protocol) || ((_c = requestOptions.agent) === null || _c === void 0 ? void 0 : _c.protocol) || ((_d = requestOptions._defaultAgent) === null || _d === void 0 ? void 0 : _d.protocol); - } - else { - requestOptions.protocol = - ((_e = requestOptions.agent) === null || _e === void 0 ? void 0 : _e.protocol) || ((_f = requestOptions._defaultAgent) === null || _f === void 0 ? void 0 : _f.protocol) || ((_h = (_g = httpModule) === null || _g === void 0 ? void 0 : _g.globalAgent) === null || _h === void 0 ? void 0 : _h.protocol); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; +function updateMetricSummaryOnActiveSpan( + metricType, + sanitizedName, + value, + unit, + tags, + bucketKey, +) { + const span = trace.getActiveSpan(); + if (span) { + const storage = getMetricStorageForSpan(span) || new Map(); + + const exportKey = `${metricType}:${sanitizedName}@${unit}`; + const bucketItem = storage.get(bucketKey); + + if (bucketItem) { + const [, summary] = bucketItem; + storage.set(bucketKey, [ + exportKey, + { + min: Math.min(summary.min, value), + max: Math.max(summary.max, value), + count: (summary.count += 1), + sum: (summary.sum += value), + tags: summary.tags, + }, + ]); + } else { + storage.set(bucketKey, [ + exportKey, + { + min: value, + max: value, + count: 1, + sum: value, + tags, + }, + ]); } - else { - return [requestOptions]; + + if (!SPAN_METRIC_SUMMARY) { + SPAN_METRIC_SUMMARY = new WeakMap(); } + + SPAN_METRIC_SUMMARY.set(span, storage); + } } -exports.normalizeRequestArgs = normalizeRequestArgs; -//# sourceMappingURL=http.js.map + +exports.getMetricSummaryJsonForSpan = getMetricSummaryJsonForSpan; +exports.updateMetricSummaryOnActiveSpan = updateMetricSummaryOnActiveSpan; +//# sourceMappingURL=metric-summary.js.map + /***/ }), -/***/ 38836: +/***/ 57873: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var domain = __nccwpck_require__(13639); -var client_1 = __nccwpck_require__(86147); -var integrations_1 = __nccwpck_require__(72310); -exports.defaultIntegrations = [ - // Common - new core_1.Integrations.InboundFilters(), - new core_1.Integrations.FunctionToString(), - new integrations_1.ContextLines(), - // Native Wrappers - new integrations_1.Console(), - new integrations_1.Http(), - // Global Handlers - new integrations_1.OnUncaughtException(), - new integrations_1.OnUnhandledRejection(), - // Misc - new integrations_1.LinkedErrors(), -]; -/** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link NodeOptions} for documentation on configuration options. - */ -function init(options) { - if (options === void 0) { options = {}; } - var _a; - var carrier = hub_1.getMainCarrier(); - var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || []; - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations); - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; - } - } - if (options.release === undefined) { - var detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } - else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; - } - } - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain.active) { - hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub()); - } - core_1.initAndBind(client_1.NodeClient, options); - if (options.autoSessionTracking) { - startSessionTracking(); - } -} -exports.init = init; + +const utils = __nccwpck_require__(25304); + /** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. + * Generate bucket key from metric properties. */ -function lastEventId() { - return core_1.getCurrentHub().lastEventId(); +function getBucketKey( + metricType, + name, + unit, + tags, +) { + const stringifiedTags = Object.entries(utils.dropUndefinedKeys(tags)).sort((a, b) => a[0].localeCompare(b[0])); + return `${metricType}${name}${unit}${stringifiedTags}`; } -exports.lastEventId = lastEventId; + +/* eslint-disable no-bitwise */ /** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). + * Simple hash function for strings. */ -function flush(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.flush(timeout)]; - } - utils_1.isDebugBuild() && utils_1.logger.warn('Cannot flush events. No client defined.'); - return [2 /*return*/, Promise.resolve(false)]; - }); - }); +function simpleHash(s) { + let rv = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + rv = (rv << 5) - rv + c; + rv &= rv; + } + return rv >>> 0; } -exports.flush = flush; +/* eslint-enable no-bitwise */ + /** - * Call `close()` on the current client, if there is one. See {@link Client.close}. + * Serialize metrics buckets into a string based on statsd format. * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -function close(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.close(timeout)]; - } - utils_1.isDebugBuild() && utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return [2 /*return*/, Promise.resolve(false)]; - }); - }); -} -exports.close = close; -/** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client - */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - var clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; - } - return false; -} -exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled; -/** - * Returns a release dynamically from environment variables. - */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - // This supports the variable that sentry-webpack-plugin injects - var global = utils_1.getGlobalObject(); - if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) { - return global.SENTRY_RELEASE.id; - } - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback); -} -exports.getSentryRelease = getSentryRelease; -/** - * Enable automatic Session Tracking for the node process. + * Example of format: + * metric.name@second:1:1.2|d|#a:value,b:anothervalue|T12345677 + * Segments: + * name: metric.name + * unit: second + * value: [1, 1.2] + * type of metric: d (distribution) + * tags: { a: value, b: anothervalue } + * timestamp: 12345677 */ -function startSessionTracking() { - var hub = core_1.getCurrentHub(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', function () { - var _a; - var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession(); - var terminalStates = ['exited', 'crashed']; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) - hub.endSession(); - }); +function serializeMetricBuckets(metricBucketItems) { + let out = ''; + for (const item of metricBucketItems) { + const tagEntries = Object.entries(item.tags); + const maybeTags = tagEntries.length > 0 ? `|#${tagEntries.map(([key, value]) => `${key}:${value}`).join(',')}` : ''; + out += `${item.name}@${item.unit}:${item.metric}|${item.metricType}${maybeTags}|T${item.timestamp}\n`; + } + return out; } -//# sourceMappingURL=sdk.js.map -/***/ }), - -/***/ 94854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** Sanitizes units */ +function sanitizeUnit(unit) { + return unit.replace(/[^\w]+/gi, '_'); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Gets the module */ -function getModule(filename) { - if (!filename) { - return; - } - // We could use optional chaining here but webpack does like that mixed with require - var base = ((require && require.main && require.main.filename && utils_1.dirname(require.main.filename)) || global.process.cwd()) + "/"; - // It's specifically a module - var file = utils_1.basename(filename, '.js'); - var path = utils_1.dirname(filename); - var n = path.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return path.substr(n + 14).replace(/\//g, '.') + ":" + file; - } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = (path + "/").lastIndexOf(base, 0); - if (n === 0) { - var moduleName = path.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; - } - moduleName += file; - return moduleName; - } - return file; +/** Sanitizes metric keys */ +function sanitizeMetricKey(key) { + return key.replace(/[^\w\-.]+/gi, '_'); } -var FILENAME_MATCH = /^\s*[-]{4,}$/; -var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/; -// eslint-disable-next-line complexity -var node = function (line) { - var _a; - if (line.match(FILENAME_MATCH)) { - return { - filename: line, - }; - } - var lineMatch = line.match(FULL_MATCH); - if (!lineMatch) { - return undefined; - } - var object; - var method; - var functionName; - var typeName; - var methodName; - if (lineMatch[1]) { - functionName = lineMatch[1]; - var methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - // eslint-disable-next-line no-plusplus - methodStart--; - } - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - var objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = undefined; - } - if (method) { - typeName = object; - methodName = method; - } - if (method === '') { - methodName = undefined; - functionName = undefined; - } - if (functionName === undefined) { - methodName = methodName || ''; - functionName = typeName ? typeName + "." + methodName : methodName; - } - var filename = ((_a = lineMatch[2]) === null || _a === void 0 ? void 0 : _a.startsWith('file://')) ? lineMatch[2].substr(7) : lineMatch[2]; - var isNative = lineMatch[5] === 'native'; - var isInternal = isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - var in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); - return { - filename: filename, - module: getModule(filename), - function: functionName, - lineno: parseInt(lineMatch[3], 10) || undefined, - colno: parseInt(lineMatch[4], 10) || undefined, - in_app: in_app, - }; -}; -exports.nodeStackParser = [90, node]; -//# sourceMappingURL=stack-parser.js.map -/***/ }), +function sanitizeTagKey(key) { + return key.replace(/[^\w\-./]+/gi, ''); +} -/***/ 41194: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const tagValueReplacements = [ + ['\n', '\\n'], + ['\r', '\\r'], + ['\t', '\\t'], + ['\\', '\\\\'], + ['|', '\\u{7c}'], + [',', '\\u{2c}'], +]; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var fs = __nccwpck_require__(57147); -var url_1 = __nccwpck_require__(57310); -var version_1 = __nccwpck_require__(31271); -var CATEGORY_MAPPING = { - event: 'error', - transaction: 'transaction', - session: 'session', - attachment: 'attachment', -}; -/** Base Transport class implementation */ -var BaseTransport = /** @class */ (function () { - /** Create instance and set this.dsn */ - function BaseTransport(options) { - this.options = options; - /** A simple buffer holding all requests. */ - this._buffer = utils_1.makePromiseBuffer(30); - /** Locks transport after receiving rate limits in a response */ - this._rateLimits = {}; - /** Default function used to parse URLs */ - this.urlParser = function (url) { return new url_1.URL(url); }; - // eslint-disable-next-line deprecation/deprecation - this._api = core_1.initAPIDetails(options.dsn, options._metadata, options.tunnel); +function getCharOrReplacement(input) { + for (const [search, replacement] of tagValueReplacements) { + if (input === search) { + return replacement; } - /** - * @inheritDoc - */ - BaseTransport.prototype.sendEvent = function (_) { - throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.'); - }; - /** - * @inheritDoc - */ - BaseTransport.prototype.close = function (timeout) { - return this._buffer.drain(timeout); - }; - /** - * Extracts proxy settings from client options and env variables. - * - * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * An order of priority for available protocols is: - * `http` => `options.httpProxy` | `process.env.http_proxy` - * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy` - */ - BaseTransport.prototype._getProxy = function (protocol) { - var e_1, _a; - var _b = process.env, no_proxy = _b.no_proxy, http_proxy = _b.http_proxy, https_proxy = _b.https_proxy; - var _c = this.options, httpProxy = _c.httpProxy, httpsProxy = _c.httpsProxy; - var proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy; - if (!no_proxy) { - return proxy; - } - var _d = this._api.dsn, host = _d.host, port = _d.port; - try { - for (var _e = tslib_1.__values(no_proxy.split(',')), _f = _e.next(); !_f.done; _f = _e.next()) { - var np = _f.value; - if (host.endsWith(np) || (host + ":" + port).endsWith(np)) { - return; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_f && !_f.done && (_a = _e.return)) _a.call(_e); - } - finally { if (e_1) throw e_1.error; } - } - return proxy; - }; - /** Returns a build request option object used by request */ - BaseTransport.prototype._getRequestOptions = function (urlParts) { - var headers = tslib_1.__assign(tslib_1.__assign({}, core_1.getRequestHeaders(this._api.dsn, version_1.SDK_NAME, core_1.SDK_VERSION)), this.options.headers); - var hostname = urlParts.hostname, pathname = urlParts.pathname, port = urlParts.port, protocol = urlParts.protocol; - // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290 - // We ignore the query string on purpose - var path = "" + pathname; - return tslib_1.__assign({ agent: this.client, headers: headers, - hostname: hostname, method: 'POST', path: path, - port: port, - protocol: protocol }, (this.options.caCerts && { - ca: fs.readFileSync(this.options.caCerts), - })); - }; - /** - * Gets the time that given category is disabled until for rate limiting - */ - BaseTransport.prototype._disabledUntil = function (requestType) { - var category = CATEGORY_MAPPING[requestType]; - return this._rateLimits[category] || this._rateLimits.all; - }; - /** - * Checks if a category is rate limited - */ - BaseTransport.prototype._isRateLimited = function (requestType) { - return this._disabledUntil(requestType) > new Date(Date.now()); - }; - /** - * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header. - */ - BaseTransport.prototype._handleRateLimit = function (headers) { - var e_2, _a, e_3, _b; - var now = Date.now(); - var rlHeader = headers['x-sentry-rate-limits']; - var raHeader = headers['retry-after']; - if (rlHeader) { - try { - // rate limit headers are of the form - //
,
,.. - // where each
is of the form - // : : : - // where - // is a delay in ms - // is the event type(s) (error, transaction, etc) being rate limited and is of the form - // ;;... - // is what's being limited (org, project, or key) - ignored by SDK - // is an arbitrary string like "org_quota" - ignored by SDK - for (var _c = tslib_1.__values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { - var limit = _d.value; - var parameters = limit.split(':', 2); - var headerDelay = parseInt(parameters[0], 10); - var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - try { - for (var _e = (e_3 = void 0, tslib_1.__values((parameters[1] && parameters[1].split(';')) || ['all'])), _f = _e.next(); !_f.done; _f = _e.next()) { - var category = _f.value; - // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this - // sdk and any categories that are not supported will not be added redundantly to the rateLimits object - var categoriesAllowed = tslib_1.__spread(Object.keys(CATEGORY_MAPPING).map(function (k) { return CATEGORY_MAPPING[k]; }), [ - 'all', - ]); - if (categoriesAllowed.includes(category)) - this._rateLimits[category] = new Date(now + delay); - } - } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (_f && !_f.done && (_b = _e.return)) _b.call(_e); - } - finally { if (e_3) throw e_3.error; } - } - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) _a.call(_c); - } - finally { if (e_2) throw e_2.error; } - } - return true; - } - else if (raHeader) { - this._rateLimits.all = new Date(now + utils_1.parseRetryAfterHeader(raHeader, now)); - return true; - } - return false; - }; - /** JSDoc */ - BaseTransport.prototype._send = function (sentryRequest, originalPayload) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - if (!this.module) { - throw new utils_1.SentryError('No module available'); - } - if (originalPayload && this._isRateLimited(sentryRequest.type)) { - return [2 /*return*/, Promise.reject({ - payload: originalPayload, - type: sentryRequest.type, - reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", - status: 429, - })]; - } - return [2 /*return*/, this._buffer.add(function () { - return new Promise(function (resolve, reject) { - if (!_this.module) { - throw new utils_1.SentryError('No module available'); - } - var options = _this._getRequestOptions(_this.urlParser(sentryRequest.url)); - var req = _this.module.request(options, function (res) { - var statusCode = res.statusCode || 500; - var status = utils_1.eventStatusFromHttpCode(statusCode); - res.setEncoding('utf8'); - /** - * "Key-value pairs of header names and values. Header names are lower-cased." - * https://nodejs.org/api/http.html#http_message_headers - */ - var retryAfterHeader = res.headers ? res.headers['retry-after'] : ''; - retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader); - var rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : ''; - rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader); - var headers = { - 'x-sentry-rate-limits': rlHeader, - 'retry-after': retryAfterHeader, - }; - var limited = _this._handleRateLimit(headers); - if (limited) - utils_1.isDebugBuild() && - utils_1.logger.warn("Too many " + sentryRequest.type + " requests, backing off until: " + _this._disabledUntil(sentryRequest.type)); - if (status === 'success') { - resolve({ status: status }); - } - else { - var rejectionMessage = "HTTP Error (" + statusCode + ")"; - if (res.headers && res.headers['x-sentry-error']) { - rejectionMessage += ": " + res.headers['x-sentry-error']; - } - reject(new utils_1.SentryError(rejectionMessage)); - } - // Force the socket to drain - res.on('data', function () { - // Drain - }); - res.on('end', function () { - // Drain - }); - }); - req.on('error', reject); - req.end(sentryRequest.body); - }); - })]; - }); - }); - }; - return BaseTransport; -}()); -exports.BaseTransport = BaseTransport; -//# sourceMappingURL=index.js.map + } -/***/ }), + return input; +} -/***/ 84490: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function sanitizeTagValue(value) { + return [...value].reduce((acc, char) => acc + getCharOrReplacement(char), ''); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var http = __nccwpck_require__(13685); -var base_1 = __nccwpck_require__(41194); -/** Node http module transport */ -var HTTPTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = _this._getProxy('http'); - _this.module = http; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; +/** + * Sanitizes tags. + */ +function sanitizeTags(unsanitizedTags) { + const tags = {}; + for (const key in unsanitizedTags) { + if (Object.prototype.hasOwnProperty.call(unsanitizedTags, key)) { + const sanitizedKey = sanitizeTagKey(key); + tags[sanitizedKey] = sanitizeTagValue(String(unsanitizedTags[key])); } - /** - * @inheritDoc - */ - HTTPTransport.prototype.sendEvent = function (event) { - return this._send(core_1.eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - HTTPTransport.prototype.sendSession = function (session) { - return this._send(core_1.sessionToSentryRequest(session, this._api), session); - }; - return HTTPTransport; -}(base_1.BaseTransport)); -exports.HTTPTransport = HTTPTransport; -//# sourceMappingURL=http.js.map - -/***/ }), + } + return tags; +} -/***/ 68621: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports.getBucketKey = getBucketKey; +exports.sanitizeMetricKey = sanitizeMetricKey; +exports.sanitizeTags = sanitizeTags; +exports.sanitizeUnit = sanitizeUnit; +exports.serializeMetricBuckets = serializeMetricBuckets; +exports.simpleHash = simpleHash; +//# sourceMappingURL=utils.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var https = __nccwpck_require__(95687); -var base_1 = __nccwpck_require__(41194); -/** Node https module transport */ -var HTTPSTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPSTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPSTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = _this._getProxy('https'); - _this.module = https; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; - } - /** - * @inheritDoc - */ - HTTPSTransport.prototype.sendEvent = function (event) { - return this._send(core_1.eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - HTTPSTransport.prototype.sendSession = function (session) { - return this._send(core_1.sessionToSentryRequest(session, this._api), session); - }; - return HTTPSTransport; -}(base_1.BaseTransport)); -exports.HTTPSTransport = HTTPSTransport; -//# sourceMappingURL=https.js.map /***/ }), -/***/ 21437: +/***/ 80022: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var base_1 = __nccwpck_require__(41194); -exports.BaseTransport = base_1.BaseTransport; -var http_1 = __nccwpck_require__(84490); -exports.HTTPTransport = http_1.HTTPTransport; -var https_1 = __nccwpck_require__(68621); -exports.HTTPSTransport = https_1.HTTPSTransport; -var new_1 = __nccwpck_require__(72208); -exports.makeNodeTransport = new_1.makeNodeTransport; -//# sourceMappingURL=index.js.map -/***/ }), - -/***/ 72208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const utils = __nccwpck_require__(25304); +const eventProcessors = __nccwpck_require__(57155); +const session = __nccwpck_require__(8114); +const applyScopeDataToEvent = __nccwpck_require__(47103); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var url_1 = __nccwpck_require__(57310); /** - * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. + * Default value for maximum number of breadcrumbs added to an event. */ -function makeNodeTransport(options) { - var _a; - var urlSegments = new url_1.URL(options.url); - var isHttps = urlSegments.protocol === 'https:'; - // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` - // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` - var proxy = applyNoProxyOption(urlSegments, options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy); - var nativeHttpModule = isHttps ? https : http; - // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node - // versions(>= 8) as they had memory leaks when using it: #2555 - var agent = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new nativeHttpModule.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - var requestExecutor = createRequestExecutor(options, (_a = options.httpModule, (_a !== null && _a !== void 0 ? _a : nativeHttpModule)), agent); - return core_1.createTransport({ bufferSize: options.bufferSize }, requestExecutor); -} -exports.makeNodeTransport = makeNodeTransport; +const DEFAULT_MAX_BREADCRUMBS = 100; + /** - * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * @param transportUrl The URL the transport intends to send events to. - * @param proxy The client configured proxy. - * @returns A proxy the transport should use. + * The global scope is kept in this module. + * When accessing this via `getGlobalScope()` we'll make sure to set one if none is currently present. */ -function applyNoProxyOption(transportUrlSegments, proxy) { - var no_proxy = process.env.no_proxy; - var urlIsExemptFromProxy = no_proxy && - no_proxy - .split(',') - .some(function (exemption) { return transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption); }); - if (urlIsExemptFromProxy) { - return undefined; - } - else { - return proxy; - } -} +let globalScope; + /** - * Creates a RequestExecutor to be used with `createTransport`. + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. */ -function createRequestExecutor(options, httpModule, agent) { - var _a = new url_1.URL(options.url), hostname = _a.hostname, pathname = _a.pathname, port = _a.port, protocol = _a.protocol, search = _a.search; - return function makeRequest(request) { - return new Promise(function (resolve, reject) { - var req = httpModule.request({ - method: 'POST', - agent: agent, - headers: options.headers, - hostname: hostname, - path: "" + pathname + search, - port: port, - protocol: protocol, - ca: options.caCerts, - }, function (res) { - var _a, _b, _c; - res.on('data', function () { - // Drain socket - }); - res.on('end', function () { - // Drain socket - }); - var statusCode = (_a = res.statusCode, (_a !== null && _a !== void 0 ? _a : 500)); - var status = utils_1.eventStatusFromHttpCode(statusCode); - res.setEncoding('utf8'); - // "Key-value pairs of header names and values. Header names are lower-cased." - // https://nodejs.org/api/http.html#http_message_headers - var retryAfterHeader = (_b = res.headers['retry-after'], (_b !== null && _b !== void 0 ? _b : null)); - var rateLimitsHeader = (_c = res.headers['x-sentry-rate-limits'], (_c !== null && _c !== void 0 ? _c : null)); - resolve({ - headers: { - 'retry-after': retryAfterHeader, - 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, - }, - reason: status, - statusCode: statusCode, - }); - }); - req.on('error', reject); - req.end(request.body); - }); - }; -} -//# sourceMappingURL=new.js.map +class Scope { + /** Flag if notifying is happening. */ -/***/ }), + /** Callback for client to receive scope changes. */ -/***/ 27937: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** Callback list that will be called after {@link applyToEvent}. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - var targetDirAbsPath = path.resolve(targetDir); - if (!fs.existsSync(targetDirAbsPath)) { - throw new Error("Cannot read contents of " + targetDirAbsPath + ". Directory does not exist."); - } - if (!fs.statSync(targetDirAbsPath).isDirectory()) { - throw new Error("Cannot read contents of " + targetDirAbsPath + ", because it is not a directory."); - } - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - var deepReadCurrentDir = function (currentDirAbsPath) { - return fs.readdirSync(currentDirAbsPath).reduce(function (absPaths, itemName) { - var itemAbsPath = path.join(currentDirAbsPath, itemName); - if (fs.statSync(itemAbsPath).isDirectory()) { - return tslib_1.__spread(absPaths, deepReadCurrentDir(itemAbsPath)); - } - return tslib_1.__spread(absPaths, [itemAbsPath]); - }, []); - }; - return deepReadCurrentDir(targetDirAbsPath).map(function (absPath) { return path.relative(targetDirAbsPath, absPath); }); -} -exports.deepReadDirSync = deepReadDirSync; -//# sourceMappingURL=utils.js.map + /** Array of breadcrumbs. */ -/***/ }), + /** User */ -/***/ 31271: -/***/ ((__unused_webpack_module, exports) => { + /** Tags */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata -exports.SDK_NAME = 'sentry.javascript.node'; -//# sourceMappingURL=version.js.map + /** Extra */ -/***/ }), + /** Contexts */ -/***/ 83789: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** Attachments */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var severity_1 = __nccwpck_require__(94124); -exports.Severity = severity_1.Severity; -var severity_2 = __nccwpck_require__(94124); -exports.SeverityLevels = severity_2.SeverityLevels; -//# sourceMappingURL=index.js.map + /** Propagation Context for distributed tracing */ -/***/ }), + /** + * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get + * sent to Sentry + */ -/***/ 94124: -/***/ ((__unused_webpack_module, exports) => { + /** Fingerprint */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * TODO(v7): Remove this enum and replace with SeverityLevel - */ -var Severity; -(function (Severity) { - /** JSDoc */ - Severity["Fatal"] = "fatal"; - /** JSDoc */ - Severity["Error"] = "error"; - /** JSDoc */ - Severity["Warning"] = "warning"; - /** JSDoc */ - Severity["Log"] = "log"; - /** JSDoc */ - Severity["Info"] = "info"; - /** JSDoc */ - Severity["Debug"] = "debug"; - /** JSDoc */ - Severity["Critical"] = "critical"; -})(Severity = exports.Severity || (exports.Severity = {})); -// TODO: in v7, these can disappear, because they now also exist in `@sentry/utils`. (Having them there rather than here -// is nice because then it enforces the idea that only types are exported from `@sentry/types`.) -exports.SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical']; -//# sourceMappingURL=severity.js.map + /** Severity */ + // eslint-disable-next-line deprecation/deprecation -/***/ }), + /** + * Transaction Name + */ -/***/ 58343: -/***/ ((__unused_webpack_module, exports) => { + /** Span */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Consumes the promise and logs the error when it rejects. - * @param promise A promise to forget. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function forget(promise) { - void promise.then(null, function (e) { - // TODO: Use a better logging mechanism - // eslint-disable-next-line no-console - console.error(e); - }); -} -exports.forget = forget; -//# sourceMappingURL=async.js.map + /** Session */ -/***/ }), + /** Request Mode Session Status */ -/***/ 30597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** The client on this scope */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -var is_1 = __nccwpck_require__(92757); -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem, keyAttrs) { - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - var currentElem = elem; - var MAX_TRAVERSE_HEIGHT = 5; - var MAX_OUTPUT_LEN = 80; - var out = []; - var height = 0; - var len = 0; - var separator = ' > '; - var sepLength = separator.length; - var nextStr = void 0; - // eslint-disable-next-line no-plusplus - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem, keyAttrs); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - out.push(nextStr); - len += nextStr.length; - currentElem = currentElem.parentNode; - } - return out.reverse().join(separator); - } - catch (_oO) { - return ''; - } -} -exports.htmlTreeAsString = htmlTreeAsString; -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el, keyAttrs) { - var elem = el; - var out = []; - var className; - var classes; - var key; - var attr; - var i; - if (!elem || !elem.tagName) { - return ''; - } - out.push(elem.tagName.toLowerCase()); - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - var keyAttrPairs = keyAttrs && keyAttrs.length - ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; }) - : null; - if (keyAttrPairs && keyAttrPairs.length) { - keyAttrPairs.forEach(function (keyAttrPair) { - out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]"); - }); - } - else { - if (elem.id) { - out.push("#" + elem.id); - } - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && is_1.isString(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push("." + classes[i]); - } - } - } - var allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push("[" + key + "=\"" + attr + "\"]"); - } - } - return out.join(''); -} -/** - * A safe form of location.href - */ -function getLocationHref() { - var global = global_1.getGlobalObject(); - try { - return global.document.location.href; - } - catch (oO) { - return ''; - } -} -exports.getLocationHref = getLocationHref; -//# sourceMappingURL=browser.js.map + // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. -/***/ }), + constructor() { + this._notifyingListeners = false; + this._scopeListeners = []; + this._eventProcessors = []; + this._breadcrumbs = []; + this._attachments = []; + this._user = {}; + this._tags = {}; + this._extra = {}; + this._contexts = {}; + this._sdkProcessingMetadata = {}; + this._propagationContext = generatePropagationContext(); + } -/***/ 38857: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Inherit values from the parent scope. + * @deprecated Use `scope.clone()` and `new Scope()` instead. + */ + static clone(scope) { + return scope ? scope.clone() : new Scope(); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var envelope_1 = __nccwpck_require__(6222); -var time_1 = __nccwpck_require__(1735); -/** - * Creates client report envelope - * @param discarded_events An array of discard events - * @param dsn A DSN that can be set on the header. Optional. - */ -function createClientReportEnvelope(discarded_events, dsn, timestamp) { - var clientReportItem = [ - { type: 'client_report' }, - { - timestamp: timestamp || time_1.dateTimestampInSeconds(), - discarded_events: discarded_events, - }, - ]; - return envelope_1.createEnvelope(dsn ? { dsn: dsn } : {}, [clientReportItem]); -} -exports.createClientReportEnvelope = createClientReportEnvelope; -//# sourceMappingURL=clientreport.js.map + /** + * Clone this scope instance. + */ + clone() { + const newScope = new Scope(); + newScope._breadcrumbs = [...this._breadcrumbs]; + newScope._tags = { ...this._tags }; + newScope._extra = { ...this._extra }; + newScope._contexts = { ...this._contexts }; + newScope._user = this._user; + newScope._level = this._level; + newScope._span = this._span; + newScope._session = this._session; + newScope._transactionName = this._transactionName; + newScope._fingerprint = this._fingerprint; + newScope._eventProcessors = [...this._eventProcessors]; + newScope._requestSession = this._requestSession; + newScope._attachments = [...this._attachments]; + newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata }; + newScope._propagationContext = { ...this._propagationContext }; + newScope._client = this._client; + + return newScope; + } + + /** Update the client on the scope. */ + setClient(client) { + this._client = client; + } -/***/ }), + /** + * Get the client assigned to this scope. + * + * It is generally recommended to use the global function `Sentry.getClient()` instead, unless you know what you are doing. + */ + getClient() { + return this._client; + } -/***/ 3275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + addScopeListener(callback) { + this._scopeListeners.push(callback); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var env_1 = __nccwpck_require__(31913); -var error_1 = __nccwpck_require__(66238); -/** Regular expression used to parse a Dsn. */ -var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; -function isValidProtocol(protocol) { - return protocol === 'http' || protocol === 'https'; -} -/** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ -function dsnToString(dsn, withPassword) { - if (withPassword === void 0) { withPassword = false; } - var host = dsn.host, path = dsn.path, pass = dsn.pass, port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey; - return (protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : '') + - ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); -} -exports.dsnToString = dsnToString; -function dsnFromString(str) { - var match = DSN_REGEX.exec(str); - if (!match) { - throw new error_1.SentryError("Invalid Sentry Dsn: " + str); - } - var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], publicKey = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; - var path = ''; - var projectId = lastPath; - var split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop(); - } - if (projectId) { - var projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - return dsnFromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, publicKey: publicKey }); -} -function dsnFromComponents(components) { - // TODO this is for backwards compatibility, and can be removed in a future version - if ('user' in components && !('publicKey' in components)) { - components.publicKey = components.user; + /** + * @inheritDoc + */ + addEventProcessor(callback) { + this._eventProcessors.push(callback); + return this; + } + + /** + * @inheritDoc + */ + setUser(user) { + // If null is passed we want to unset everything, but still define keys, + // so that later down in the pipeline any existing values are cleared. + this._user = user || { + email: undefined, + id: undefined, + ip_address: undefined, + segment: undefined, + username: undefined, + }; + + if (this._session) { + session.updateSession(this._session, { user }); } - return { - user: components.publicKey || '', - protocol: components.protocol, - publicKey: components.publicKey || '', - pass: components.pass || '', - host: components.host, - port: components.port || '', - path: components.path || '', - projectId: components.projectId, + + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + getUser() { + return this._user; + } + + /** + * @inheritDoc + */ + getRequestSession() { + return this._requestSession; + } + + /** + * @inheritDoc + */ + setRequestSession(requestSession) { + this._requestSession = requestSession; + return this; + } + + /** + * @inheritDoc + */ + setTags(tags) { + this._tags = { + ...this._tags, + ...tags, }; -} -function validateDsn(dsn) { - if (!env_1.isDebugBuild()) { - return; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setTag(key, value) { + this._tags = { ...this._tags, [key]: value }; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setExtras(extras) { + this._extra = { + ...this._extra, + ...extras, + }; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setExtra(key, extra) { + this._extra = { ...this._extra, [key]: extra }; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setFingerprint(fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setLevel( + // eslint-disable-next-line deprecation/deprecation + level, + ) { + this._level = level; + this._notifyScopeListeners(); + return this; + } + + /** + * Sets the transaction name on the scope for future events. + */ + setTransactionName(name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + setContext(key, context) { + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; + } else { + this._contexts[key] = context; } - var port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol; - var requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; - requiredComponents.forEach(function (component) { - if (!dsn[component]) { - throw new error_1.SentryError("Invalid Sentry Dsn: " + component + " missing"); - } - }); - if (!projectId.match(/^\d+$/)) { - throw new error_1.SentryError("Invalid Sentry Dsn: Invalid projectId " + projectId); + + this._notifyScopeListeners(); + return this; + } + + /** + * Sets the Span on the scope. + * @param span Span + * @deprecated Instead of setting a span on a scope, use `startSpan()`/`startSpanManual()` instead. + */ + setSpan(span) { + this._span = span; + this._notifyScopeListeners(); + return this; + } + + /** + * Returns the `Span` if there is one. + * @deprecated Use `getActiveSpan()` instead. + */ + getSpan() { + return this._span; + } + + /** + * Returns the `Transaction` attached to the scope (if there is one). + * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead. + */ + getTransaction() { + // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will + // have a pointer to the currently-active transaction. + const span = this._span; + // Cannot replace with getRootSpan because getRootSpan returns a span, not a transaction + // Also, this method will be removed anyway. + // eslint-disable-next-line deprecation/deprecation + return span && span.transaction; + } + + /** + * @inheritDoc + */ + setSession(session) { + if (!session) { + delete this._session; + } else { + this._session = session; } - if (!isValidProtocol(protocol)) { - throw new error_1.SentryError("Invalid Sentry Dsn: Invalid protocol " + protocol); + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + getSession() { + return this._session; + } + + /** + * @inheritDoc + */ + update(captureContext) { + if (!captureContext) { + return this; } - if (port && isNaN(parseInt(port, 10))) { - throw new error_1.SentryError("Invalid Sentry Dsn: Invalid port " + port); + + const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext; + + if (scopeToMerge instanceof Scope) { + const scopeData = scopeToMerge.getScopeData(); + + this._tags = { ...this._tags, ...scopeData.tags }; + this._extra = { ...this._extra, ...scopeData.extra }; + this._contexts = { ...this._contexts, ...scopeData.contexts }; + if (scopeData.user && Object.keys(scopeData.user).length) { + this._user = scopeData.user; + } + if (scopeData.level) { + this._level = scopeData.level; + } + if (scopeData.fingerprint.length) { + this._fingerprint = scopeData.fingerprint; + } + if (scopeToMerge.getRequestSession()) { + this._requestSession = scopeToMerge.getRequestSession(); + } + if (scopeData.propagationContext) { + this._propagationContext = scopeData.propagationContext; + } + } else if (utils.isPlainObject(scopeToMerge)) { + const scopeContext = captureContext ; + this._tags = { ...this._tags, ...scopeContext.tags }; + this._extra = { ...this._extra, ...scopeContext.extra }; + this._contexts = { ...this._contexts, ...scopeContext.contexts }; + if (scopeContext.user) { + this._user = scopeContext.user; + } + if (scopeContext.level) { + this._level = scopeContext.level; + } + if (scopeContext.fingerprint) { + this._fingerprint = scopeContext.fingerprint; + } + if (scopeContext.requestSession) { + this._requestSession = scopeContext.requestSession; + } + if (scopeContext.propagationContext) { + this._propagationContext = scopeContext.propagationContext; + } } - return true; -} -/** The Sentry Dsn, identifying a Sentry instance and project. */ -function makeDsn(from) { - var components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); - validateDsn(components); - return components; -} -exports.makeDsn = makeDsn; -//# sourceMappingURL=dsn.js.map -/***/ }), + return this; + } -/***/ 19489: -/***/ ((__unused_webpack_module, exports) => { + /** + * @inheritDoc + */ + clear() { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._requestSession = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + this._attachments = []; + this._propagationContext = generatePropagationContext(); + return this; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug', 'critical']; -//# sourceMappingURL=enums.js.map + /** + * @inheritDoc + */ + addBreadcrumb(breadcrumb, maxBreadcrumbs) { + const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; -/***/ }), + // No data has been changed, so don't notify scope listeners + if (maxCrumbs <= 0) { + return this; + } -/***/ 31913: -/***/ ((__unused_webpack_module, exports) => { + const mergedBreadcrumb = { + timestamp: utils.dateTimestampInSeconds(), + ...breadcrumb, + }; + + const breadcrumbs = this._breadcrumbs; + breadcrumbs.push(mergedBreadcrumb); + this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs; + + this._notifyScopeListeners(); + + return this; + } + + /** + * @inheritDoc + */ + getLastBreadcrumb() { + return this._breadcrumbs[this._breadcrumbs.length - 1]; + } + + /** + * @inheritDoc + */ + clearBreadcrumbs() { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + } + + /** + * @inheritDoc + */ + addAttachment(attachment) { + this._attachments.push(attachment); + return this; + } + + /** + * @inheritDoc + * @deprecated Use `getScopeData()` instead. + */ + getAttachments() { + const data = this.getScopeData(); + + return data.attachments; + } + + /** + * @inheritDoc + */ + clearAttachments() { + this._attachments = []; + return this; + } + + /** @inheritDoc */ + getScopeData() { + const { + _breadcrumbs, + _attachments, + _contexts, + _tags, + _extra, + _user, + _level, + _fingerprint, + _eventProcessors, + _propagationContext, + _sdkProcessingMetadata, + _transactionName, + _span, + } = this; + + return { + breadcrumbs: _breadcrumbs, + attachments: _attachments, + contexts: _contexts, + tags: _tags, + extra: _extra, + user: _user, + level: _level, + fingerprint: _fingerprint || [], + eventProcessors: _eventProcessors, + propagationContext: _propagationContext, + sdkProcessingMetadata: _sdkProcessingMetadata, + transactionName: _transactionName, + span: _span, + }; + } + + /** + * Applies data from the scope to the event and runs all event processors on it. + * + * @param event Event + * @param hint Object containing additional information about the original exception, for use by the event processors. + * @hidden + * @deprecated Use `applyScopeDataToEvent()` directly + */ + applyToEvent( + event, + hint = {}, + additionalEventProcessors = [], + ) { + applyScopeDataToEvent.applyScopeDataToEvent(event, this.getScopeData()); + + // TODO (v8): Update this order to be: Global > Client > Scope + const eventProcessors$1 = [ + ...additionalEventProcessors, + // eslint-disable-next-line deprecation/deprecation + ...eventProcessors.getGlobalEventProcessors(), + ...this._eventProcessors, + ]; + + return eventProcessors.notifyEventProcessors(eventProcessors$1, event, hint); + } + + /** + * Add data which will be accessible during event processing but won't get sent to Sentry + */ + setSDKProcessingMetadata(newData) { + this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; + + return this; + } + + /** + * @inheritDoc + */ + setPropagationContext(context) { + this._propagationContext = context; + return this; + } + + /** + * @inheritDoc + */ + getPropagationContext() { + return this._propagationContext; + } + + /** + * Capture an exception for this scope. + * + * @param exception The exception to capture. + * @param hint Optinal additional data to attach to the Sentry event. + * @returns the id of the captured Sentry event. + */ + captureException(exception, hint) { + const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4(); + + if (!this._client) { + utils.logger.warn('No client configured on scope - will not capture exception!'); + return eventId; + } + + const syntheticException = new Error('Sentry syntheticException'); + + this._client.captureException( + exception, + { + originalException: exception, + syntheticException, + ...hint, + event_id: eventId, + }, + this, + ); + + return eventId; + } + + /** + * Capture a message for this scope. + * + * @param message The message to capture. + * @param level An optional severity level to report the message with. + * @param hint Optional additional data to attach to the Sentry event. + * @returns the id of the captured message. + */ + captureMessage(message, level, hint) { + const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4(); + + if (!this._client) { + utils.logger.warn('No client configured on scope - will not capture message!'); + return eventId; + } + + const syntheticException = new Error(message); + + this._client.captureMessage( + message, + level, + { + originalException: message, + syntheticException, + ...hint, + event_id: eventId, + }, + this, + ); + + return eventId; + } + + /** + * Captures a manually created event for this scope and sends it to Sentry. + * + * @param exception The event to capture. + * @param hint Optional additional data to attach to the Sentry event. + * @returns the id of the captured event. + */ + captureEvent(event, hint) { + const eventId = hint && hint.event_id ? hint.event_id : utils.uuid4(); + + if (!this._client) { + utils.logger.warn('No client configured on scope - will not capture event!'); + return eventId; + } + + this._client.captureEvent(event, { ...hint, event_id: eventId }, this); + + return eventId; + } + + /** + * This will be called on every set call. + */ + _notifyScopeListeners() { + // We need this check for this._notifyingListeners to be able to work on scope during updates + // If this check is not here we'll produce endless recursion when something is done with the scope + // during the callback. + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach(callback => { + callback(this); + }); + this._notifyingListeners = false; + } + } +} /** - * This module exists for optimizations in the build process through rollup and terser. We define some global - * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these - * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will - * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to - * `logger` and preventing node-related code from appearing in browser bundles. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var __SENTRY_DEBUG__ = true; -/** - * Figures out if we're building with debug functionality. - * - * @returns true if this is a debug build + * Get the global scope. + * This scope is applied to _all_ events. */ -function isDebugBuild() { - return __SENTRY_DEBUG__; +function getGlobalScope() { + if (!globalScope) { + globalScope = new Scope(); + } + + return globalScope; } -exports.isDebugBuild = isDebugBuild; + /** - * Figures out if we're building a browser bundle. - * - * @returns true if this is a browser bundle build. + * This is mainly needed for tests. + * DO NOT USE this, as this is an internal API and subject to change. + * @hidden */ -function isBrowserBundle() { - return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; +function setGlobalScope(scope) { + globalScope = scope; } -exports.isBrowserBundle = isBrowserBundle; -//# sourceMappingURL=env.js.map + +function generatePropagationContext() { + return { + traceId: utils.uuid4(), + spanId: utils.uuid4().substring(16), + }; +} + +exports.Scope = Scope; +exports.getGlobalScope = getGlobalScope; +exports.setGlobalScope = setGlobalScope; +//# sourceMappingURL=scope.js.map + /***/ }), -/***/ 6222: +/***/ 60954: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var is_1 = __nccwpck_require__(92757); -/** - * Creates an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function createEnvelope(headers, items) { - if (items === void 0) { items = []; } - return [headers, items]; -} -exports.createEnvelope = createEnvelope; + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const exports$1 = __nccwpck_require__(61117); +const hub = __nccwpck_require__(5553); + +/** A class object that can instantiate Client objects. */ + /** - * Add an item to an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. + * + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. */ -function addItemToEnvelope(envelope, newItem) { - var _a = tslib_1.__read(envelope, 2), headers = _a[0], items = _a[1]; - return [headers, tslib_1.__spread(items, [newItem])]; +function initAndBind( + clientClass, + options, +) { + if (options.debug === true) { + if (debugBuild.DEBUG_BUILD) { + utils.logger.enable(); + } else { + // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped + utils.consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + }); + } + } + const scope = exports$1.getCurrentScope(); + scope.update(options.initialScope); + + const client = new clientClass(options); + setCurrentClient(client); + initializeClient(client); } -exports.addItemToEnvelope = addItemToEnvelope; + /** - * Get the type of the envelope. Grabs the type from the first envelope item. + * Make the given client the current client. */ -function getEnvelopeType(envelope) { - var _a = tslib_1.__read(envelope, 2), _b = tslib_1.__read(_a[1], 1), _c = tslib_1.__read(_b[0], 1), firstItemHeader = _c[0]; - return firstItemHeader.type; +function setCurrentClient(client) { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const top = hub$1.getStackTop(); + top.client = client; + top.scope.setClient(client); } -exports.getEnvelopeType = getEnvelopeType; + /** - * Serializes an envelope into a string. + * Initialize the client for the current scope. + * Make sure to call this after `setCurrentClient()`. */ -function serializeEnvelope(envelope) { - var _a = tslib_1.__read(envelope, 2), headers = _a[0], items = _a[1]; - var serializedHeaders = JSON.stringify(headers); - // Have to cast items to any here since Envelope is a union type - // Fixed in Typescript 4.2 - // TODO: Remove any[] cast when we upgrade to TS 4.2 - // https://github.com/microsoft/TypeScript/issues/36390 - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return items.reduce(function (acc, item) { - var _a = tslib_1.__read(item, 2), itemHeaders = _a[0], payload = _a[1]; - // We do not serialize payloads that are primitives - var serializedPayload = is_1.isPrimitive(payload) ? String(payload) : JSON.stringify(payload); - return acc + "\n" + JSON.stringify(itemHeaders) + "\n" + serializedPayload; - }, serializedHeaders); +function initializeClient(client) { + if (client.init) { + client.init(); + // TODO v8: Remove this fallback + // eslint-disable-next-line deprecation/deprecation + } else if (client.setupIntegrations) { + // eslint-disable-next-line deprecation/deprecation + client.setupIntegrations(); + } } -exports.serializeEnvelope = serializeEnvelope; -//# sourceMappingURL=envelope.js.map + +exports.initAndBind = initAndBind; +exports.setCurrentClient = setCurrentClient; +//# sourceMappingURL=sdk.js.map + /***/ }), -/***/ 66238: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 52781: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var polyfill_1 = __nccwpck_require__(1243); -/** An error emitted by Sentry SDKs and related utilities. */ -var SentryError = /** @class */ (function (_super) { - tslib_1.__extends(SentryError, _super); - function SentryError(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - _this.message = message; - _this.name = _newTarget.prototype.constructor.name; - polyfill_1.setPrototypeOf(_this, _newTarget.prototype); - return _this; - } - return SentryError; -}(Error)); -exports.SentryError = SentryError; -//# sourceMappingURL=error.js.map -/***/ }), +/** + * Use this attribute to represent the source of a span. + * Should be one of: custom, url, route, view, component, task, unknown + * + */ +const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source'; -/***/ 68813: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Use this attribute to represent the sample rate used for a span. + */ +const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate'; /** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + * Use this attribute to represent the operation of a span. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var node_1 = __nccwpck_require__(16411); -var fallbackGlobalObject = {}; +const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op'; + /** - * Safely get global scope object - * - * @returns Global scope object + * Use this attribute to represent the origin of a span. */ -function getGlobalObject() { - return (node_1.isNodeEnv() - ? global - : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals - ? window // eslint-disable-line no-restricted-globals - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); -} -exports.getGlobalObject = getGlobalObject; -//# sourceMappingURL=global.js.map +const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin'; -/***/ }), +/** + * The id of the profile that this span occured in. + */ +const SEMANTIC_ATTRIBUTE_PROFILE_ID = 'profile_id'; -/***/ 1620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +exports.SEMANTIC_ATTRIBUTE_PROFILE_ID = SEMANTIC_ATTRIBUTE_PROFILE_ID; +exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = SEMANTIC_ATTRIBUTE_SENTRY_OP; +exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = SEMANTIC_ATTRIBUTE_SENTRY_SOURCE; +//# sourceMappingURL=semanticAttributes.js.map -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -tslib_1.__exportStar(__nccwpck_require__(58343), exports); -tslib_1.__exportStar(__nccwpck_require__(30597), exports); -tslib_1.__exportStar(__nccwpck_require__(3275), exports); -tslib_1.__exportStar(__nccwpck_require__(19489), exports); -tslib_1.__exportStar(__nccwpck_require__(66238), exports); -tslib_1.__exportStar(__nccwpck_require__(68813), exports); -tslib_1.__exportStar(__nccwpck_require__(65474), exports); -tslib_1.__exportStar(__nccwpck_require__(92757), exports); -tslib_1.__exportStar(__nccwpck_require__(15577), exports); -tslib_1.__exportStar(__nccwpck_require__(49515), exports); -tslib_1.__exportStar(__nccwpck_require__(32154), exports); -tslib_1.__exportStar(__nccwpck_require__(16411), exports); -tslib_1.__exportStar(__nccwpck_require__(28592), exports); -tslib_1.__exportStar(__nccwpck_require__(69249), exports); -tslib_1.__exportStar(__nccwpck_require__(39188), exports); -tslib_1.__exportStar(__nccwpck_require__(31811), exports); -tslib_1.__exportStar(__nccwpck_require__(68853), exports); -tslib_1.__exportStar(__nccwpck_require__(5986), exports); -tslib_1.__exportStar(__nccwpck_require__(70313), exports); -tslib_1.__exportStar(__nccwpck_require__(66538), exports); -tslib_1.__exportStar(__nccwpck_require__(88714), exports); -tslib_1.__exportStar(__nccwpck_require__(87833), exports); -tslib_1.__exportStar(__nccwpck_require__(1735), exports); -tslib_1.__exportStar(__nccwpck_require__(66850), exports); -tslib_1.__exportStar(__nccwpck_require__(31913), exports); -tslib_1.__exportStar(__nccwpck_require__(6222), exports); -tslib_1.__exportStar(__nccwpck_require__(38857), exports); -tslib_1.__exportStar(__nccwpck_require__(69377), exports); -//# sourceMappingURL=index.js.map /***/ }), -/***/ 65474: +/***/ 99508: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var env_1 = __nccwpck_require__(31913); -var global_1 = __nccwpck_require__(68813); -var is_1 = __nccwpck_require__(92757); -var logger_1 = __nccwpck_require__(15577); -var object_1 = __nccwpck_require__(69249); -var stacktrace_1 = __nccwpck_require__(5986); -var supports_1 = __nccwpck_require__(88714); -var global = global_1.getGlobalObject(); -/** - * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. - * - Console API - * - Fetch API - * - XHR API - * - History API - * - DOM API (click/typing) - * - Error API - * - UnhandledRejection API - */ -var handlers = {}; -var instrumented = {}; -/** Instruments given API */ -function instrument(type) { - if (instrumented[type]) { - return; - } - instrumented[type] = true; - switch (type) { - case 'console': - instrumentConsole(); - break; - case 'dom': - instrumentDOM(); - break; - case 'xhr': - instrumentXHR(); - break; - case 'fetch': - instrumentFetch(); - break; - case 'history': - instrumentHistory(); - break; - case 'error': - instrumentError(); - break; - case 'unhandledrejection': - instrumentUnhandledRejection(); - break; - default: - env_1.isDebugBuild() && logger_1.logger.warn('unknown instrumentation type:', type); - return; - } -} + +const utils = __nccwpck_require__(25304); +const baseclient = __nccwpck_require__(35746); +const checkin = __nccwpck_require__(74109); +const debugBuild = __nccwpck_require__(44220); +const exports$1 = __nccwpck_require__(61117); +const aggregator = __nccwpck_require__(456); +const sessionflusher = __nccwpck_require__(27749); +const hubextensions = __nccwpck_require__(69866); +const spanUtils = __nccwpck_require__(19925); +const getRootSpan = __nccwpck_require__(55660); +__nccwpck_require__(13973); +const dynamicSamplingContext = __nccwpck_require__(65372); + /** - * Add handler that will be called when given type of instrumentation triggers. - * Use at your own risk, this might break without changelog notice, only used internally. - * @hidden + * The Sentry Server Runtime Client SDK. */ -function addInstrumentationHandler(type, callback) { - handlers[type] = handlers[type] || []; - handlers[type].push(callback); - instrument(type); -} -exports.addInstrumentationHandler = addInstrumentationHandler; -/** JSDoc */ -function triggerHandlers(type, data) { - var e_1, _a; - if (!type || !handlers[type]) { - return; +class ServerRuntimeClient + + extends baseclient.BaseClient { + + /** + * Creates a new Edge SDK instance. + * @param options Configuration options for this SDK. + */ + constructor(options) { + // Server clients always support tracing + hubextensions.addTracingExtensions(); + + super(options); + + if (options._experiments && options._experiments['metricsAggregator']) { + this.metricsAggregator = new aggregator.MetricsAggregator(this); } - try { - for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { - var handler = _c.value; - try { - handler(data); - } - catch (e) { - env_1.isDebugBuild() && - logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError:", e); - } - } + } + + /** + * @inheritDoc + */ + eventFromException(exception, hint) { + return utils.resolvedSyncPromise(utils.eventFromUnknownInput(exports$1.getClient(), this._options.stackParser, exception, hint)); + } + + /** + * @inheritDoc + */ + eventFromMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + ) { + return utils.resolvedSyncPromise( + utils.eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace), + ); + } + + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const requestSession = scope.getRequestSession(); + + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + + return super.captureException(exception, hint, scope); + } + + /** + * @inheritDoc + */ + captureEvent(event, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const eventType = event.type || 'exception'; + const isException = + eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; + + // If the event is of type Exception, then a request session should be captured + if (isException) { + const requestSession = scope.getRequestSession(); + + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; } - finally { if (e_1) throw e_1.error; } + } } -} -/** JSDoc */ -function instrumentConsole() { - if (!('console' in global)) { - return; + + return super.captureEvent(event, hint, scope); + } + + /** + * + * @inheritdoc + */ + close(timeout) { + if (this._sessionFlusher) { + this._sessionFlusher.close(); } - logger_1.CONSOLE_LEVELS.forEach(function (level) { - if (!(level in global.console)) { - return; - } - object_1.fill(global.console, level, function (originalConsoleMethod) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - triggerHandlers('console', { args: args, level: level }); - // this fails for some browsers. :( - if (originalConsoleMethod) { - originalConsoleMethod.apply(global.console, args); - } - }; - }); - }); -} -/** JSDoc */ -function instrumentFetch() { - if (!supports_1.supportsNativeFetch()) { - return; + return super.close(timeout); + } + + /** Method that initialises an instance of SessionFlusher on Client */ + initSessionFlusher() { + const { release, environment } = this._options; + if (!release) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } else { + this._sessionFlusher = new sessionflusher.SessionFlusher(this, { + release, + environment, + }); } - object_1.fill(global, 'fetch', function (originalFetch) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var handlerData = { - args: args, - fetchData: { - method: getFetchMethod(args), - url: getFetchUrl(args), - }, - startTimestamp: Date.now(), - }; - triggerHandlers('fetch', tslib_1.__assign({}, handlerData)); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalFetch.apply(global, args).then(function (response) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); - return response; - }, function (error) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); - // NOTE: If you are a Sentry user, and you are seeing this stack frame, - // it means the sentry.javascript SDK caught an error invoking your application code. - // This is expected behavior and NOT indicative of a bug with sentry.javascript. - throw error; - }); - }; - }); -} -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/** Extract `method` from fetch call arguments */ -function getFetchMethod(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { - return String(fetchArgs[0].method).toUpperCase(); + } + + /** + * Create a cron monitor check in and send it to Sentry. + * + * @param checkIn An object that describes a check in. + * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want + * to create a monitor automatically when sending a check in. + */ + captureCheckIn(checkIn, monitorConfig, scope) { + const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : utils.uuid4(); + if (!this._isEnabled()) { + debugBuild.DEBUG_BUILD && utils.logger.warn('SDK not enabled, will not capture checkin.'); + return id; + } + + const options = this.getOptions(); + const { release, environment, tunnel } = options; + + const serializedCheckIn = { + check_in_id: id, + monitor_slug: checkIn.monitorSlug, + status: checkIn.status, + release, + environment, + }; + + if ('duration' in checkIn) { + serializedCheckIn.duration = checkIn.duration; + } + + if (monitorConfig) { + serializedCheckIn.monitor_config = { + schedule: monitorConfig.schedule, + checkin_margin: monitorConfig.checkinMargin, + max_runtime: monitorConfig.maxRuntime, + timezone: monitorConfig.timezone, + }; } - if (fetchArgs[1] && fetchArgs[1].method) { - return String(fetchArgs[1].method).toUpperCase(); + + const [dynamicSamplingContext, traceContext] = this._getTraceInfoFromScope(scope); + if (traceContext) { + serializedCheckIn.contexts = { + trace: traceContext, + }; } - return 'GET'; -} -/** Extract `url` from fetch call arguments */ -function getFetchUrl(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if (typeof fetchArgs[0] === 'string') { - return fetchArgs[0]; + + const envelope = checkin.createCheckInEnvelope( + serializedCheckIn, + dynamicSamplingContext, + this.getSdkMetadata(), + tunnel, + this.getDsn(), + ); + + debugBuild.DEBUG_BUILD && utils.logger.info('Sending checkin:', checkIn.monitorSlug, checkIn.status); + + // _sendEnvelope should not throw + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this._sendEnvelope(envelope); + + return id; + } + + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + _captureRequestSession() { + if (!this._sessionFlusher) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } else { + this._sessionFlusher.incrementSessionStatusCount(); } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { - return fetchArgs[0].url; + } + + /** + * @inheritDoc + */ + _prepareEvent( + event, + hint, + scope, + isolationScope, + ) { + if (this._options.platform) { + event.platform = event.platform || this._options.platform; + } + + if (this._options.runtime) { + event.contexts = { + ...event.contexts, + runtime: (event.contexts || {}).runtime || this._options.runtime, + }; } - return String(fetchArgs[0]); -} -/* eslint-enable @typescript-eslint/no-unsafe-member-access */ -/** JSDoc */ -function instrumentXHR() { - if (!('XMLHttpRequest' in global)) { - return; + + if (this._options.serverName) { + event.server_name = event.server_name || this._options.serverName; } - var xhrproto = XMLHttpRequest.prototype; - object_1.fill(xhrproto, 'open', function (originalOpen) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var xhr = this; - var url = args[1]; - var xhrInfo = (xhr.__sentry_xhr__ = { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0], - url: args[1], - }); - // if Sentry key appears in URL, don't capture it as a request - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (is_1.isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) { - xhr.__sentry_own_request__ = true; - } - var onreadystatechangeHandler = function () { - if (xhr.readyState === 4) { - try { - // touching statusCode in some platforms throws - // an exception - xhrInfo.status_code = xhr.status; - } - catch (e) { - /* do nothing */ - } - triggerHandlers('xhr', { - args: args, - endTimestamp: Date.now(), - startTimestamp: Date.now(), - xhr: xhr, - }); - } - }; - if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { - object_1.fill(xhr, 'onreadystatechange', function (original) { - return function () { - var readyStateArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - readyStateArgs[_i] = arguments[_i]; - } - onreadystatechangeHandler(); - return original.apply(xhr, readyStateArgs); - }; - }); - } - else { - xhr.addEventListener('readystatechange', onreadystatechangeHandler); - } - return originalOpen.apply(xhr, args); - }; - }); - object_1.fill(xhrproto, 'send', function (originalSend) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (this.__sentry_xhr__ && args[0] !== undefined) { - this.__sentry_xhr__.body = args[0]; - } - triggerHandlers('xhr', { - args: args, - startTimestamp: Date.now(), - xhr: this, - }); - return originalSend.apply(this, args); - }; - }); -} -var lastHref; -/** JSDoc */ -function instrumentHistory() { - if (!supports_1.supportsHistory()) { - return; + + return super._prepareEvent(event, hint, scope, isolationScope); + } + + /** Extract trace information from scope */ + _getTraceInfoFromScope( + scope, + ) { + if (!scope) { + return [undefined, undefined]; } - var oldOnPopState = global.onpopstate; - global.onpopstate = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var to = global.location.href; - // keep track of the current URL state, as we always receive only the updated state - var from = lastHref; - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - if (oldOnPopState) { - // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. - // https://github.com/getsentry/sentry-javascript/issues/3344 - // https://github.com/bugsnag/bugsnag-js/issues/469 - try { - return oldOnPopState.apply(this, args); - } - catch (_oO) { - // no-empty - } - } + + // eslint-disable-next-line deprecation/deprecation + const span = scope.getSpan(); + if (span) { + const samplingContext = getRootSpan.getRootSpan(span) ? dynamicSamplingContext.getDynamicSamplingContextFromSpan(span) : undefined; + return [samplingContext, spanUtils.spanToTraceContext(span)]; + } + + const { traceId, spanId, parentSpanId, dsc } = scope.getPropagationContext(); + const traceContext = { + trace_id: traceId, + span_id: spanId, + parent_span_id: parentSpanId, }; - /** @hidden */ - function historyReplacementFunction(originalHistoryFunction) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var url = args.length > 2 ? args[2] : undefined; - if (url) { - // coerce to string (this is what pushState does) - var from = lastHref; - var to = String(url); - // keep track of the current URL state, as we always receive only the updated state - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - } - return originalHistoryFunction.apply(this, args); - }; - } - object_1.fill(global.history, 'pushState', historyReplacementFunction); - object_1.fill(global.history, 'replaceState', historyReplacementFunction); -} -var debounceDuration = 1000; -var debounceTimerID; -var lastCapturedEvent; -/** - * Decide whether the current event should finish the debounce of previously captured one. - * @param previous previously captured event - * @param current event to be captured - */ -function shouldShortcircuitPreviousDebounce(previous, current) { - // If there was no previous event, it should always be swapped for the new one. - if (!previous) { - return true; - } - // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. - if (previous.type !== current.type) { - return true; - } - try { - // If both events have the same type, it's still possible that actions were performed on different targets. - // e.g. 2 clicks on different buttons. - if (previous.target !== current.target) { - return true; - } - } - catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ - // to which an event listener was attached), we treat them as the same action, as we want to capture - // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. - return false; -} -/** - * Decide whether an event should be captured. - * @param event event to be captured - */ -function shouldSkipDOMEvent(event) { - // We are only interested in filtering `keypress` events for now. - if (event.type !== 'keypress') { - return false; - } - try { - var target = event.target; - if (!target || !target.tagName) { - return true; - } - // Only consider keypress events on actual input elements. This will disregard keypresses targeting body - // e.g.tabbing through elements, hotkeys, etc. - if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { - return false; - } + if (dsc) { + return [dsc, traceContext]; } - catch (e) { - // just accessing `target` property can throw an exception in some rare circumstances - // see: https://github.com/getsentry/sentry-javascript/issues/838 - } - return true; -} -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param handler function that will be triggered - * @param globalListener indicates whether event was captured by the global event listener - * @returns wrapped breadcrumb events handler - * @hidden - */ -function makeDOMEventHandler(handler, globalListener) { - if (globalListener === void 0) { globalListener = false; } - return function (event) { - // It's possible this handler might trigger multiple times for the same - // event (e.g. event propagation through node ancestors). - // Ignore if we've already captured that event. - if (!event || lastCapturedEvent === event) { - return; - } - // We always want to skip _some_ events. - if (shouldSkipDOMEvent(event)) { - return; - } - var name = event.type === 'keypress' ? 'input' : event.type; - // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons. - if (debounceTimerID === undefined) { - handler({ - event: event, - name: name, - global: globalListener, - }); - lastCapturedEvent = event; - } - // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one. - // If that's the case, emit the previous event and store locally the newly-captured DOM event. - else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) { - handler({ - event: event, - name: name, - global: globalListener, - }); - lastCapturedEvent = event; - } - // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. - clearTimeout(debounceTimerID); - debounceTimerID = global.setTimeout(function () { - debounceTimerID = undefined; - }, debounceDuration); - }; -} -/** JSDoc */ -function instrumentDOM() { - if (!('document' in global)) { - return; - } - // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom - // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before - // we instrument `addEventListener` so that we don't end up attaching this handler twice. - var triggerDOMHandler = triggerHandlers.bind(null, 'dom'); - var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); - global.document.addEventListener('click', globalDOMEventHandler, false); - global.document.addEventListener('keypress', globalDOMEventHandler, false); - // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled - // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That - // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler - // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still - // guaranteed to fire at least once.) - ['EventTarget', 'Node'].forEach(function (target) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var proto = global[target] && global[target].prototype; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - object_1.fill(proto, 'addEventListener', function (originalAddEventListener) { - return function (type, listener, options) { - if (type === 'click' || type == 'keypress') { - try { - var el = this; - var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); - var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 }); - if (!handlerForType.handler) { - var handler = makeDOMEventHandler(triggerDOMHandler); - handlerForType.handler = handler; - originalAddEventListener.call(this, type, handler, options); - } - handlerForType.refCount += 1; - } - catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - return originalAddEventListener.call(this, type, listener, options); - }; - }); - object_1.fill(proto, 'removeEventListener', function (originalRemoveEventListener) { - return function (type, listener, options) { - if (type === 'click' || type == 'keypress') { - try { - var el = this; - var handlers_2 = el.__sentry_instrumentation_handlers__ || {}; - var handlerForType = handlers_2[type]; - if (handlerForType) { - handlerForType.refCount -= 1; - // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. - if (handlerForType.refCount <= 0) { - originalRemoveEventListener.call(this, type, handlerForType.handler, options); - handlerForType.handler = undefined; - delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete - } - // If there are no longer any custom handlers of any type on this element, cleanup everything. - if (Object.keys(handlers_2).length === 0) { - delete el.__sentry_instrumentation_handlers__; - } - } - } - catch (e) { - // Accessing dom properties is always fragile. - // Also allows us to skip `addEventListenrs` calls with no proper `this` context. - } - } - return originalRemoveEventListener.call(this, type, listener, options); - }; - }); - }); -} -var _oldOnErrorHandler = null; -/** JSDoc */ -function instrumentError() { - _oldOnErrorHandler = global.onerror; - global.onerror = function (msg, url, line, column, error) { - triggerHandlers('error', { - column: column, - error: error, - line: line, - msg: msg, - url: url, - }); - if (_oldOnErrorHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnErrorHandler.apply(this, arguments); - } - return false; - }; -} -var _oldOnUnhandledRejectionHandler = null; -/** JSDoc */ -function instrumentUnhandledRejection() { - _oldOnUnhandledRejectionHandler = global.onunhandledrejection; - global.onunhandledrejection = function (e) { - triggerHandlers('unhandledrejection', e); - if (_oldOnUnhandledRejectionHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnUnhandledRejectionHandler.apply(this, arguments); - } - return true; - }; + + return [dynamicSamplingContext.getDynamicSamplingContextFromClient(traceId, this, scope), traceContext]; + } } -//# sourceMappingURL=instrument.js.map + +exports.ServerRuntimeClient = ServerRuntimeClient; +//# sourceMappingURL=server-runtime-client.js.map + /***/ }), -/***/ 92757: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8114: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ Object.defineProperty(exports, "__esModule", ({ value: true })); -// eslint-disable-next-line @typescript-eslint/unbound-method -var objectToString = Object.prototype.toString; + +const utils = __nccwpck_require__(25304); + /** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. + * Creates a new `Session` object by setting certain default parameters. If optional @param context + * is passed, the passed properties are applied to the session object. * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (objectToString.call(wat)) { - case '[object Error]': - case '[object Exception]': - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -exports.isError = isError; -function isBuiltin(wat, ty) { - return objectToString.call(wat) === "[object " + ty + "]"; -} -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. + * @param context (optional) additional properties to be applied to the returned session object * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @returns a new `Session` object */ -function isErrorEvent(wat) { - return isBuiltin(wat, 'ErrorEvent'); +function makeSession(context) { + // Both timestamp and started are in seconds since the UNIX epoch. + const startingTime = utils.timestampInSeconds(); + + const session = { + sid: utils.uuid4(), + init: true, + timestamp: startingTime, + started: startingTime, + duration: 0, + status: 'ok', + errors: 0, + ignoreDuration: false, + toJSON: () => sessionToJSON(session), + }; + + if (context) { + updateSession(session, context); + } + + return session; } -exports.isErrorEvent = isErrorEvent; + /** - * Checks whether given value's type is DOMError - * {@link isDOMError}. + * Updates a session object with the properties passed in the context. * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return isBuiltin(wat, 'DOMError'); -} -exports.isDOMError = isDOMError; -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. + * Note that this function mutates the passed object and returns void. + * (Had to do this instead of returning a new and updated session because closing and sending a session + * makes an update to the session after it was passed to the sending logic. + * @see BaseClient.captureSession ) * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @param session the `Session` to update + * @param context the `SessionContext` holding the properties that should be updated in @param session */ -function isDOMException(wat) { - return isBuiltin(wat, 'DOMException'); +// eslint-disable-next-line complexity +function updateSession(session, context = {}) { + if (context.user) { + if (!session.ipAddress && context.user.ip_address) { + session.ipAddress = context.user.ip_address; + } + + if (!session.did && !context.did) { + session.did = context.user.id || context.user.email || context.user.username; + } + } + + session.timestamp = context.timestamp || utils.timestampInSeconds(); + + if (context.abnormal_mechanism) { + session.abnormal_mechanism = context.abnormal_mechanism; + } + + if (context.ignoreDuration) { + session.ignoreDuration = context.ignoreDuration; + } + if (context.sid) { + // Good enough uuid validation. — Kamil + session.sid = context.sid.length === 32 ? context.sid : utils.uuid4(); + } + if (context.init !== undefined) { + session.init = context.init; + } + if (!session.did && context.did) { + session.did = `${context.did}`; + } + if (typeof context.started === 'number') { + session.started = context.started; + } + if (session.ignoreDuration) { + session.duration = undefined; + } else if (typeof context.duration === 'number') { + session.duration = context.duration; + } else { + const duration = session.timestamp - session.started; + session.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + session.release = context.release; + } + if (context.environment) { + session.environment = context.environment; + } + if (!session.ipAddress && context.ipAddress) { + session.ipAddress = context.ipAddress; + } + if (!session.userAgent && context.userAgent) { + session.userAgent = context.userAgent; + } + if (typeof context.errors === 'number') { + session.errors = context.errors; + } + if (context.status) { + session.status = context.status; + } } -exports.isDOMException = isDOMException; + /** - * Checks whether given value's type is a string - * {@link isString}. + * Closes a session by setting its status and updating the session object with it. + * Internally calls `updateSession` to update the passed session object. * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return isBuiltin(wat, 'String'); -} -exports.isString = isString; -/** - * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. + * Note that this function mutates the passed session (@see updateSession for explanation). * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @param session the `Session` object to be closed + * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, + * this function will keep the previously set status, unless it was `'ok'` in which case + * it is changed to `'exited'`. */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +function closeSession(session, status) { + let context = {}; + if (status) { + context = { status }; + } else if (session.status === 'ok') { + context = { status: 'exited' }; + } + + updateSession(session, context); } -exports.isPrimitive = isPrimitive; + /** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. + * Serializes a passed session object to a JSON object with a slightly different structure. + * This is necessary because the Sentry backend requires a slightly different schema of a session + * than the one the JS SDKs use internally. * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return isBuiltin(wat, 'Object'); -} -exports.isPlainObject = isPlainObject; -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. + * @param session the session to be converted * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @returns a JSON object of the passed session */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); +function sessionToJSON(session) { + return utils.dropUndefinedKeys({ + sid: `${session.sid}`, + init: session.init, + // Make sure that sec is converted to ms for date constructor + started: new Date(session.started * 1000).toISOString(), + timestamp: new Date(session.timestamp * 1000).toISOString(), + status: session.status, + errors: session.errors, + did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, + duration: session.duration, + abnormal_mechanism: session.abnormal_mechanism, + attrs: { + release: session.release, + environment: session.environment, + ip_address: session.ipAddress, + user_agent: session.userAgent, + }, + }); } -exports.isEvent = isEvent; + +exports.closeSession = closeSession; +exports.makeSession = makeSession; +exports.updateSession = updateSession; +//# sourceMappingURL=session.js.map + + +/***/ }), + +/***/ 27749: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const exports$1 = __nccwpck_require__(61117); + /** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @inheritdoc */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +class SessionFlusher { + + // Cast to any so that it can use Node.js timeout + // eslint-disable-next-line @typescript-eslint/no-explicit-any + + constructor(client, attrs) { + this._client = client; + this.flushTimeout = 60; + this._pendingAggregates = {}; + this._isEnabled = true; + + // Call to setInterval, so that flush is called every 60 seconds. + this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (this._intervalId.unref) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this._intervalId.unref(); + } + this._sessionAttrs = attrs; + } + + /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ + flush() { + const sessionAggregates = this.getSessionAggregates(); + if (sessionAggregates.aggregates.length === 0) { + return; + } + this._pendingAggregates = {}; + this._client.sendSession(sessionAggregates); + } + + /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ + getSessionAggregates() { + const aggregates = Object.keys(this._pendingAggregates).map((key) => { + return this._pendingAggregates[parseInt(key)]; + }); + + const sessionAggregates = { + attrs: this._sessionAttrs, + aggregates, + }; + return utils.dropUndefinedKeys(sessionAggregates); + } + + /** JSDoc */ + close() { + clearInterval(this._intervalId); + this._isEnabled = false; + this.flush(); + } + + /** + * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then + * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to + * `_incrementSessionStatusCount` along with the start date + */ + incrementSessionStatusCount() { + if (!this._isEnabled) { + return; + } + const scope = exports$1.getCurrentScope(); + const requestSession = scope.getRequestSession(); + + if (requestSession && requestSession.status) { + this._incrementSessionStatusCount(requestSession.status, new Date()); + // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in + // case captureRequestSession is called more than once to prevent double count + scope.setRequestSession(undefined); + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + } + } + + /** + * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of + * the session received + */ + _incrementSessionStatusCount(status, date) { + // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys + const sessionStartedTrunc = new Date(date).setSeconds(0, 0); + this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + + // corresponds to aggregated sessions in one specific minute bucket + // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} + const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; + if (!aggregationCounts.started) { + aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); + } + + switch (status) { + case 'errored': + aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; + return aggregationCounts.errored; + case 'ok': + aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; + return aggregationCounts.exited; + default: + aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; + return aggregationCounts.crashed; + } + } } -exports.isElement = isElement; + +exports.SessionFlusher = SessionFlusher; +//# sourceMappingURL=sessionflusher.js.map + + +/***/ }), + +/***/ 67704: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); + /** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Create envelope from Span item. */ -function isRegExp(wat) { - return isBuiltin(wat, 'RegExp'); +function createSpanEnvelope(spans, dsn) { + const headers = { + sent_at: new Date().toISOString(), + }; + + if (dsn) { + headers.dsn = utils.dsnToString(dsn); + } + + const items = spans.map(createSpanItem); + return utils.createEnvelope(headers, items); } -exports.isRegExp = isRegExp; -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); + +function createSpanItem(span) { + const spanHeaders = { + type: 'span', + }; + return [spanHeaders, span]; } -exports.isThenable = isThenable; + +exports.createSpanEnvelope = createSpanEnvelope; +//# sourceMappingURL=span.js.map + + +/***/ }), + +/***/ 65372: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const constants = __nccwpck_require__(647); +const exports$1 = __nccwpck_require__(61117); +const getRootSpan = __nccwpck_require__(55660); +const spanUtils = __nccwpck_require__(19925); + /** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. + * Creates a dynamic sampling context from a client. * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Dispatches the `createDsc` lifecycle hook as a side effect. */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +function getDynamicSamplingContextFromClient( + trace_id, + client, + scope, +) { + const options = client.getOptions(); + + const { publicKey: public_key } = client.getDsn() || {}; + // TODO(v8): Remove segment from User + // eslint-disable-next-line deprecation/deprecation + const { segment: user_segment } = (scope && scope.getUser()) || {}; + + const dsc = utils.dropUndefinedKeys({ + environment: options.environment || constants.DEFAULT_ENVIRONMENT, + release: options.release, + user_segment, + public_key, + trace_id, + }) ; + + client.emit && client.emit('createDsc', dsc); + + return dsc; } -exports.isSyntheticEvent = isSyntheticEvent; + /** - * Checks whether given value is NaN - * {@link isNaN}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * A Span with a frozen dynamic sampling context. */ -function isNaN(wat) { - return typeof wat === 'number' && wat !== wat; -} -exports.isNaN = isNaN; + /** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. + * Creates a dynamic sampling context from a span (and client and scope) * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. + * @param span the span from which a few values like the root span name and sample rate are extracted. + * + * @returns a dynamic sampling context */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } - catch (_e) { - return false; - } +function getDynamicSamplingContextFromSpan(span) { + const client = exports$1.getClient(); + if (!client) { + return {}; + } + + // passing emit=false here to only emit later once the DSC is actually populated + const dsc = getDynamicSamplingContextFromClient(spanUtils.spanToJSON(span).trace_id || '', client, exports$1.getCurrentScope()); + + // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext + const txn = getRootSpan.getRootSpan(span) ; + if (!txn) { + return dsc; + } + + // TODO (v8): Remove v7FrozenDsc as a Transaction will no longer have _frozenDynamicSamplingContext + // For now we need to avoid breaking users who directly created a txn with a DSC, where this field is still set. + // @see Transaction class constructor + const v7FrozenDsc = txn && txn._frozenDynamicSamplingContext; + if (v7FrozenDsc) { + return v7FrozenDsc; + } + + // TODO (v8): Replace txn.metadata with txn.attributes[] + // We can't do this yet because attributes aren't always set yet. + // eslint-disable-next-line deprecation/deprecation + const { sampleRate: maybeSampleRate, source } = txn.metadata; + if (maybeSampleRate != null) { + dsc.sample_rate = `${maybeSampleRate}`; + } + + // We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII + const jsonSpan = spanUtils.spanToJSON(txn); + + // after JSON conversion, txn.name becomes jsonSpan.description + if (source && source !== 'url') { + dsc.transaction = jsonSpan.description; + } + + dsc.sampled = String(spanUtils.spanIsSampled(txn)); + + client.emit && client.emit('createDsc', dsc); + + return dsc; } -exports.isInstanceOf = isInstanceOf; -//# sourceMappingURL=is.js.map + +exports.getDynamicSamplingContextFromClient = getDynamicSamplingContextFromClient; +exports.getDynamicSamplingContextFromSpan = getDynamicSamplingContextFromSpan; +//# sourceMappingURL=dynamicSamplingContext.js.map + /***/ }), -/***/ 15577: +/***/ 64332: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var env_1 = __nccwpck_require__(31913); -var global_1 = __nccwpck_require__(68813); -// TODO: Implement different loggers for different environments -var global = global_1.getGlobalObject(); -/** Prefix for logging strings */ -var PREFIX = 'Sentry Logger '; -exports.CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert']; + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const utils$1 = __nccwpck_require__(29406); + +let errorsInstrumented = false; + /** - * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods. - * Restores wrapping after the callback completes. - * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback + * Configures global error listeners */ -function consoleSandbox(callback) { - var global = global_1.getGlobalObject(); - if (!('console' in global)) { - return callback(); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var originalConsole = global.console; - var wrappedLevels = {}; - // Restore all wrapped console methods - exports.CONSOLE_LEVELS.forEach(function (level) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (level in global.console && originalConsole[level].__sentry_original__) { - wrappedLevels[level] = originalConsole[level]; - originalConsole[level] = originalConsole[level].__sentry_original__; - } - }); - // Perform callback manipulations - var result = callback(); - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(function (level) { - originalConsole[level] = wrappedLevels[level]; - }); - return result; -} -exports.consoleSandbox = consoleSandbox; -/** JSDoc */ -var Logger = /** @class */ (function () { - /** JSDoc */ - function Logger() { - this._enabled = false; - } - /** JSDoc */ - Logger.prototype.disable = function () { - this._enabled = false; - }; - /** JSDoc */ - Logger.prototype.enable = function () { - this._enabled = true; - }; - /** JSDoc */ - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - consoleSandbox(function () { - var _a; - (_a = global.console).log.apply(_a, tslib_1.__spread([PREFIX + "[Log]:"], args)); - }); - }; - /** JSDoc */ - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - consoleSandbox(function () { - var _a; - (_a = global.console).warn.apply(_a, tslib_1.__spread([PREFIX + "[Warn]:"], args)); - }); - }; - /** JSDoc */ - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - consoleSandbox(function () { - var _a; - (_a = global.console).error.apply(_a, tslib_1.__spread([PREFIX + "[Error]:"], args)); - }); - }; - return Logger; -}()); -var sentryGlobal = global.__SENTRY__ || {}; -var logger = sentryGlobal.logger || new Logger(); -exports.logger = logger; -if (env_1.isDebugBuild()) { - // Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used - sentryGlobal.logger = logger; - global.__SENTRY__ = sentryGlobal; -} -//# sourceMappingURL=logger.js.map - -/***/ }), +function registerErrorInstrumentation() { + if (errorsInstrumented) { + return; + } -/***/ 49515: -/***/ ((__unused_webpack_module, exports) => { + errorsInstrumented = true; + utils.addGlobalErrorInstrumentationHandler(errorCallback); + utils.addGlobalUnhandledRejectionInstrumentationHandler(errorCallback); +} -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Helper to decycle json objects + * If an error or unhandled promise occurs, we mark the active transaction as failed */ -function memoBuilder() { - var hasWeakSet = typeof WeakSet === 'function'; - var inner = hasWeakSet ? new WeakSet() : []; - function memoize(obj) { - if (hasWeakSet) { - if (inner.has(obj)) { - return true; - } - inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < inner.length; i++) { - var value = inner[i]; - if (value === obj) { - return true; - } - } - inner.push(obj); - return false; - } - function unmemoize(obj) { - if (hasWeakSet) { - inner.delete(obj); - } - else { - for (var i = 0; i < inner.length; i++) { - if (inner[i] === obj) { - inner.splice(i, 1); - break; - } - } - } - } - return [memoize, unmemoize]; +function errorCallback() { + // eslint-disable-next-line deprecation/deprecation + const activeTransaction = utils$1.getActiveTransaction(); + if (activeTransaction) { + const status = 'internal_error'; + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); + activeTransaction.setStatus(status); + } } -exports.memoBuilder = memoBuilder; -//# sourceMappingURL=memo.js.map + +// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the +// node.js default exit behaviour +errorCallback.tag = 'sentry_tracingErrorCallback'; + +exports.registerErrorInstrumentation = registerErrorInstrumentation; +//# sourceMappingURL=errors.js.map + /***/ }), -/***/ 32154: +/***/ 69866: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var global_1 = __nccwpck_require__(68813); -var object_1 = __nccwpck_require__(69249); -var string_1 = __nccwpck_require__(66538); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const hub = __nccwpck_require__(5553); +const spanUtils = __nccwpck_require__(19925); +const errors = __nccwpck_require__(64332); +const idletransaction = __nccwpck_require__(58753); +const sampling = __nccwpck_require__(45606); +const transaction = __nccwpck_require__(85111); + +/** Returns all trace headers that are currently on the top scope. */ +// eslint-disable-next-line deprecation/deprecation +function traceHeaders() { + // eslint-disable-next-line deprecation/deprecation + const scope = this.getScope(); + // eslint-disable-next-line deprecation/deprecation + const span = scope.getSpan(); + + return span + ? { + 'sentry-trace': spanUtils.spanToTraceHeader(span), + } + : {}; +} + /** - * UUID4 generator + * Creates a new transaction and adds a sampling decision if it doesn't yet have one. * - * @returns string Generated UUID4. + * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if + * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an + * "extension method." + * + * @param this: The Hub starting the transaction + * @param transactionContext: Data used to configure the transaction + * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) + * + * @returns The new transaction + * + * @see {@link Hub.startTransaction} */ -function uuid4() { - var global = global_1.getGlobalObject(); - var crypto = global.crypto || global.msCrypto; - if (!(crypto === void 0) && crypto.getRandomValues) { - // Use window.crypto API if available - var arr = new Uint16Array(8); - crypto.getRandomValues(arr); - // set 4 in byte 7 - // eslint-disable-next-line no-bitwise - arr[3] = (arr[3] & 0xfff) | 0x4000; - // set 2 most significant bits of byte 9 to '10' - // eslint-disable-next-line no-bitwise - arr[4] = (arr[4] & 0x3fff) | 0x8000; - var pad = function (num) { - var v = num.toString(16); - while (v.length < 4) { - v = "0" + v; - } - return v; - }; - return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); - } - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - // eslint-disable-next-line no-bitwise - var r = (Math.random() * 16) | 0; - // eslint-disable-next-line no-bitwise - var v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); +function _startTransaction( + // eslint-disable-next-line deprecation/deprecation + + transactionContext, + customSamplingContext, +) { + // eslint-disable-next-line deprecation/deprecation + const client = this.getClient(); + const options = (client && client.getOptions()) || {}; + + const configInstrumenter = options.instrumenter || 'sentry'; + const transactionInstrumenter = transactionContext.instrumenter || 'sentry'; + + if (configInstrumenter !== transactionInstrumenter) { + debugBuild.DEBUG_BUILD && + utils.logger.error( + `A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter. +The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`, + ); + + // eslint-disable-next-line deprecation/deprecation + transactionContext.sampled = false; + } + + // eslint-disable-next-line deprecation/deprecation + let transaction$1 = new transaction.Transaction(transactionContext, this); + transaction$1 = sampling.sampleTransaction(transaction$1, options, { + name: transactionContext.name, + parentSampled: transactionContext.parentSampled, + transactionContext, + attributes: { + // eslint-disable-next-line deprecation/deprecation + ...transactionContext.data, + ...transactionContext.attributes, + }, + ...customSamplingContext, + }); + if (transaction$1.isRecording()) { + transaction$1.initSpanRecorder(options._experiments && (options._experiments.maxSpans )); + } + if (client && client.emit) { + client.emit('startTransaction', transaction$1); + } + return transaction$1; } -exports.uuid4 = uuid4; + /** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object + * Create new idle transaction. */ -function parseUrl(url) { - if (!url) { - return {}; - } - var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (!match) { - return {}; - } - // coerce to undefined values to empty string so we don't get 'undefined' - var query = match[6] || ''; - var fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, - }; -} -exports.parseUrl = parseUrl; -function getFirstException(event) { - return event.exception && event.exception.values ? event.exception.values[0] : undefined; +function startIdleTransaction( + // eslint-disable-next-line deprecation/deprecation + hub, + transactionContext, + idleTimeout, + finalTimeout, + onScope, + customSamplingContext, + heartbeatInterval, + delayAutoFinishUntilSignal = false, +) { + // eslint-disable-next-line deprecation/deprecation + const client = hub.getClient(); + const options = (client && client.getOptions()) || {}; + + // eslint-disable-next-line deprecation/deprecation + let transaction = new idletransaction.IdleTransaction( + transactionContext, + hub, + idleTimeout, + finalTimeout, + heartbeatInterval, + onScope, + delayAutoFinishUntilSignal, + ); + transaction = sampling.sampleTransaction(transaction, options, { + name: transactionContext.name, + parentSampled: transactionContext.parentSampled, + transactionContext, + attributes: { + // eslint-disable-next-line deprecation/deprecation + ...transactionContext.data, + ...transactionContext.attributes, + }, + ...customSamplingContext, + }); + if (transaction.isRecording()) { + transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans )); + } + if (client && client.emit) { + client.emit('startTransaction', transaction); + } + return transaction; } + /** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description + * Adds tracing extensions to the global hub. */ -function getEventDescription(event) { - var message = event.message, eventId = event.event_id; - if (message) { - return message; - } - var firstException = getFirstException(event); - if (firstException) { - if (firstException.type && firstException.value) { - return firstException.type + ": " + firstException.value; - } - return firstException.type || firstException.value || eventId || ''; - } - return eventId || ''; +function addTracingExtensions() { + const carrier = hub.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; + } + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + if (!carrier.__SENTRY__.extensions.startTransaction) { + carrier.__SENTRY__.extensions.startTransaction = _startTransaction; + } + if (!carrier.__SENTRY__.extensions.traceHeaders) { + carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; + } + + errors.registerErrorInstrumentation(); } -exports.getEventDescription = getEventDescription; + +exports.addTracingExtensions = addTracingExtensions; +exports.startIdleTransaction = startIdleTransaction; +//# sourceMappingURL=hubextensions.js.map + + +/***/ }), + +/***/ 58753: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const spanUtils = __nccwpck_require__(19925); +const span = __nccwpck_require__(41223); +const transaction = __nccwpck_require__(85111); + +const TRACING_DEFAULTS = { + idleTimeout: 1000, + finalTimeout: 30000, + heartbeatInterval: 5000, +}; + +const FINISH_REASON_TAG = 'finishReason'; + +const IDLE_TRANSACTION_FINISH_REASONS = [ + 'heartbeatFailed', + 'idleTimeout', + 'documentHidden', + 'finalTimeout', + 'externalFinish', + 'cancelled', +]; + /** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden + * @inheritDoc */ -function addExceptionTypeValue(event, value, type) { - var exception = (event.exception = event.exception || {}); - var values = (exception.values = exception.values || []); - var firstException = (values[0] = values[0] || {}); - if (!firstException.value) { - firstException.value = value || ''; - } - if (!firstException.type) { - firstException.type = type || 'Error'; +class IdleTransactionSpanRecorder extends span.SpanRecorder { + constructor( + _pushActivity, + _popActivity, + transactionSpanId, + maxlen, + ) { + super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; } + + /** + * @inheritDoc + */ + add(span) { + // We should make sure we do not push and pop activities for + // the transaction that this span recorder belongs to. + if (span.spanContext().spanId !== this.transactionSpanId) { + // We patch span.end() to pop an activity after setting an endTimestamp. + // eslint-disable-next-line @typescript-eslint/unbound-method + const originalEnd = span.end; + span.end = (...rest) => { + this._popActivity(span.spanContext().spanId); + return originalEnd.apply(span, rest); + }; + + // We should only push new activities if the span does not have an end timestamp. + if (spanUtils.spanToJSON(span).timestamp === undefined) { + this._pushActivity(span.spanContext().spanId); + } } + + super.add(span); + } } -exports.addExceptionTypeValue = addExceptionTypeValue; + /** - * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden + * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. + * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will + * put itself on the scope on creation. */ -function addExceptionMechanism(event, newMechanism) { - var firstException = getFirstException(event); - if (!firstException) { - return; +class IdleTransaction extends transaction.Transaction { + // Activities store a list of active spans + + // Track state of activities in previous heartbeat + + // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. + + // We should not use heartbeat if we finished a transaction + + // Idle timeout was canceled and we should finish the transaction with the last span end. + + /** + * Timer that tracks Transaction idleTimeout + */ + + /** + * @deprecated Transactions will be removed in v8. Use spans instead. + */ + constructor( + transactionContext, + // eslint-disable-next-line deprecation/deprecation + _idleHub, + /** + * The time to wait in ms until the idle transaction will be finished. This timer is started each time + * there are no active spans on this transaction. + */ + _idleTimeout = TRACING_DEFAULTS.idleTimeout, + /** + * The final value in ms that a transaction cannot exceed + */ + _finalTimeout = TRACING_DEFAULTS.finalTimeout, + _heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval, + // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends + _onScope = false, + /** + * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval` + * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option) + * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is + * reached, no matter what this option is configured to. + * + * Defaults to `false`. + */ + delayAutoFinishUntilSignal = false, + ) { + super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope; + this.activities = {}; + this._heartbeatCounter = 0; + this._finished = false; + this._idleTimeoutCanceledPermanently = false; + this._beforeFinishCallbacks = []; + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4]; + this._autoFinishAllowed = !delayAutoFinishUntilSignal; + + if (_onScope) { + // We set the transaction here on the scope so error events pick up the trace + // context and attach it to the error. + debugBuild.DEBUG_BUILD && utils.logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`); + // eslint-disable-next-line deprecation/deprecation + _idleHub.getScope().setSpan(this); } - var defaultMechanism = { type: 'generic', handled: true }; - var currentMechanism = firstException.mechanism; - firstException.mechanism = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, defaultMechanism), currentMechanism), newMechanism); - if (newMechanism && 'data' in newMechanism) { - var mergedData = tslib_1.__assign(tslib_1.__assign({}, (currentMechanism && currentMechanism.data)), newMechanism.data); - firstException.mechanism.data = mergedData; + + if (!delayAutoFinishUntilSignal) { + this._restartIdleTimeout(); } -} -exports.addExceptionMechanism = addExceptionMechanism; -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - var match = input.match(SEMVER_REGEXP) || []; - var major = parseInt(match[1], 10); - var minor = parseInt(match[2], 10); - var patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} -exports.parseSemver = parseSemver; -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext) { - if (linesOfContext === void 0) { linesOfContext = 5; } - var lineno = frame.lineno || 0; - var maxLines = lines.length; - var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map(function (line) { return string_1.snipLine(line, 0); }); - frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map(function (line) { return string_1.snipLine(line, 0); }); -} -exports.addContextToFrame = addContextToFrame; -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} -exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (exception && exception.__sentry_captured__) { - return true; + + setTimeout(() => { + if (!this._finished) { + this.setStatus('deadline_exceeded'); + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3]; + this.end(); + } + }, this._finalTimeout); + } + + /** {@inheritDoc} */ + end(endTimestamp) { + const endTimestampInS = spanUtils.spanTimeInputToSeconds(endTimestamp); + + this._finished = true; + this.activities = {}; + + // eslint-disable-next-line deprecation/deprecation + if (this.op === 'ui.action.click') { + this.setAttribute(FINISH_REASON_TAG, this._finishReason); } - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - object_1.addNonEnumerableProperty(exception, '__sentry_captured__', true); + + // eslint-disable-next-line deprecation/deprecation + if (this.spanRecorder) { + debugBuild.DEBUG_BUILD && + // eslint-disable-next-line deprecation/deprecation + utils.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op); + + for (const callback of this._beforeFinishCallbacks) { + callback(this, endTimestampInS); + } + + // eslint-disable-next-line deprecation/deprecation + this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => { + // If we are dealing with the transaction itself, we just return it + if (span.spanContext().spanId === this.spanContext().spanId) { + return true; + } + + // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early + if (!spanUtils.spanToJSON(span).timestamp) { + span.setStatus('cancelled'); + span.end(endTimestampInS); + debugBuild.DEBUG_BUILD && + utils.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); + } + + const { start_timestamp: startTime, timestamp: endTime } = spanUtils.spanToJSON(span); + const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS; + + // Add a delta with idle timeout so that we prevent false positives + const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000; + const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError; + + if (debugBuild.DEBUG_BUILD) { + const stringifiedSpan = JSON.stringify(span, undefined, 2); + if (!spanStartedBeforeTransactionFinish) { + utils.logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan); + } else if (!spanEndedBeforeFinalTimeout) { + utils.logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan); + } + } + + return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout; + }); + + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] flushing IdleTransaction'); + } else { + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] No active IdleTransaction'); } - catch (err) { - // `exception` is a primitive, so we can't mark it seen + + // if `this._onScope` is `true`, the transaction put itself on the scope when it started + if (this._onScope) { + // eslint-disable-next-line deprecation/deprecation + const scope = this._idleHub.getScope(); + // eslint-disable-next-line deprecation/deprecation + if (scope.getTransaction() === this) { + // eslint-disable-next-line deprecation/deprecation + scope.setSpan(undefined); + } } - return false; -} -exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught; -//# sourceMappingURL=misc.js.map -/***/ }), + return super.end(endTimestamp); + } -/***/ 16411: -/***/ ((module, exports, __nccwpck_require__) => { + /** + * Register a callback function that gets executed before the transaction finishes. + * Useful for cleanup or if you want to add any additional spans based on current context. + * + * This is exposed because users have no other way of running something before an idle transaction + * finishes. + */ + registerBeforeFinishCallback(callback) { + this._beforeFinishCallbacks.push(callback); + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var env_1 = __nccwpck_require__(31913); -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - // explicitly check for browser bundles as those can be optimized statically - // by terser/rollup. - return (!env_1.isBrowserBundle() && - Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'); -} -exports.isNodeEnv = isNodeEnv; -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} -exports.dynamicRequire = dynamicRequire; -/** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. - * - * @param moduleName module name to require - * @returns possibly required module - */ -function loadModule(moduleName) { - var mod; - try { - mod = dynamicRequire(module, moduleName); + /** + * @inheritDoc + */ + initSpanRecorder(maxlen) { + // eslint-disable-next-line deprecation/deprecation + if (!this.spanRecorder) { + const pushActivity = (id) => { + if (this._finished) { + return; + } + this._pushActivity(id); + }; + const popActivity = (id) => { + if (this._finished) { + return; + } + this._popActivity(id); + }; + + // eslint-disable-next-line deprecation/deprecation + this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen); + + // Start heartbeat so that transactions do not run forever. + debugBuild.DEBUG_BUILD && utils.logger.log('Starting heartbeat'); + this._pingHeartbeat(); } - catch (e) { - // no-empty + // eslint-disable-next-line deprecation/deprecation + this.spanRecorder.add(this); + } + + /** + * Cancels the existing idle timeout, if there is one. + * @param restartOnChildSpanChange Default is `true`. + * If set to false the transaction will end + * with the last child span. + */ + cancelIdleTimeout( + endTimestamp, + { + restartOnChildSpanChange, } - try { - var cwd = dynamicRequire(module, 'process').cwd; - mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName); + + = { + restartOnChildSpanChange: true, + }, + ) { + this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false; + if (this._idleTimeoutID) { + clearTimeout(this._idleTimeoutID); + this._idleTimeoutID = undefined; + + if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) { + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5]; + this.end(endTimestamp); + } } - catch (e) { - // no-empty + } + + /** + * Temporary method used to externally set the transaction's `finishReason` + * + * ** WARNING** + * This is for the purpose of experimentation only and will be removed in the near future, do not use! + * + * @internal + * + */ + setFinishReason(reason) { + this._finishReason = reason; + } + + /** + * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`. + */ + sendAutoFinishSignal() { + if (!this._autoFinishAllowed) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] Received finish signal for idle transaction.'); + this._restartIdleTimeout(); + this._autoFinishAllowed = true; } - return mod; -} -exports.loadModule = loadModule; -//# sourceMappingURL=node.js.map + } -/***/ }), + /** + * Restarts idle timeout, if there is no running idle timeout it will start one. + */ + _restartIdleTimeout(endTimestamp) { + this.cancelIdleTimeout(); + this._idleTimeoutID = setTimeout(() => { + if (!this._finished && Object.keys(this.activities).length === 0) { + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1]; + this.end(endTimestamp); + } + }, this._idleTimeout); + } -/***/ 28592: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Start tracking a specific activity. + * @param spanId The span id that represents the activity + */ + _pushActivity(spanId) { + this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently }); + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] pushActivity: ${spanId}`); + this.activities[spanId] = true; + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var is_1 = __nccwpck_require__(92757); -var memo_1 = __nccwpck_require__(49515); -var object_1 = __nccwpck_require__(69249); -var stacktrace_1 = __nccwpck_require__(5986); -/** - * Recursively normalizes the given object. - * - * - Creates a copy to prevent original input mutation - * - Skips non-enumerable properties - * - When stringifying, calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format - * - Translates known global objects/classes to a string representations - * - Takes care of `Error` object serialization - * - Optionally limits depth of final output - * - Optionally limits number of properties/elements included in any single object/array - * - * @param input The object to be normalized. - * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) - * @param maxProperties The max number of elements or properties to be included in any single array or - * object in the normallized output.. - * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. - */ -function normalize(input, depth, maxProperties) { - if (depth === void 0) { depth = +Infinity; } - if (maxProperties === void 0) { maxProperties = +Infinity; } - try { - // since we're at the outermost level, there is no key - return visit('', input, depth, maxProperties); - } - catch (err) { - return { ERROR: "**non-serializable** (" + err + ")" }; + /** + * Remove an activity from usage + * @param spanId The span id that represents the activity + */ + _popActivity(spanId) { + if (this.activities[spanId]) { + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] popActivity ${spanId}`); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.activities[spanId]; + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); } -} -exports.normalize = normalize; -/** JSDoc */ -function normalizeToSize(object, -// Default Node.js REPL depth -depth, -// 100kB, as 200kB is max payload size, so half sounds reasonable -maxSize) { - if (depth === void 0) { depth = 3; } - if (maxSize === void 0) { maxSize = 100 * 1024; } - var normalized = normalize(object, depth); - if (jsonSize(normalized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - return normalized; -} -exports.normalizeToSize = normalizeToSize; -/** - * Visits a node to perform normalization on it - * - * @param key The key corresponding to the given node - * @param value The node to be visited - * @param depth Optional number indicating the maximum recursion depth - * @param maxProperties Optional maximum number of properties/elements included in any single object/array - * @param memo Optional Memo class handling decycling - */ -function visit(key, value, depth, maxProperties, memo) { - if (depth === void 0) { depth = +Infinity; } - if (maxProperties === void 0) { maxProperties = +Infinity; } - if (memo === void 0) { memo = memo_1.memoBuilder(); } - var _a = tslib_1.__read(memo, 2), memoize = _a[0], unmemoize = _a[1]; - // If the value has a `toJSON` method, see if we can bail and let it do the work - var valueWithToJSON = value; - if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { - try { - return valueWithToJSON.toJSON(); - } - catch (err) { - // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) + + if (Object.keys(this.activities).length === 0) { + const endTimestamp = utils.timestampInSeconds(); + if (this._idleTimeoutCanceledPermanently) { + if (this._autoFinishAllowed) { + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5]; + this.end(endTimestamp); } + } else { + // We need to add the timeout here to have the real endtimestamp of the transaction + // Remember timestampInSeconds is in seconds, timeout is in ms + this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000); + } } - // Get the simple cases out of the way first - if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !is_1.isNaN(value))) { - return value; - } - var stringified = stringifyValue(key, value); - // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. - // Everything else will have already been serialized, so if we don't see that pattern, we're done. - if (!stringified.startsWith('[object ')) { - return stringified; - } - // We're also done if we've reached the max depth - if (depth === 0) { - // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. - return stringified.replace('object ', ''); - } - // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. - if (memoize(value)) { - return '[Circular ~]'; - } - // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse - // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each - // property/entry, and keep track of the number of items we add to it. - var normalized = (Array.isArray(value) ? [] : {}); - var numAdded = 0; - // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant - // properties are non-enumerable and otherwise would get missed. - var visitable = (is_1.isError(value) || is_1.isEvent(value) ? object_1.convertToPlainObject(value) : value); - for (var visitKey in visitable) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { - continue; - } - if (numAdded >= maxProperties) { - normalized[visitKey] = '[MaxProperties ~]'; - break; - } - // Recursively visit all the child nodes - var visitValue = visitable[visitKey]; - normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); - numAdded += 1; + } + + /** + * Checks when entries of this.activities are not changing for 3 beats. + * If this occurs we finish the transaction. + */ + _beat() { + // We should not be running heartbeat if the idle transaction is finished. + if (this._finished) { + return; } - // Once we've visited all the branches, remove the parent from memo storage - unmemoize(value); - // Return accumulated values - return normalized; -} -exports.walk = visit; -/** - * Stringify the given value. Handles various known special values and types. - * - * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn - * the number 1231 into "[Object Number]", nor on `null`, as it will throw. - * - * @param value The value to stringify - * @returns A stringified representation of the given value - */ -function stringifyValue(key, -// this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for -// our internal use, it'll do -value) { - try { - if (key === 'domain' && value && typeof value === 'object' && value._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - // eslint-disable-next-line no-restricted-globals - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - // React's SyntheticEvent thingy - if (is_1.isSyntheticEvent(value)) { - return '[SyntheticEvent]'; - } - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) - if (value === void 0) { - return '[undefined]'; - } - if (typeof value === 'function') { - return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; - } - if (typeof value === 'symbol') { - return "[" + String(value) + "]"; - } - // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion - if (typeof value === 'bigint') { - return "[BigInt: " + String(value) + "]"; - } - // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting - // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as - // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), - // we can make sure that only plain objects come out that way. - return "[object " + Object.getPrototypeOf(value).constructor.name + "]"; + + const heartbeatString = Object.keys(this.activities).join(''); + + if (heartbeatString === this._prevHeartbeatString) { + this._heartbeatCounter++; + } else { + this._heartbeatCounter = 1; } - catch (err) { - return "**non-serializable** (" + err + ")"; + + this._prevHeartbeatString = heartbeatString; + + if (this._heartbeatCounter >= 3) { + if (this._autoFinishAllowed) { + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] Transaction finished because of no change for 3 heart beats'); + this.setStatus('deadline_exceeded'); + this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0]; + this.end(); + } + } else { + this._pingHeartbeat(); } + } + + /** + * Pings the heartbeat + */ + _pingHeartbeat() { + debugBuild.DEBUG_BUILD && utils.logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`); + setTimeout(() => { + this._beat(); + }, this._heartbeatInterval); + } } -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} -/** Calculates bytes size of input object */ -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} -//# sourceMappingURL=normalize.js.map + +exports.IdleTransaction = IdleTransaction; +exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder; +exports.TRACING_DEFAULTS = TRACING_DEFAULTS; +//# sourceMappingURL=idletransaction.js.map + /***/ }), -/***/ 69249: +/***/ 94259: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var browser_1 = __nccwpck_require__(30597); -var is_1 = __nccwpck_require__(92757); -var string_1 = __nccwpck_require__(66538); -/** - * Replace a method in an object with a wrapped version of itself. - * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. - * @returns void - */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - var original = source[name]; - var wrapped = replacementFactory(original); - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - markFunctionWrapped(wrapped, original); - } - catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } - source[name] = wrapped; -} -exports.fill = fill; + +const utils = __nccwpck_require__(29406); + /** - * Defines a non-enumerable property on the given object. - * - * @param obj The object on which to set the property - * @param name The name of the property to be set - * @param value The value to which to set the property + * Adds a measurement to the current active transaction. */ -function addNonEnumerableProperty(obj, name, value) { - Object.defineProperty(obj, name, { - // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it - value: value, - writable: true, - configurable: true, - }); +function setMeasurement(name, value, unit) { + // eslint-disable-next-line deprecation/deprecation + const transaction = utils.getActiveTransaction(); + if (transaction) { + // eslint-disable-next-line deprecation/deprecation + transaction.setMeasurement(name, value, unit); + } } -exports.addNonEnumerableProperty = addNonEnumerableProperty; + +exports.setMeasurement = setMeasurement; +//# sourceMappingURL=measurement.js.map + + +/***/ }), + +/***/ 45606: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const semanticAttributes = __nccwpck_require__(52781); +const hasTracingEnabled = __nccwpck_require__(1295); +const spanUtils = __nccwpck_require__(19925); + /** - * Remembers the original function on the wrapped function and - * patches up the prototype. + * Makes a sampling decision for the given transaction and stores it on the transaction. * - * @param wrapped the wrapper function - * @param original the original function that gets wrapped - */ -function markFunctionWrapped(wrapped, original) { - var proto = original.prototype || {}; - wrapped.prototype = original.prototype = proto; - addNonEnumerableProperty(wrapped, '__sentry_original__', original); -} -exports.markFunctionWrapped = markFunctionWrapped; -/** - * This extracts the original function if available. See - * `markFunctionWrapped` for more information. + * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be + * sent to Sentry. * - * @param func the function to unwrap - * @returns the unwrapped version of the function if available. + * This method muttes the given `transaction` and will set the `sampled` value on it. + * It returns the same transaction, for convenience. */ -function getOriginalFunction(func) { - return func.__sentry_original__; +function sampleTransaction( + transaction, + options, + samplingContext, +) { + // nothing to do if tracing is not enabled + if (!hasTracingEnabled.hasTracingEnabled(options)) { + // eslint-disable-next-line deprecation/deprecation + transaction.sampled = false; + return transaction; + } + + // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that + // eslint-disable-next-line deprecation/deprecation + if (transaction.sampled !== undefined) { + // eslint-disable-next-line deprecation/deprecation + transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(transaction.sampled)); + return transaction; + } + + // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` were defined, so one of these should + // work; prefer the hook if so + let sampleRate; + if (typeof options.tracesSampler === 'function') { + sampleRate = options.tracesSampler(samplingContext); + transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate)); + } else if (samplingContext.parentSampled !== undefined) { + sampleRate = samplingContext.parentSampled; + } else if (typeof options.tracesSampleRate !== 'undefined') { + sampleRate = options.tracesSampleRate; + transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, Number(sampleRate)); + } else { + // When `enableTracing === true`, we use a sample rate of 100% + sampleRate = 1; + transaction.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, sampleRate); + } + + // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The + // only valid values are booleans or numbers between 0 and 1.) + if (!isValidSampleRate(sampleRate)) { + debugBuild.DEBUG_BUILD && utils.logger.warn('[Tracing] Discarding transaction because of invalid sample rate.'); + // eslint-disable-next-line deprecation/deprecation + transaction.sampled = false; + return transaction; + } + + // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped + if (!sampleRate) { + debugBuild.DEBUG_BUILD && + utils.logger.log( + `[Tracing] Discarding transaction because ${ + typeof options.tracesSampler === 'function' + ? 'tracesSampler returned 0 or false' + : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' + }`, + ); + // eslint-disable-next-line deprecation/deprecation + transaction.sampled = false; + return transaction; + } + + // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is + // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. + // eslint-disable-next-line deprecation/deprecation + transaction.sampled = Math.random() < (sampleRate ); + + // if we're not going to keep it, we're done + // eslint-disable-next-line deprecation/deprecation + if (!transaction.sampled) { + debugBuild.DEBUG_BUILD && + utils.logger.log( + `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( + sampleRate, + )})`, + ); + return transaction; + } + + debugBuild.DEBUG_BUILD && + // eslint-disable-next-line deprecation/deprecation + utils.logger.log(`[Tracing] starting ${transaction.op} transaction - ${spanUtils.spanToJSON(transaction).description}`); + return transaction; } -exports.getOriginalFunction = getOriginalFunction; + /** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded + * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). */ -function urlEncode(object) { - return Object.keys(object) - .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) - .join('&'); +function isValidSampleRate(rate) { + // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (utils.isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { + debugBuild.DEBUG_BUILD && + utils.logger.warn( + `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( + rate, + )} of type ${JSON.stringify(typeof rate)}.`, + ); + return false; + } + + // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false + if (rate < 0 || rate > 1) { + debugBuild.DEBUG_BUILD && + utils.logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); + return false; + } + return true; } -exports.urlEncode = urlEncode; + +exports.isValidSampleRate = isValidSampleRate; +exports.sampleTransaction = sampleTransaction; +//# sourceMappingURL=sampling.js.map + + +/***/ }), + +/***/ 41223: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const metricSummary = __nccwpck_require__(3875); +const semanticAttributes = __nccwpck_require__(52781); +const getRootSpan = __nccwpck_require__(55660); +const spanUtils = __nccwpck_require__(19925); +const spanstatus = __nccwpck_require__(13973); + /** - * Transforms any object into an object literal with all its attributes - * attached to it. - * - * @param value Initial source that we have to transform in order for it to be usable by the serializer + * Keeps track of finished spans for a given transaction + * @internal + * @hideconstructor + * @hidden */ -function convertToPlainObject(value) { - var newObj = value; - if (is_1.isError(value)) { - newObj = tslib_1.__assign({ message: value.message, name: value.name, stack: value.stack }, getOwnProperties(value)); - } - else if (is_1.isEvent(value)) { - var event_1 = value; - newObj = tslib_1.__assign({ type: event_1.type, target: serializeEventTarget(event_1.target), currentTarget: serializeEventTarget(event_1.currentTarget) }, getOwnProperties(event_1)); - if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { - newObj.detail = event_1.detail; - } - } - return newObj; -} -exports.convertToPlainObject = convertToPlainObject; -/** Creates a string representation of the target of an `Event` object */ -function serializeEventTarget(target) { - try { - return is_1.isElement(target) ? browser_1.htmlTreeAsString(target) : Object.prototype.toString.call(target); - } - catch (_oO) { - return ''; - } -} -/** Filters out all but an object's own properties */ -function getOwnProperties(obj) { - var extractedProps = {}; - for (var property in obj) { - if (Object.prototype.hasOwnProperty.call(obj, property)) { - extractedProps[property] = obj[property]; - } +class SpanRecorder { + + constructor(maxlen = 1000) { + this._maxlen = maxlen; + this.spans = []; + } + + /** + * This is just so that we don't run out of memory while recording a lot + * of spans. At some point we just stop and flush out the start of the + * trace tree (i.e.the first n spans with the smallest + * start_timestamp). + */ + add(span) { + if (this.spans.length > this._maxlen) { + // eslint-disable-next-line deprecation/deprecation + span.spanRecorder = undefined; + } else { + this.spans.push(span); } - return extractedProps; + } } + /** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` + * Span contains all data about a span */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function extractExceptionKeysForMessage(exception, maxLength) { - if (maxLength === void 0) { maxLength = 40; } - var keys = Object.keys(convertToPlainObject(exception)); - keys.sort(); - if (!keys.length) { - return '[object has no keys]'; - } - if (keys[0].length >= maxLength) { - return string_1.truncate(keys[0], maxLength); +class Span { + /** + * Tags for the span. + * @deprecated Use `spanToJSON(span).atttributes` instead. + */ + + /** + * Data for the span. + * @deprecated Use `spanToJSON(span).atttributes` instead. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + + /** + * List of spans that were finalized + * + * @deprecated This property will no longer be public. Span recording will be handled internally. + */ + + /** + * @inheritDoc + * @deprecated Use top level `Sentry.getRootSpan()` instead + */ + + /** + * The instrumenter that created this span. + * + * TODO (v8): This can probably be replaced by an `instanceOf` check of the span class. + * the instrumenter can only be sentry or otel so we can check the span instance + * to verify which one it is and remove this field entirely. + * + * @deprecated This field will be removed. + */ + + /** Epoch timestamp in seconds when the span started. */ + + /** Epoch timestamp in seconds when the span ended. */ + + /** Internal keeper of the status */ + + /** + * You should never call the constructor manually, always use `Sentry.startTransaction()` + * or call `startChild()` on an existing span. + * @internal + * @hideconstructor + * @hidden + */ + constructor(spanContext = {}) { + this._traceId = spanContext.traceId || utils.uuid4(); + this._spanId = spanContext.spanId || utils.uuid4().substring(16); + this._startTime = spanContext.startTimestamp || utils.timestampInSeconds(); + // eslint-disable-next-line deprecation/deprecation + this.tags = spanContext.tags ? { ...spanContext.tags } : {}; + // eslint-disable-next-line deprecation/deprecation + this.data = spanContext.data ? { ...spanContext.data } : {}; + // eslint-disable-next-line deprecation/deprecation + this.instrumenter = spanContext.instrumenter || 'sentry'; + + this._attributes = {}; + this.setAttributes({ + [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanContext.origin || 'manual', + [semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op, + ...spanContext.attributes, + }); + + // eslint-disable-next-line deprecation/deprecation + this._name = spanContext.name || spanContext.description; + + if (spanContext.parentSpanId) { + this._parentSpanId = spanContext.parentSpanId; } - for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { - var serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return string_1.truncate(serialized, maxLength); + // We want to include booleans as well here + if ('sampled' in spanContext) { + this._sampled = spanContext.sampled; } - return ''; -} -exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; -/** - * Given any object, return the new object with removed keys that value was `undefined`. - * Works recursively on objects and arrays. - */ -function dropUndefinedKeys(val) { - var e_1, _a; - if (is_1.isPlainObject(val)) { - var rv = {}; - try { - for (var _b = tslib_1.__values(Object.keys(val)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - if (typeof val[key] !== 'undefined') { - rv[key] = dropUndefinedKeys(val[key]); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - return rv; + if (spanContext.status) { + this._status = spanContext.status; } - if (Array.isArray(val)) { - return val.map(dropUndefinedKeys); + if (spanContext.endTimestamp) { + this._endTime = spanContext.endTimestamp; } - return val; -} -exports.dropUndefinedKeys = dropUndefinedKeys; -/** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. - * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods - */ -function objectify(wat) { - var objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case is_1.isPrimitive(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new wat.constructor(wat); - break; - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; + if (spanContext.exclusiveTime !== undefined) { + this._exclusiveTime = spanContext.exclusiveTime; } - return objectified; -} -exports.objectify = objectify; -//# sourceMappingURL=object.js.map + this._measurements = spanContext.measurements ? { ...spanContext.measurements } : {}; + } -/***/ }), + // This rule conflicts with another eslint rule :( + /* eslint-disable @typescript-eslint/member-ordering */ -/***/ 39188: -/***/ ((__unused_webpack_module, exports) => { + /** + * An alias for `description` of the Span. + * @deprecated Use `spanToJSON(span).description` instead. + */ + get name() { + return this._name || ''; + } -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } - else if (last === '..') { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up++; - } - else if (up) { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up--; - } - } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - // eslint-disable-next-line no-plusplus - for (; up--; up) { - parts.unshift('..'); - } - } - return parts; -} -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - var parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var resolvedPath = ''; - var resolvedAbsolute = false; - for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? args[i] : '/'; - // Skip empty entries - if (!path) { - continue; - } - resolvedPath = path + "/" + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/'); - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} -exports.resolve = resolve; -/** JSDoc */ -function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } - } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } - } - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join('/'); -} -exports.relative = relative; -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - var isPathAbsolute = isAbsolute(path); - var trailingSlash = path.substr(-1) === '/'; - // Normalize the path - var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/'); - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } - return (isPathAbsolute ? '/' : '') + normalizedPath; -} -exports.normalizePath = normalizePath; -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} -exports.isAbsolute = isAbsolute; -// posix version -/** JSDoc */ -function join() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return normalizePath(args.join('/')); -} -exports.join = join; -/** JSDoc */ -function dirname(path) { - var result = splitPath(path); - var root = result[0]; - var dir = result[1]; - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); + /** + * Update the name of the span. + * @deprecated Use `spanToJSON(span).description` instead. + */ + set name(name) { + this.updateName(name); + } + + /** + * Get the description of the Span. + * @deprecated Use `spanToJSON(span).description` instead. + */ + get description() { + return this._name; + } + + /** + * Get the description of the Span. + * @deprecated Use `spanToJSON(span).description` instead. + */ + set description(description) { + this._name = description; + } + + /** + * The ID of the trace. + * @deprecated Use `spanContext().traceId` instead. + */ + get traceId() { + return this._traceId; + } + + /** + * The ID of the trace. + * @deprecated You cannot update the traceId of a span after span creation. + */ + set traceId(traceId) { + this._traceId = traceId; + } + + /** + * The ID of the span. + * @deprecated Use `spanContext().spanId` instead. + */ + get spanId() { + return this._spanId; + } + + /** + * The ID of the span. + * @deprecated You cannot update the spanId of a span after span creation. + */ + set spanId(spanId) { + this._spanId = spanId; + } + + /** + * @inheritDoc + * + * @deprecated Use `startSpan` functions instead. + */ + set parentSpanId(string) { + this._parentSpanId = string; + } + + /** + * @inheritDoc + * + * @deprecated Use `spanToJSON(span).parent_span_id` instead. + */ + get parentSpanId() { + return this._parentSpanId; + } + + /** + * Was this span chosen to be sent as part of the sample? + * @deprecated Use `isRecording()` instead. + */ + get sampled() { + return this._sampled; + } + + /** + * Was this span chosen to be sent as part of the sample? + * @deprecated You cannot update the sampling decision of a span after span creation. + */ + set sampled(sampled) { + this._sampled = sampled; + } + + /** + * Attributes for the span. + * @deprecated Use `spanToJSON(span).atttributes` instead. + */ + get attributes() { + return this._attributes; + } + + /** + * Attributes for the span. + * @deprecated Use `setAttributes()` instead. + */ + set attributes(attributes) { + this._attributes = attributes; + } + + /** + * Timestamp in seconds (epoch time) indicating when the span started. + * @deprecated Use `spanToJSON()` instead. + */ + get startTimestamp() { + return this._startTime; + } + + /** + * Timestamp in seconds (epoch time) indicating when the span started. + * @deprecated In v8, you will not be able to update the span start time after creation. + */ + set startTimestamp(startTime) { + this._startTime = startTime; + } + + /** + * Timestamp in seconds when the span ended. + * @deprecated Use `spanToJSON()` instead. + */ + get endTimestamp() { + return this._endTime; + } + + /** + * Timestamp in seconds when the span ended. + * @deprecated Set the end time via `span.end()` instead. + */ + set endTimestamp(endTime) { + this._endTime = endTime; + } + + /** + * The status of the span. + * + * @deprecated Use `spanToJSON().status` instead to get the status. + */ + get status() { + return this._status; + } + + /** + * The status of the span. + * + * @deprecated Use `.setStatus()` instead to set or update the status. + */ + set status(status) { + this._status = status; + } + + /** + * Operation of the span + * + * @deprecated Use `spanToJSON().op` to read the op instead. + */ + get op() { + return this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP] ; + } + + /** + * Operation of the span + * + * @deprecated Use `startSpan()` functions to set or `span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'op') + * to update the span instead. + */ + set op(op) { + this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP, op); + } + + /** + * The origin of the span, giving context about what created the span. + * + * @deprecated Use `spanToJSON().origin` to read the origin instead. + */ + get origin() { + return this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ; + } + + /** + * The origin of the span, giving context about what created the span. + * + * @deprecated Use `startSpan()` functions to set the origin instead. + */ + set origin(origin) { + this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin); + } + + /* eslint-enable @typescript-eslint/member-ordering */ + + /** @inheritdoc */ + spanContext() { + const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this; + return { + spanId, + traceId, + traceFlags: sampled ? spanUtils.TRACE_FLAG_SAMPLED : spanUtils.TRACE_FLAG_NONE, + }; + } + + /** + * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`. + * Also the `sampled` decision will be inherited. + * + * @deprecated Use `startSpan()`, `startSpanManual()` or `startInactiveSpan()` instead. + */ + startChild( + spanContext, + ) { + const childSpan = new Span({ + ...spanContext, + parentSpanId: this._spanId, + sampled: this._sampled, + traceId: this._traceId, + }); + + // eslint-disable-next-line deprecation/deprecation + childSpan.spanRecorder = this.spanRecorder; + // eslint-disable-next-line deprecation/deprecation + if (childSpan.spanRecorder) { + // eslint-disable-next-line deprecation/deprecation + childSpan.spanRecorder.add(childSpan); } - return root + dir; -} -exports.dirname = dirname; -/** JSDoc */ -function basename(path, ext) { - var f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); + + const rootSpan = getRootSpan.getRootSpan(this); + // TODO: still set span.transaction here until we have a more permanent solution + // Probably similarly to the weakmap we hold in node-experimental + // eslint-disable-next-line deprecation/deprecation + childSpan.transaction = rootSpan ; + + if (debugBuild.DEBUG_BUILD && rootSpan) { + const opStr = (spanContext && spanContext.op) || '< unknown op >'; + const nameStr = spanUtils.spanToJSON(childSpan).description || '< unknown name >'; + const idStr = rootSpan.spanContext().spanId; + + const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`; + utils.logger.log(logMessage); + this._logMessage = logMessage; } - return f; -} -exports.basename = basename; -//# sourceMappingURL=path.js.map -/***/ }), + return childSpan; + } -/***/ 1243: -/***/ ((__unused_webpack_module, exports) => { + /** + * Sets the tag attribute on the current span. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key Tag key + * @param value Tag value + * @deprecated Use `setAttribute()` instead. + */ + setTag(key, value) { + // eslint-disable-next-line deprecation/deprecation + this.tags = { ...this.tags, [key]: value }; + return this; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); -/** - * setPrototypeOf polyfill using __proto__ - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function setProtoOf(obj, proto) { - // @ts-ignore __proto__ does not exist on obj - obj.__proto__ = proto; - return obj; -} -/** - * setPrototypeOf polyfill using mixin - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function mixinProperties(obj, proto) { - for (var prop in proto) { - if (!Object.prototype.hasOwnProperty.call(obj, prop)) { - // @ts-ignore typescript complains about indexing so we remove - obj[prop] = proto[prop]; - } + /** + * Sets the data attribute on the current span + * @param key Data key + * @param value Data value + * @deprecated Use `setAttribute()` instead. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setData(key, value) { + // eslint-disable-next-line deprecation/deprecation + this.data = { ...this.data, [key]: value }; + return this; + } + + /** @inheritdoc */ + setAttribute(key, value) { + if (value === undefined) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._attributes[key]; + } else { + this._attributes[key] = value; } - return obj; -} -//# sourceMappingURL=polyfill.js.map + } -/***/ }), + /** @inheritdoc */ + setAttributes(attributes) { + Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key])); + } -/***/ 31811: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * @inheritDoc + */ + setStatus(value) { + this._status = value; + return this; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var error_1 = __nccwpck_require__(66238); -var syncpromise_1 = __nccwpck_require__(87833); -/** - * Creates an new PromiseBuffer object with the specified limit - * @param limit max number of promises that can be stored in the buffer - */ -function makePromiseBuffer(limit) { - var buffer = []; - function isReady() { - return limit === undefined || buffer.length < limit; + /** + * @inheritDoc + * @deprecated Use top-level `setHttpStatus()` instead. + */ + setHttpStatus(httpStatus) { + spanstatus.setHttpStatus(this, httpStatus); + return this; + } + + /** + * @inheritdoc + * + * @deprecated Use `.updateName()` instead. + */ + setName(name) { + this.updateName(name); + } + + /** + * @inheritDoc + */ + updateName(name) { + this._name = name; + return this; + } + + /** + * @inheritDoc + * + * @deprecated Use `spanToJSON(span).status === 'ok'` instead. + */ + isSuccess() { + return this._status === 'ok'; + } + + /** + * @inheritDoc + * + * @deprecated Use `.end()` instead. + */ + finish(endTimestamp) { + return this.end(endTimestamp); + } + + /** @inheritdoc */ + end(endTimestamp) { + // If already ended, skip + if (this._endTime) { + return; } - /** - * Remove a promise from the queue. - * - * @param task Can be any PromiseLike - * @returns Removed promise. - */ - function remove(task) { - return buffer.splice(buffer.indexOf(task), 1)[0]; + const rootSpan = getRootSpan.getRootSpan(this); + if ( + debugBuild.DEBUG_BUILD && + // Don't call this for transactions + rootSpan && + rootSpan.spanContext().spanId !== this._spanId + ) { + const logMessage = this._logMessage; + if (logMessage) { + utils.logger.log((logMessage ).replace('Starting', 'Finishing')); + } } - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: - * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - function add(taskProducer) { - if (!isReady()) { - return syncpromise_1.rejectedSyncPromise(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); - } - // start the task and add its promise to the queue - var task = taskProducer(); - if (buffer.indexOf(task) === -1) { - buffer.push(task); - } - void task - .then(function () { return remove(task); }) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, function () { - return remove(task).then(null, function () { - // We have to add another catch here because `remove()` starts a new promise chain. - }); - }); - return task; + + this._endTime = spanUtils.spanTimeInputToSeconds(endTimestamp); + } + + /** + * @inheritDoc + * + * @deprecated Use `spanToTraceHeader()` instead. + */ + toTraceparent() { + return spanUtils.spanToTraceHeader(this); + } + + /** + * @inheritDoc + * + * @deprecated Use `spanToJSON()` or access the fields directly instead. + */ + toContext() { + return utils.dropUndefinedKeys({ + data: this._getData(), + description: this._name, + endTimestamp: this._endTime, + // eslint-disable-next-line deprecation/deprecation + op: this.op, + parentSpanId: this._parentSpanId, + sampled: this._sampled, + spanId: this._spanId, + startTimestamp: this._startTime, + status: this._status, + // eslint-disable-next-line deprecation/deprecation + tags: this.tags, + traceId: this._traceId, + }); + } + + /** + * @inheritDoc + * + * @deprecated Update the fields directly instead. + */ + updateWithContext(spanContext) { + // eslint-disable-next-line deprecation/deprecation + this.data = spanContext.data || {}; + // eslint-disable-next-line deprecation/deprecation + this._name = spanContext.name || spanContext.description; + this._endTime = spanContext.endTimestamp; + // eslint-disable-next-line deprecation/deprecation + this.op = spanContext.op; + this._parentSpanId = spanContext.parentSpanId; + this._sampled = spanContext.sampled; + this._spanId = spanContext.spanId || this._spanId; + this._startTime = spanContext.startTimestamp || this._startTime; + this._status = spanContext.status; + // eslint-disable-next-line deprecation/deprecation + this.tags = spanContext.tags || {}; + this._traceId = spanContext.traceId || this._traceId; + + return this; + } + + /** + * @inheritDoc + * + * @deprecated Use `spanToTraceContext()` util function instead. + */ + getTraceContext() { + return spanUtils.spanToTraceContext(this); + } + + /** + * Get JSON representation of this span. + * + * @hidden + * @internal This method is purely for internal purposes and should not be used outside + * of SDK code. If you need to get a JSON representation of a span, + * use `spanToJSON(span)` instead. + */ + getSpanJSON() { + return utils.dropUndefinedKeys({ + data: this._getData(), + description: this._name, + op: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_OP] , + parent_span_id: this._parentSpanId, + span_id: this._spanId, + start_timestamp: this._startTime, + status: this._status, + // eslint-disable-next-line deprecation/deprecation + tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, + timestamp: this._endTime, + trace_id: this._traceId, + origin: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] , + _metrics_summary: metricSummary.getMetricSummaryJsonForSpan(this), + profile_id: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_PROFILE_ID] , + exclusive_time: this._exclusiveTime, + measurements: Object.keys(this._measurements).length > 0 ? this._measurements : undefined, + }); + } + + /** @inheritdoc */ + isRecording() { + return !this._endTime && !!this._sampled; + } + + /** + * Convert the object to JSON. + * @deprecated Use `spanToJSON(span)` instead. + */ + toJSON() { + return this.getSpanJSON(); + } + + /** + * Get the merged data for this span. + * For now, this combines `data` and `attributes` together, + * until eventually we can ingest `attributes` directly. + */ + _getData() + + { + // eslint-disable-next-line deprecation/deprecation + const { data, _attributes: attributes } = this; + + const hasData = Object.keys(data).length > 0; + const hasAttributes = Object.keys(attributes).length > 0; + + if (!hasData && !hasAttributes) { + return undefined; } - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - function drain(timeout) { - return new syncpromise_1.SyncPromise(function (resolve, reject) { - var counter = buffer.length; - if (!counter) { - return resolve(true); - } - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - var capturedSetTimeout = setTimeout(function () { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - // if all promises resolve in time, cancel the timer and resolve to `true` - buffer.forEach(function (item) { - void syncpromise_1.resolvedSyncPromise(item).then(function () { - // eslint-disable-next-line no-plusplus - if (!--counter) { - clearTimeout(capturedSetTimeout); - resolve(true); - } - }, reject); - }); - }); + + if (hasData && hasAttributes) { + return { + ...data, + ...attributes, + }; } - return { - $: buffer, - add: add, - drain: drain, - }; + + return hasData ? data : attributes; + } } -exports.makePromiseBuffer = makePromiseBuffer; -//# sourceMappingURL=promisebuffer.js.map + +exports.Span = Span; +exports.SpanRecorder = SpanRecorder; +//# sourceMappingURL=span.js.map + /***/ }), -/***/ 69377: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 13973: +/***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -exports.DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds -/** - * Extracts Retry-After value from the request header or returns default value - * @param header string representation of 'Retry-After' header - * @param now current unix timestamp - * - */ -function parseRetryAfterHeader(header, now) { - if (now === void 0) { now = Date.now(); } - var headerDelay = parseInt("" + header, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; + +/** The status of an Span. + * + * @deprecated Use string literals - if you require type casting, cast to SpanStatusType type + */ +exports.SpanStatus = void 0; (function (SpanStatus) { + /** The operation completed successfully. */ + const Ok = 'ok'; SpanStatus["Ok"] = Ok; + /** Deadline expired before operation could complete. */ + const DeadlineExceeded = 'deadline_exceeded'; SpanStatus["DeadlineExceeded"] = DeadlineExceeded; + /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ + const Unauthenticated = 'unauthenticated'; SpanStatus["Unauthenticated"] = Unauthenticated; + /** 403 Forbidden */ + const PermissionDenied = 'permission_denied'; SpanStatus["PermissionDenied"] = PermissionDenied; + /** 404 Not Found. Some requested entity (file or directory) was not found. */ + const NotFound = 'not_found'; SpanStatus["NotFound"] = NotFound; + /** 429 Too Many Requests */ + const ResourceExhausted = 'resource_exhausted'; SpanStatus["ResourceExhausted"] = ResourceExhausted; + /** Client specified an invalid argument. 4xx. */ + const InvalidArgument = 'invalid_argument'; SpanStatus["InvalidArgument"] = InvalidArgument; + /** 501 Not Implemented */ + const Unimplemented = 'unimplemented'; SpanStatus["Unimplemented"] = Unimplemented; + /** 503 Service Unavailable */ + const Unavailable = 'unavailable'; SpanStatus["Unavailable"] = Unavailable; + /** Other/generic 5xx. */ + const InternalError = 'internal_error'; SpanStatus["InternalError"] = InternalError; + /** Unknown. Any non-standard HTTP status code. */ + const UnknownError = 'unknown_error'; SpanStatus["UnknownError"] = UnknownError; + /** The operation was cancelled (typically by the user). */ + const Cancelled = 'cancelled'; SpanStatus["Cancelled"] = Cancelled; + /** Already exists (409) */ + const AlreadyExists = 'already_exists'; SpanStatus["AlreadyExists"] = AlreadyExists; + /** Operation was rejected because the system is not in a state required for the operation's */ + const FailedPrecondition = 'failed_precondition'; SpanStatus["FailedPrecondition"] = FailedPrecondition; + /** The operation was aborted, typically due to a concurrency issue. */ + const Aborted = 'aborted'; SpanStatus["Aborted"] = Aborted; + /** Operation was attempted past the valid range. */ + const OutOfRange = 'out_of_range'; SpanStatus["OutOfRange"] = OutOfRange; + /** Unrecoverable data loss or corruption */ + const DataLoss = 'data_loss'; SpanStatus["DataLoss"] = DataLoss; +})(exports.SpanStatus || (exports.SpanStatus = {})); + +/** + * Converts a HTTP status code into a {@link SpanStatusType}. + * + * @param httpStatus The HTTP response status code. + * @returns The span status or unknown_error. + */ +function getSpanStatusFromHttpCode(httpStatus) { + if (httpStatus < 400 && httpStatus >= 100) { + return 'ok'; + } + + if (httpStatus >= 400 && httpStatus < 500) { + switch (httpStatus) { + case 401: + return 'unauthenticated'; + case 403: + return 'permission_denied'; + case 404: + return 'not_found'; + case 409: + return 'already_exists'; + case 413: + return 'failed_precondition'; + case 429: + return 'resource_exhausted'; + default: + return 'invalid_argument'; } - var headerDate = Date.parse("" + header); - if (!isNaN(headerDate)) { - return headerDate - now; + } + + if (httpStatus >= 500 && httpStatus < 600) { + switch (httpStatus) { + case 501: + return 'unimplemented'; + case 503: + return 'unavailable'; + case 504: + return 'deadline_exceeded'; + default: + return 'internal_error'; } - return exports.DEFAULT_RETRY_AFTER; + } + + return 'unknown_error'; } -exports.parseRetryAfterHeader = parseRetryAfterHeader; + /** - * Gets the time that given category is disabled until for rate limiting + * Converts a HTTP status code into a {@link SpanStatusType}. + * + * @deprecated Use {@link spanStatusFromHttpCode} instead. + * This export will be removed in v8 as the signature contains a typo. + * + * @param httpStatus The HTTP response status code. + * @returns The span status or unknown_error. */ -function disabledUntil(limits, category) { - return limits[category] || limits.all || 0; -} -exports.disabledUntil = disabledUntil; +const spanStatusfromHttpCode = getSpanStatusFromHttpCode; + /** - * Checks if a category is rate limited + * Sets the Http status attributes on the current span based on the http code. + * Additionally, the span's status is updated, depending on the http code. */ -function isRateLimited(limits, category, now) { - if (now === void 0) { now = Date.now(); } - return disabledUntil(limits, category) > now; -} -exports.isRateLimited = isRateLimited; -/** - * Update ratelimits from incoming headers. - * Returns true if headers contains a non-empty rate limiting header. - */ -function updateRateLimits(limits, headers, now) { - var e_1, _a, e_2, _b; - if (now === void 0) { now = Date.now(); } - var updatedRateLimits = tslib_1.__assign({}, limits); - // "The name is case-insensitive." - // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - var rateLimitHeader = headers['x-sentry-rate-limits']; - var retryAfterHeader = headers['retry-after']; - if (rateLimitHeader) { - try { - /** - * rate limit headers are of the form - *
,
,.. - * where each
is of the form - * : : : - * where - * is a delay in seconds - * is the event type(s) (error, transaction, etc) being rate limited and is of the form - * ;;... - * is what's being limited (org, project, or key) - ignored by SDK - * is an arbitrary string like "org_quota" - ignored by SDK - */ - for (var _c = tslib_1.__values(rateLimitHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { - var limit = _d.value; - var parameters = limit.split(':', 2); - var headerDelay = parseInt(parameters[0], 10); - var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - if (!parameters[1]) { - updatedRateLimits.all = now + delay; - } - else { - try { - for (var _e = (e_2 = void 0, tslib_1.__values(parameters[1].split(';'))), _f = _e.next(); !_f.done; _f = _e.next()) { - var category = _f.value; - updatedRateLimits[category] = now + delay; - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_f && !_f.done && (_b = _e.return)) _b.call(_e); - } - finally { if (e_2) throw e_2.error; } - } - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) _a.call(_c); - } - finally { if (e_1) throw e_1.error; } - } - } - else if (retryAfterHeader) { - updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); - } - return updatedRateLimits; +function setHttpStatus(span, httpStatus) { + // TODO (v8): Remove these calls + // Relay does not require us to send the status code as a tag + // For now, just because users might expect it to land as a tag we keep sending it. + // Same with data. + // In v8, we replace both, simply with + // span.setAttribute('http.response.status_code', httpStatus); + + // eslint-disable-next-line deprecation/deprecation + span.setTag('http.status_code', String(httpStatus)); + // eslint-disable-next-line deprecation/deprecation + span.setData('http.response.status_code', httpStatus); + + const spanStatus = getSpanStatusFromHttpCode(httpStatus); + if (spanStatus !== 'unknown_error') { + span.setStatus(spanStatus); + } } -exports.updateRateLimits = updateRateLimits; -//# sourceMappingURL=ratelimit.js.map + +exports.getSpanStatusFromHttpCode = getSpanStatusFromHttpCode; +exports.setHttpStatus = setHttpStatus; +exports.spanStatusfromHttpCode = spanStatusfromHttpCode; +//# sourceMappingURL=spanstatus.js.map + /***/ }), -/***/ 68853: +/***/ 16474: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var enums_1 = __nccwpck_require__(19489); -function isSupportedSeverity(level) { - return enums_1.SeverityLevels.indexOf(level) !== -1; -} + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const hub = __nccwpck_require__(5553); +const spanUtils = __nccwpck_require__(19925); +__nccwpck_require__(64332); +__nccwpck_require__(13973); +const dynamicSamplingContext = __nccwpck_require__(65372); +const exports$1 = __nccwpck_require__(61117); +const handleCallbackErrors = __nccwpck_require__(46544); +const hasTracingEnabled = __nccwpck_require__(1295); + /** - * Converts a string-based level into a {@link Severity}. + * Wraps a function with a transaction/span and finishes the span after the function is done. * - * @param level string representation of Severity - * @returns Severity + * Note that if you have not enabled tracing extensions via `addTracingExtensions` + * or you didn't set `tracesSampleRate`, this function will not generate spans + * and the `span` returned from the callback will be undefined. + * + * This function is meant to be used internally and may break at any time. Use at your own risk. + * + * @internal + * @private + * + * @deprecated Use `startSpan` instead. */ -function severityFromString(level) { - if (level === 'warn') - return types_1.Severity.Warning; - if (isSupportedSeverity(level)) { - return level; - } - return types_1.Severity.Log; -} -exports.severityFromString = severityFromString; -//# sourceMappingURL=severity.js.map +function trace( + context, + callback, + // eslint-disable-next-line @typescript-eslint/no-empty-function + onError = () => {}, + // eslint-disable-next-line @typescript-eslint/no-empty-function + afterFinish = () => {}, +) { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); + const scope = exports$1.getCurrentScope(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + + const spanContext = normalizeContext(context); + const activeSpan = createChildSpanOrTransaction(hub$1, { + parentSpan, + spanContext, + forceTransaction: false, + scope, + }); -/***/ }), + // eslint-disable-next-line deprecation/deprecation + scope.setSpan(activeSpan); -/***/ 5986: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return handleCallbackErrors.handleCallbackErrors( + () => callback(activeSpan), + error => { + activeSpan && activeSpan.setStatus('internal_error'); + onError(error, activeSpan); + }, + () => { + activeSpan && activeSpan.end(); + // eslint-disable-next-line deprecation/deprecation + scope.setSpan(parentSpan); + afterFinish(); + }, + ); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var STACKTRACE_LIMIT = 50; /** - * Creates a stack parser with the supplied line parsers + * Wraps a function with a transaction/span and finishes the span after the function is done. + * The created span is the active span and will be used as parent by other spans created inside the function + * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active. * - * StackFrames are returned in the correct order for Sentry Exception - * frames and with Sentry SDK internal frames removed from the top and bottom + * If you want to create a span that is not set as active, use {@link startInactiveSpan}. * + * Note that if you have not enabled tracing extensions via `addTracingExtensions` + * or you didn't set `tracesSampleRate`, this function will not generate spans + * and the `span` returned from the callback will be undefined. */ -function createStackParser() { - var parsers = []; - for (var _i = 0; _i < arguments.length; _i++) { - parsers[_i] = arguments[_i]; - } - var sortedParsers = parsers.sort(function (a, b) { return a[0] - b[0]; }).map(function (p) { return p[1]; }); - return function (stack, skipFirst) { - var e_1, _a, e_2, _b; - if (skipFirst === void 0) { skipFirst = 0; } - var frames = []; - try { - for (var _c = tslib_1.__values(stack.split('\n').slice(skipFirst)), _d = _c.next(); !_d.done; _d = _c.next()) { - var line = _d.value; - try { - for (var sortedParsers_1 = (e_2 = void 0, tslib_1.__values(sortedParsers)), sortedParsers_1_1 = sortedParsers_1.next(); !sortedParsers_1_1.done; sortedParsers_1_1 = sortedParsers_1.next()) { - var parser = sortedParsers_1_1.value; - var frame = parser(line); - if (frame) { - frames.push(frame); - break; - } - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (sortedParsers_1_1 && !sortedParsers_1_1.done && (_b = sortedParsers_1.return)) _b.call(sortedParsers_1); - } - finally { if (e_2) throw e_2.error; } - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) _a.call(_c); +function startSpan(context, callback) { + const spanContext = normalizeContext(context); + + return hub.runWithAsyncContext(() => { + return exports$1.withScope(context.scope, scope => { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + + const shouldSkipSpan = context.onlyIfParent && !parentSpan; + const activeSpan = shouldSkipSpan + ? undefined + : createChildSpanOrTransaction(hub$1, { + parentSpan, + spanContext, + forceTransaction: context.forceTransaction, + scope, + }); + + return handleCallbackErrors.handleCallbackErrors( + () => callback(activeSpan), + () => { + // Only update the span status if it hasn't been changed yet + if (activeSpan) { + const { status } = spanUtils.spanToJSON(activeSpan); + if (!status || status === 'ok') { + activeSpan.setStatus('internal_error'); } - finally { if (e_1) throw e_1.error; } - } - return stripSentryFramesAndReverse(frames); - }; + } + }, + () => activeSpan && activeSpan.end(), + ); + }); + }); } -exports.createStackParser = createStackParser; + /** - * @hidden + * @deprecated Use {@link startSpan} instead. */ -function stripSentryFramesAndReverse(stack) { - if (!stack.length) { - return []; - } - var localStack = stack; - var firstFrameFunction = localStack[0].function || ''; - var lastFrameFunction = localStack[localStack.length - 1].function || ''; - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); - } - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(function (frame) { return (tslib_1.__assign(tslib_1.__assign({}, frame), { filename: frame.filename || localStack[0].filename, function: frame.function || '?' })); }) - .reverse(); -} -exports.stripSentryFramesAndReverse = stripSentryFramesAndReverse; -var defaultFunctionName = ''; +const startActiveSpan = startSpan; + /** - * Safely extract function name from itself + * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span + * after the function is done automatically. You'll have to call `span.end()` manually. + * + * The created span is the active span and will be used as parent by other spans created inside the function + * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active. + * + * Note that if you have not enabled tracing extensions via `addTracingExtensions` + * or you didn't set `tracesSampleRate`, this function will not generate spans + * and the `span` returned from the callback will be undefined. */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } - catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} -exports.getFunctionName = getFunctionName; -//# sourceMappingURL=stacktrace.js.map +function startSpanManual( + context, + callback, +) { + const spanContext = normalizeContext(context); + + return hub.runWithAsyncContext(() => { + return exports$1.withScope(context.scope, scope => { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const parentSpan = scope.getSpan(); + + const shouldSkipSpan = context.onlyIfParent && !parentSpan; + const activeSpan = shouldSkipSpan + ? undefined + : createChildSpanOrTransaction(hub$1, { + parentSpan, + spanContext, + forceTransaction: context.forceTransaction, + scope, + }); -/***/ }), + function finishAndSetSpan() { + activeSpan && activeSpan.end(); + } -/***/ 70313: -/***/ ((__unused_webpack_module, exports) => { + return handleCallbackErrors.handleCallbackErrors( + () => callback(activeSpan, finishAndSetSpan), + () => { + // Only update the span status if it hasn't been changed yet, and the span is not yet finished + if (activeSpan && activeSpan.isRecording()) { + const { status } = spanUtils.spanToJSON(activeSpan); + if (!status || status === 'ok') { + activeSpan.setStatus('internal_error'); + } + } + }, + ); + }); + }); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Converts an HTTP status code to sentry status {@link EventStatus}. + * Creates a span. This span is not set as active, so will not get automatic instrumentation spans + * as children or be able to be accessed via `Sentry.getSpan()`. + * + * If you want to create a span that is set as active, use {@link startSpan}. * - * @param code number HTTP status code - * @returns EventStatus + * Note that if you have not enabled tracing extensions via `addTracingExtensions` + * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans + * and the `span` returned from the callback will be undefined. */ -function eventStatusFromHttpCode(code) { - if (code >= 200 && code < 300) { - return 'success'; - } - if (code === 429) { - return 'rate_limit'; - } - if (code >= 400 && code < 500) { - return 'invalid'; - } - if (code >= 500) { - return 'failed'; - } - return 'unknown'; -} -exports.eventStatusFromHttpCode = eventStatusFromHttpCode; -//# sourceMappingURL=status.js.map +function startInactiveSpan(context) { + if (!hasTracingEnabled.hasTracingEnabled()) { + return undefined; + } -/***/ }), + const spanContext = normalizeContext(context); + // eslint-disable-next-line deprecation/deprecation + const hub$1 = hub.getCurrentHub(); + const parentSpan = context.scope + ? // eslint-disable-next-line deprecation/deprecation + context.scope.getSpan() + : getActiveSpan(); -/***/ 66538: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const shouldSkipSpan = context.onlyIfParent && !parentSpan; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string (0 = unlimited) - * @returns string Encoded - */ -function truncate(str, max) { - if (max === void 0) { max = 0; } - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : str.substr(0, max) + "..."; + if (shouldSkipSpan) { + return undefined; + } + + const scope = context.scope || exports$1.getCurrentScope(); + + // Even though we don't actually want to make this span active on the current scope, + // we need to make it active on a temporary scope that we use for event processing + // as otherwise, it won't pick the correct span for the event when processing it + const temporaryScope = (scope ).clone(); + + return createChildSpanOrTransaction(hub$1, { + parentSpan, + spanContext, + forceTransaction: context.forceTransaction, + scope: temporaryScope, + }); } -exports.truncate = truncate; + /** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded + * Returns the currently active span. */ -function snipLine(line, colno) { - var newLine = line; - var lineLength = newLine.length; - if (lineLength <= 150) { - return newLine; - } - if (colno > lineLength) { - // eslint-disable-next-line no-param-reassign - colno = lineLength; - } - var start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - var end = Math.min(start + 140, lineLength); - if (end > lineLength - 5) { - end = lineLength; - } - if (end === lineLength) { - start = Math.max(end - 140, 0); - } - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = "'{snip} " + newLine; - } - if (end < lineLength) { - newLine += ' {snip}'; - } - return newLine; +function getActiveSpan() { + // eslint-disable-next-line deprecation/deprecation + return exports$1.getCurrentScope().getSpan(); } -exports.snipLine = snipLine; -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - var output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < input.length; i++) { - var value = input[i]; - try { - output.push(String(value)); - } - catch (e) { - output.push('[value cannot be serialized]'); - } - } - return output.join(delimiter); + +const continueTrace = ( + { + sentryTrace, + baggage, + } + +, + callback, +) => { + // TODO(v8): Change this function so it doesn't do anything besides setting the propagation context on the current scope: + /* + return withScope((scope) => { + const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); + scope.setPropagationContext(propagationContext); + return callback(); + }) + */ + + const currentScope = exports$1.getCurrentScope(); + + // eslint-disable-next-line deprecation/deprecation + const { traceparentData, dynamicSamplingContext, propagationContext } = utils.tracingContextFromHeaders( + sentryTrace, + baggage, + ); + + currentScope.setPropagationContext(propagationContext); + + if (debugBuild.DEBUG_BUILD && traceparentData) { + utils.logger.log(`[Tracing] Continuing trace ${traceparentData.traceId}.`); + } + + const transactionContext = { + ...traceparentData, + metadata: utils.dropUndefinedKeys({ + dynamicSamplingContext, + }), + }; + + if (!callback) { + return transactionContext; + } + + return hub.runWithAsyncContext(() => { + return callback(transactionContext); + }); +}; + +function createChildSpanOrTransaction( + // eslint-disable-next-line deprecation/deprecation + hub$1, + { + parentSpan, + spanContext, + forceTransaction, + scope, + } + +, +) { + if (!hasTracingEnabled.hasTracingEnabled()) { + return undefined; + } + + const isolationScope = hub.getIsolationScope(); + + let span; + if (parentSpan && !forceTransaction) { + // eslint-disable-next-line deprecation/deprecation + span = parentSpan.startChild(spanContext); + } else if (parentSpan) { + // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope + const dsc = dynamicSamplingContext.getDynamicSamplingContextFromSpan(parentSpan); + const { traceId, spanId: parentSpanId } = parentSpan.spanContext(); + const sampled = spanUtils.spanIsSampled(parentSpan); + + // eslint-disable-next-line deprecation/deprecation + span = hub$1.startTransaction({ + traceId, + parentSpanId, + parentSampled: sampled, + ...spanContext, + metadata: { + dynamicSamplingContext: dsc, + // eslint-disable-next-line deprecation/deprecation + ...spanContext.metadata, + }, + }); + } else { + const { traceId, dsc, parentSpanId, sampled } = { + ...isolationScope.getPropagationContext(), + ...scope.getPropagationContext(), + }; + + // eslint-disable-next-line deprecation/deprecation + span = hub$1.startTransaction({ + traceId, + parentSpanId, + parentSampled: sampled, + ...spanContext, + metadata: { + dynamicSamplingContext: dsc, + // eslint-disable-next-line deprecation/deprecation + ...spanContext.metadata, + }, + }); + } + + // We always set this as active span on the scope + // In the case of this being an inactive span, we ensure to pass a detached scope in here in the first place + // But by having this here, we can ensure that the lookup through `getCapturedScopesOnSpan` results in the correct scope & span combo + // eslint-disable-next-line deprecation/deprecation + scope.setSpan(span); + + setCapturedScopesOnSpan(span, scope, isolationScope); + + return span; } -exports.safeJoin = safeJoin; + /** - * Checks if the value matches a regex or includes the string - * @param value The string value to be checked against - * @param pattern Either a regex or a string that must be contained in value + * This converts StartSpanOptions to TransactionContext. + * For the most part (for now) we accept the same options, + * but some of them need to be transformed. + * + * Eventually the StartSpanOptions will be more aligned with OpenTelemetry. */ -function isMatchingPattern(value, pattern) { - if (!is_1.isString(value)) { - return false; - } - if (is_1.isRegExp(pattern)) { - return pattern.test(value); - } - if (typeof pattern === 'string') { - return value.indexOf(pattern) !== -1; - } - return false; +function normalizeContext(context) { + if (context.startTime) { + const ctx = { ...context }; + ctx.startTimestamp = spanUtils.spanTimeInputToSeconds(context.startTime); + delete ctx.startTime; + return ctx; + } + + return context; } -exports.isMatchingPattern = isMatchingPattern; + +const SCOPE_ON_START_SPAN_FIELD = '_sentryScope'; +const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope'; + +function setCapturedScopesOnSpan(span, scope, isolationScope) { + if (span) { + utils.addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope); + utils.addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope); + } +} + /** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped + * Grabs the scope and isolation scope off a span that were active when the span was started. */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +function getCapturedScopesOnSpan(span) { + return { + scope: (span )[SCOPE_ON_START_SPAN_FIELD], + isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD], + }; } -exports.escapeStringForRegex = escapeStringForRegex; -//# sourceMappingURL=string.js.map + +exports.continueTrace = continueTrace; +exports.getActiveSpan = getActiveSpan; +exports.getCapturedScopesOnSpan = getCapturedScopesOnSpan; +exports.startActiveSpan = startActiveSpan; +exports.startInactiveSpan = startInactiveSpan; +exports.startSpan = startSpan; +exports.startSpanManual = startSpanManual; +exports.trace = trace; +//# sourceMappingURL=trace.js.map + /***/ }), -/***/ 88714: +/***/ 85111: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var env_1 = __nccwpck_require__(31913); -var global_1 = __nccwpck_require__(68813); -var logger_1 = __nccwpck_require__(15577); -/** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. - */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } - catch (e) { - return false; + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); +const hub = __nccwpck_require__(5553); +const metricSummary = __nccwpck_require__(3875); +const semanticAttributes = __nccwpck_require__(52781); +const spanUtils = __nccwpck_require__(19925); +const dynamicSamplingContext = __nccwpck_require__(65372); +const span = __nccwpck_require__(41223); +const trace = __nccwpck_require__(16474); + +/** JSDoc */ +class Transaction extends span.Span { + /** + * The reference to the current hub. + */ + // eslint-disable-next-line deprecation/deprecation + + // DO NOT yet remove this property, it is used in a hack for v7 backwards compatibility. + + /** + * This constructor should never be called manually. Those instrumenting tracing should use + * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. + * @internal + * @hideconstructor + * @hidden + * + * @deprecated Transactions will be removed in v8. Use spans instead. + */ + // eslint-disable-next-line deprecation/deprecation + constructor(transactionContext, hub$1) { + super(transactionContext); + this._contexts = {}; + + // eslint-disable-next-line deprecation/deprecation + this._hub = hub$1 || hub.getCurrentHub(); + + this._name = transactionContext.name || ''; + + this._metadata = { + // eslint-disable-next-line deprecation/deprecation + ...transactionContext.metadata, + }; + + this._trimEnd = transactionContext.trimEnd; + + // this is because transactions are also spans, and spans have a transaction pointer + // TODO (v8): Replace this with another way to set the root span + // eslint-disable-next-line deprecation/deprecation + this.transaction = this; + + // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means + // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means) + const incomingDynamicSamplingContext = this._metadata.dynamicSamplingContext; + if (incomingDynamicSamplingContext) { + // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext` + this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext }; } -} -exports.supportsErrorEvent = supportsErrorEvent; -/** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. - * - * @returns Answer to the given question. - */ -function supportsDOMError() { - try { - // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': - // 1 argument required, but only 0 present. - // @ts-ignore It really needs 1 argument, not 0. - new DOMError(''); - return true; + } + + // This sadly conflicts with the getter/setter ordering :( + /* eslint-disable @typescript-eslint/member-ordering */ + + /** + * Getter for `name` property. + * @deprecated Use `spanToJSON(span).description` instead. + */ + get name() { + return this._name; + } + + /** + * Setter for `name` property, which also sets `source` as custom. + * @deprecated Use `updateName()` and `setMetadata()` instead. + */ + set name(newName) { + // eslint-disable-next-line deprecation/deprecation + this.setName(newName); + } + + /** + * Get the metadata for this transaction. + * @deprecated Use `spanGetMetadata(transaction)` instead. + */ + get metadata() { + // We merge attributes in for backwards compatibility + return { + // Defaults + // eslint-disable-next-line deprecation/deprecation + source: 'custom', + spanMetadata: {}, + + // Legacy metadata + ...this._metadata, + + // From attributes + ...(this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] && { + source: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] , + }), + ...(this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] && { + sampleRate: this._attributes[semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] , + }), + }; + } + + /** + * Update the metadata for this transaction. + * @deprecated Use `spanGetMetadata(transaction)` instead. + */ + set metadata(metadata) { + this._metadata = metadata; + } + + /* eslint-enable @typescript-eslint/member-ordering */ + + /** + * Setter for `name` property, which also sets `source` on the metadata. + * + * @deprecated Use `.updateName()` and `.setAttribute()` instead. + */ + setName(name, source = 'custom') { + this._name = name; + this.setAttribute(semanticAttributes.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source); + } + + /** @inheritdoc */ + updateName(name) { + this._name = name; + return this; + } + + /** + * Attaches SpanRecorder to the span itself + * @param maxlen maximum number of spans that can be recorded + */ + initSpanRecorder(maxlen = 1000) { + // eslint-disable-next-line deprecation/deprecation + if (!this.spanRecorder) { + // eslint-disable-next-line deprecation/deprecation + this.spanRecorder = new span.SpanRecorder(maxlen); } - catch (e) { - return false; + // eslint-disable-next-line deprecation/deprecation + this.spanRecorder.add(this); + } + + /** + * Set the context of a transaction event. + * @deprecated Use either `.setAttribute()`, or set the context on the scope before creating the transaction. + */ + setContext(key, context) { + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; + } else { + this._contexts[key] = context; } -} -exports.supportsDOMError = supportsDOMError; -/** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. - * - * @returns Answer to the given question. - */ -function supportsDOMException() { - try { - new DOMException(''); - return true; + } + + /** + * @inheritDoc + * + * @deprecated Use top-level `setMeasurement()` instead. + */ + setMeasurement(name, value, unit = '') { + this._measurements[name] = { value, unit }; + } + + /** + * Store metadata on this transaction. + * @deprecated Use attributes or store data on the scope instead. + */ + setMetadata(newMetadata) { + this._metadata = { ...this._metadata, ...newMetadata }; + } + + /** + * @inheritDoc + */ + end(endTimestamp) { + const timestampInS = spanUtils.spanTimeInputToSeconds(endTimestamp); + const transaction = this._finishTransaction(timestampInS); + if (!transaction) { + return undefined; } - catch (e) { - return false; + // eslint-disable-next-line deprecation/deprecation + return this._hub.captureEvent(transaction); + } + + /** + * @inheritDoc + */ + toContext() { + // eslint-disable-next-line deprecation/deprecation + const spanContext = super.toContext(); + + return utils.dropUndefinedKeys({ + ...spanContext, + name: this._name, + trimEnd: this._trimEnd, + }); + } + + /** + * @inheritDoc + */ + updateWithContext(transactionContext) { + // eslint-disable-next-line deprecation/deprecation + super.updateWithContext(transactionContext); + + this._name = transactionContext.name || ''; + this._trimEnd = transactionContext.trimEnd; + + return this; + } + + /** + * @inheritdoc + * + * @experimental + * + * @deprecated Use top-level `getDynamicSamplingContextFromSpan` instead. + */ + getDynamicSamplingContext() { + return dynamicSamplingContext.getDynamicSamplingContextFromSpan(this); + } + + /** + * Override the current hub with a new one. + * Used if you want another hub to finish the transaction. + * + * @internal + */ + // eslint-disable-next-line deprecation/deprecation + setHub(hub) { + this._hub = hub; + } + + /** + * Get the profile id of the transaction. + */ + getProfileId() { + if (this._contexts !== undefined && this._contexts['profile'] !== undefined) { + return this._contexts['profile'].profile_id ; } -} -exports.supportsDOMException = supportsDOMException; -/** - * Tells whether current environment supports Fetch API - * {@link supportsFetch}. - * - * @returns Answer to the given question. - */ -function supportsFetch() { - if (!('fetch' in global_1.getGlobalObject())) { - return false; + return undefined; + } + + /** + * Finish the transaction & prepare the event to send to Sentry. + */ + _finishTransaction(endTimestamp) { + // This transaction is already finished, so we should not flush it again. + if (this._endTime !== undefined) { + return undefined; } - try { - new Headers(); - new Request(''); - new Response(); - return true; + + if (!this._name) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Transaction has no name, falling back to ``.'); + this._name = ''; } - catch (e) { - return false; + + // just sets the end timestamp + super.end(endTimestamp); + + // eslint-disable-next-line deprecation/deprecation + const client = this._hub.getClient(); + if (client && client.emit) { + client.emit('finishTransaction', this); } -} -exports.supportsFetch = supportsFetch; -/** - * isNativeFetch checks if the given function is a native implementation of fetch() - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function isNativeFetch(func) { - return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); -} -exports.isNativeFetch = isNativeFetch; -/** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. - * - * @returns true if `window.fetch` is natively implemented, false otherwise - */ -function supportsNativeFetch() { - if (!supportsFetch()) { - return false; + + if (this._sampled !== true) { + // At this point if `sampled !== true` we want to discard the transaction. + debugBuild.DEBUG_BUILD && utils.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); + + if (client) { + client.recordDroppedEvent('sample_rate', 'transaction'); + } + + return undefined; } - var global = global_1.getGlobalObject(); - // Fast path to avoid DOM I/O - // eslint-disable-next-line @typescript-eslint/unbound-method - if (isNativeFetch(global.fetch)) { - return true; + + // eslint-disable-next-line deprecation/deprecation + const finishedSpans = this.spanRecorder + ? // eslint-disable-next-line deprecation/deprecation + this.spanRecorder.spans.filter(span => span !== this && spanUtils.spanToJSON(span).timestamp) + : []; + + if (this._trimEnd && finishedSpans.length > 0) { + const endTimes = finishedSpans.map(span => spanUtils.spanToJSON(span).timestamp).filter(Boolean) ; + this._endTime = endTimes.reduce((prev, current) => { + return prev > current ? prev : current; + }); } - // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) - // so create a "pure" iframe to see if that has native fetch - var result = false; - var doc = global.document; + + const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = trace.getCapturedScopesOnSpan(this); + // eslint-disable-next-line deprecation/deprecation - if (doc && typeof doc.createElement === 'function') { - try { - var sandbox = doc.createElement('iframe'); - sandbox.hidden = true; - doc.head.appendChild(sandbox); - if (sandbox.contentWindow && sandbox.contentWindow.fetch) { - // eslint-disable-next-line @typescript-eslint/unbound-method - result = isNativeFetch(sandbox.contentWindow.fetch); - } - doc.head.removeChild(sandbox); - } - catch (err) { - env_1.isDebugBuild() && - logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } + const { metadata } = this; + // eslint-disable-next-line deprecation/deprecation + const { source } = metadata; + + const transaction = { + contexts: { + ...this._contexts, + // We don't want to override trace context + trace: spanUtils.spanToTraceContext(this), + }, + // TODO: Pass spans serialized via `spanToJSON()` here instead in v8. + spans: finishedSpans, + start_timestamp: this._startTime, + // eslint-disable-next-line deprecation/deprecation + tags: this.tags, + timestamp: this._endTime, + transaction: this._name, + type: 'transaction', + sdkProcessingMetadata: { + ...metadata, + capturedSpanScope, + capturedSpanIsolationScope, + ...utils.dropUndefinedKeys({ + dynamicSamplingContext: dynamicSamplingContext.getDynamicSamplingContextFromSpan(this), + }), + }, + _metrics_summary: metricSummary.getMetricSummaryJsonForSpan(this), + ...(source && { + transaction_info: { + source, + }, + }), + }; + + const hasMeasurements = Object.keys(this._measurements).length > 0; + + if (hasMeasurements) { + debugBuild.DEBUG_BUILD && + utils.logger.log( + '[Measurements] Adding measurements to transaction', + JSON.stringify(this._measurements, undefined, 2), + ); + transaction.measurements = this._measurements; } - return result; + + // eslint-disable-next-line deprecation/deprecation + debugBuild.DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing ${this.op} transaction: ${this._name}.`); + + return transaction; + } } -exports.supportsNativeFetch = supportsNativeFetch; + +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map + + +/***/ }), + +/***/ 29406: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const hub = __nccwpck_require__(5553); + /** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. + * Grabs active transaction off scope. * - * @returns Answer to the given question. + * @deprecated You should not rely on the transaction, but just use `startSpan()` APIs instead. */ -function supportsReportingObserver() { - return 'ReportingObserver' in global_1.getGlobalObject(); +// eslint-disable-next-line deprecation/deprecation +function getActiveTransaction(maybeHub) { + // eslint-disable-next-line deprecation/deprecation + const hub$1 = maybeHub || hub.getCurrentHub(); + // eslint-disable-next-line deprecation/deprecation + const scope = hub$1.getScope(); + // eslint-disable-next-line deprecation/deprecation + return scope.getTransaction() ; } -exports.supportsReportingObserver = supportsReportingObserver; + /** - * Tells whether current environment supports Referrer Policy API - * {@link supportsReferrerPolicy}. + * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used + * to be declared in this file. It was later moved into `@sentry/utils` as part of a + * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData` + * is the only tracing function used by `@sentry/node`). * - * @returns Answer to the given question. - */ -function supportsReferrerPolicy() { - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default' - // (see https://caniuse.com/#feat=referrer-policy), - // it doesn't. And it throws an exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - if (!supportsFetch()) { - return false; - } - try { - new Request('_', { - referrerPolicy: 'origin', - }); - return true; - } - catch (e) { - return false; - } -} -exports.supportsReferrerPolicy = supportsReferrerPolicy; -/** - * Tells whether current environment supports History API - * {@link supportsHistory}. + * These exports are kept here for backwards compatability's sake. * - * @returns Answer to the given question. + * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details. + * + * @deprecated Import this function from `@sentry/utils` instead */ -function supportsHistory() { - // NOTE: in Chrome App environment, touching history.pushState, *even inside - // a try/catch block*, will cause Chrome to output an error to console.error - // borrowed from: https://github.com/angular/angular.js/pull/13945/files - var global = global_1.getGlobalObject(); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var chrome = global.chrome; - var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; - return !isChromePackagedApp && hasHistoryApi; -} -exports.supportsHistory = supportsHistory; -//# sourceMappingURL=supports.js.map +const extractTraceparentData = utils.extractTraceparentData; + +exports.stripUrlQueryAndFragment = utils.stripUrlQueryAndFragment; +exports.extractTraceparentData = extractTraceparentData; +exports.getActiveTransaction = getActiveTransaction; +//# sourceMappingURL=utils.js.map + /***/ }), -/***/ 87833: +/***/ 6424: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/explicit-function-return-type */ -/* eslint-disable @typescript-eslint/typedef */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var is_1 = __nccwpck_require__(92757); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); + +const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; + /** - * Creates a resolved sync promise. + * Creates an instance of a Sentry `Transport` * - * @param value the value to resolve the promise with - * @returns the resolved sync promise + * @param options + * @param makeRequest */ -function resolvedSyncPromise(value) { - return new SyncPromise(function (resolve) { - resolve(value); +function createTransport( + options, + makeRequest, + buffer = utils.makePromiseBuffer( + options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE, + ), +) { + let rateLimits = {}; + const flush = (timeout) => buffer.drain(timeout); + + function send(envelope) { + const filteredEnvelopeItems = []; + + // Drop rate limited items from envelope + utils.forEachEnvelopeItem(envelope, (item, type) => { + const dataCategory = utils.envelopeItemTypeToDataCategory(type); + if (utils.isRateLimited(rateLimits, dataCategory)) { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent('ratelimit_backoff', dataCategory, event); + } else { + filteredEnvelopeItems.push(item); + } }); + + // Skip sending if envelope is empty after filtering out rate limited events + if (filteredEnvelopeItems.length === 0) { + return utils.resolvedSyncPromise(); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const filteredEnvelope = utils.createEnvelope(envelope[0], filteredEnvelopeItems ); + + // Creates client report for each item in an envelope + const recordEnvelopeLoss = (reason) => { + utils.forEachEnvelopeItem(filteredEnvelope, (item, type) => { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent(reason, utils.envelopeItemTypeToDataCategory(type), event); + }); + }; + + const requestTask = () => + makeRequest({ body: utils.serializeEnvelope(filteredEnvelope, options.textEncoder) }).then( + response => { + // We don't want to throw on NOK responses, but we want to at least log them + if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { + debugBuild.DEBUG_BUILD && utils.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); + } + + rateLimits = utils.updateRateLimits(rateLimits, response); + return response; + }, + error => { + recordEnvelopeLoss('network_error'); + throw error; + }, + ); + + return buffer.add(requestTask).then( + result => result, + error => { + if (error instanceof utils.SentryError) { + debugBuild.DEBUG_BUILD && utils.logger.error('Skipped sending event because buffer is full.'); + recordEnvelopeLoss('queue_overflow'); + return utils.resolvedSyncPromise(); + } else { + throw error; + } + }, + ); + } + + // We use this to identifify if the transport is the base transport + // TODO (v8): Remove this again as we'll no longer need it + send.__sentry__baseTransport__ = true; + + return { + send, + flush, + }; } -exports.resolvedSyncPromise = resolvedSyncPromise; -/** - * Creates a rejected sync promise. - * - * @param value the value to reject the promise with - * @returns the rejected sync promise - */ -function rejectedSyncPromise(reason) { - return new SyncPromise(function (_, reject) { - reject(reason); - }); + +function getEventForEnvelopeItem(item, type) { + if (type !== 'event' && type !== 'transaction') { + return undefined; + } + + return Array.isArray(item) ? (item )[1] : undefined; } -exports.rejectedSyncPromise = rejectedSyncPromise; -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -var SyncPromise = /** @class */ (function () { - function SyncPromise(executor) { - var _this = this; - this._state = 0 /* PENDING */; - this._handlers = []; - /** JSDoc */ - this._resolve = function (value) { - _this._setResult(1 /* RESOLVED */, value); - }; - /** JSDoc */ - this._reject = function (reason) { - _this._setResult(2 /* REJECTED */, reason); - }; - /** JSDoc */ - this._setResult = function (state, value) { - if (_this._state !== 0 /* PENDING */) { - return; - } - if (is_1.isThenable(value)) { - void value.then(_this._resolve, _this._reject); - return; - } - _this._state = state; - _this._value = value; - _this._executeHandlers(); - }; - /** JSDoc */ - this._executeHandlers = function () { - if (_this._state === 0 /* PENDING */) { - return; - } - var cachedHandlers = _this._handlers.slice(); - _this._handlers = []; - cachedHandlers.forEach(function (handler) { - if (handler[0]) { - return; - } - if (_this._state === 1 /* RESOLVED */) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler[1](_this._value); - } - if (_this._state === 2 /* REJECTED */) { - handler[2](_this._value); - } - handler[0] = true; - }); - }; - try { - executor(this._resolve, this._reject); - } - catch (e) { - this._reject(e); - } - } - /** JSDoc */ - SyncPromise.prototype.then = function (onfulfilled, onrejected) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - _this._handlers.push([ - false, - function (result) { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result); - } - else { - try { - resolve(onfulfilled(result)); - } - catch (e) { - reject(e); - } - } - }, - function (reason) { - if (!onrejected) { - reject(reason); - } - else { - try { - resolve(onrejected(reason)); - } - catch (e) { - reject(e); - } - } - }, - ]); - _this._executeHandlers(); - }); - }; - /** JSDoc */ - SyncPromise.prototype.catch = function (onrejected) { - return this.then(function (val) { return val; }, onrejected); - }; - /** JSDoc */ - SyncPromise.prototype.finally = function (onfinally) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - var val; - var isRejected; - return _this.then(function (value) { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, function (reason) { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }).then(function () { - if (isRejected) { - reject(val); - return; - } - resolve(val); - }); - }); - }; - return SyncPromise; -}()); -exports.SyncPromise = SyncPromise; -//# sourceMappingURL=syncpromise.js.map + +exports.DEFAULT_TRANSPORT_BUFFER_SIZE = DEFAULT_TRANSPORT_BUFFER_SIZE; +exports.createTransport = createTransport; +//# sourceMappingURL=base.js.map + /***/ }), -/***/ 1735: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 36228: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -var global_1 = __nccwpck_require__(68813); -var node_1 = __nccwpck_require__(16411); + +const utils = __nccwpck_require__(25304); +const api = __nccwpck_require__(28494); + /** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. + * Gets an event from an envelope. * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + * This is only exported for use in the tests */ -var dateTimestampSource = { - nowSeconds: function () { return Date.now() / 1000; }, -}; +function eventFromEnvelope(env, types) { + let event; + + utils.forEachEnvelopeItem(env, (item, type) => { + if (types.includes(type)) { + event = Array.isArray(item) ? (item )[1] : undefined; + } + // bail out if we found an event + return !!event; + }); + + return event; +} + /** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. + * Creates a transport that overrides the release on all events. */ -function getBrowserPerformance() { - var performance = global_1.getGlobalObject().performance; - if (!performance || !performance.now) { - return undefined; - } - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - var timeOrigin = Date.now() - performance.now(); +function makeOverrideReleaseTransport( + createTransport, + release, +) { + return options => { + const transport = createTransport(options); + return { - now: function () { return performance.now(); }, - timeOrigin: timeOrigin, + ...transport, + send: async (envelope) => { + const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']); + + if (event) { + event.release = release; + } + return transport.send(envelope); + }, }; + }; } -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); - return perfHooks.performance; - } - catch (_) { - return undefined; - } + +/** Overrides the DSN in the envelope header */ +function overrideDsn(envelope, dsn) { + return utils.createEnvelope( + dsn + ? { + ...envelope[0], + dsn, + } + : envelope[0], + envelope[1], + ); } + /** - * The Performance API implementation for the current platform, if available. - */ -var platformPerformance = node_1.isNodeEnv() ? getNodePerformance() : getBrowserPerformance(); -var timestampSource = platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, - }; -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. + * Creates a transport that can send events to different DSNs depending on the envelope contents. */ -exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -// Re-exported with an old name for backwards-compatibility. -exports.timestampWithMs = exports.timestampInSeconds; -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -exports.usingPerformanceAPI = platformPerformance !== undefined; -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -exports.browserPerformanceTimeOrigin = (function () { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. - var performance = global_1.getGlobalObject().performance; - if (!performance || !performance.now) { - exports._browserPerformanceTimeOriginMode = 'none'; - return undefined; - } - var threshold = 3600 * 1000; - var performanceNow = performance.now(); - var dateNow = Date.now(); - // if timeOrigin isn't available set delta to threshold so it isn't used - var timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - var timeOriginIsReliable = timeOriginDelta < threshold; - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - var navigationStart = performance.timing && performance.timing.navigationStart; - var hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - var navigationStartIsReliable = navigationStartDelta < threshold; - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - exports._browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } - else { - exports._browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; +function makeMultiplexedTransport( + createTransport, + matcher, +) { + return options => { + const fallbackTransport = createTransport(options); + const otherTransports = new Map(); + + function getTransport(dsn, release) { + // We create a transport for every unique dsn/release combination as there may be code from multiple releases in + // use at the same time + const key = release ? `${dsn}:${release}` : dsn; + + let transport = otherTransports.get(key); + + if (!transport) { + const validatedDsn = utils.dsnFromString(dsn); + if (!validatedDsn) { + return undefined; } + + const url = api.getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel); + + transport = release + ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url }) + : createTransport({ ...options, url }); + + otherTransports.set(key, transport); + } + + return [dsn, transport]; } - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - exports._browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); -//# sourceMappingURL=time.js.map + + async function send(envelope) { + function getEvent(types) { + const eventTypes = types && types.length ? types : ['event']; + return eventFromEnvelope(envelope, eventTypes); + } + + const transports = matcher({ envelope, getEvent }) + .map(result => { + if (typeof result === 'string') { + return getTransport(result, undefined); + } else { + return getTransport(result.dsn, result.release); + } + }) + .filter((t) => !!t); + + // If we have no transports to send to, use the fallback transport + if (transports.length === 0) { + // Don't override the DSN in the header for the fallback transport. '' is falsy + transports.push(['', fallbackTransport]); + } + + const results = await Promise.all( + transports.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn))), + ); + + return results[0]; + } + + async function flush(timeout) { + const promises = [await fallbackTransport.flush(timeout)]; + for (const [, transport] of otherTransports) { + promises.push(await transport.flush(timeout)); + } + + return promises.every(r => r); + } + + return { + send, + flush, + }; + }; +} + +exports.eventFromEnvelope = eventFromEnvelope; +exports.makeMultiplexedTransport = makeMultiplexedTransport; +//# sourceMappingURL=multiplexed.js.map + /***/ }), -/***/ 66850: -/***/ ((__unused_webpack_module, exports) => { +/***/ 91386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$'); + +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(44220); + +const MIN_DELAY = 100; // 100 ms +const START_DELAY = 5000; // 5 seconds +const MAX_DELAY = 3.6e6; // 1 hour + +function log(msg, error) { + debugBuild.DEBUG_BUILD && utils.logger.info(`[Offline]: ${msg}`, error); +} + /** - * Extract transaction context data from a `sentry-trace` header. - * - * @param traceparent Traceparent string + * Wraps a transport and stores and retries events when they fail to send. * - * @returns Object containing data from the header, or undefined if traceparent string is malformed + * @param createTransport The transport to wrap. */ -function extractTraceparentData(traceparent) { - var matches = traceparent.match(exports.TRACEPARENT_REGEXP); - if (matches) { - var parentSampled = void 0; - if (matches[3] === '1') { - parentSampled = true; +function makeOfflineTransport( + createTransport, +) { + return options => { + const transport = createTransport(options); + const store = options.createStore ? options.createStore(options) : undefined; + + let retryDelay = START_DELAY; + let flushTimer; + + function shouldQueue(env, error, retryDelay) { + // We don't queue Session Replay envelopes because they are: + // - Ordered and Replay relies on the response status to know when they're successfully sent. + // - Likely to fill the queue quickly and block other events from being sent. + // We also want to drop client reports because they can be generated when we retry sending events while offline. + if (utils.envelopeContainsItemType(env, ['replay_event', 'replay_recording', 'client_report'])) { + return false; + } + + if (options.shouldStore) { + return options.shouldStore(env, error, retryDelay); + } + + return true; + } + + function flushIn(delay) { + if (!store) { + return; + } + + if (flushTimer) { + clearTimeout(flushTimer ); + } + + flushTimer = setTimeout(async () => { + flushTimer = undefined; + + const found = await store.pop(); + if (found) { + log('Attempting to send previously queued event'); + void send(found).catch(e => { + log('Failed to retry sending', e); + }); + } + }, delay) ; + + // We need to unref the timer in node.js, otherwise the node process never exit. + if (typeof flushTimer !== 'number' && flushTimer.unref) { + flushTimer.unref(); + } + } + + function flushWithBackOff() { + if (flushTimer) { + return; + } + + flushIn(retryDelay); + + retryDelay = Math.min(retryDelay * 2, MAX_DELAY); + } + + async function send(envelope) { + try { + const result = await transport.send(envelope); + + let delay = MIN_DELAY; + + if (result) { + // If there's a retry-after header, use that as the next delay. + if (result.headers && result.headers['retry-after']) { + delay = utils.parseRetryAfterHeader(result.headers['retry-after']); + } // If we have a server error, return now so we don't flush the queue. + else if ((result.statusCode || 0) >= 400) { + return result; + } } - else if (matches[3] === '0') { - parentSampled = false; + + flushIn(delay); + retryDelay = START_DELAY; + return result; + } catch (e) { + if (store && (await shouldQueue(envelope, e , retryDelay))) { + await store.insert(envelope); + flushWithBackOff(); + log('Error sending. Event queued', e ); + return {}; + } else { + throw e; } - return { - traceId: matches[1], - parentSampled: parentSampled, - parentSpanId: matches[2], - }; + } } - return undefined; + + if (options.flushAtStartup) { + flushWithBackOff(); + } + + return { + send, + flush: t => transport.flush(t), + }; + }; } -exports.extractTraceparentData = extractTraceparentData; -//# sourceMappingURL=tracing.js.map -/***/ }), +exports.MIN_DELAY = MIN_DELAY; +exports.START_DELAY = START_DELAY; +exports.makeOfflineTransport = makeOfflineTransport; +//# sourceMappingURL=offline.js.map -/***/ 83633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ }), + +/***/ 47103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(25304); +const dynamicSamplingContext = __nccwpck_require__(65372); +const getRootSpan = __nccwpck_require__(55660); +const spanUtils = __nccwpck_require__(19925); /** - * Module dependencies. - * @private + * Applies data from the scope to the event and runs all event processors on it. */ +function applyScopeDataToEvent(event, data) { + const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data; -var Negotiator = __nccwpck_require__(95385) -var mime = __nccwpck_require__(43583) + // Apply general data + applyDataToEvent(event, data); -/** - * Module exports. - * @public - */ + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relies on that. + if (span) { + applySpanToEvent(event, span); + } -module.exports = Accepts + applyFingerprintToEvent(event, fingerprint); + applyBreadcrumbsToEvent(event, breadcrumbs); + applySdkMetadataToEvent(event, sdkProcessingMetadata); +} -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ +/** Merge data of two scopes together. */ +function mergeScopeData(data, mergeData) { + const { + extra, + tags, + user, + contexts, + level, + sdkProcessingMetadata, + breadcrumbs, + fingerprint, + eventProcessors, + attachments, + propagationContext, + // eslint-disable-next-line deprecation/deprecation + transactionName, + span, + } = mergeData; -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) + mergeAndOverwriteScopeData(data, 'extra', extra); + mergeAndOverwriteScopeData(data, 'tags', tags); + mergeAndOverwriteScopeData(data, 'user', user); + mergeAndOverwriteScopeData(data, 'contexts', contexts); + mergeAndOverwriteScopeData(data, 'sdkProcessingMetadata', sdkProcessingMetadata); + + if (level) { + data.level = level; } - this.headers = req.headers - this.negotiator = new Negotiator(req) + if (transactionName) { + // eslint-disable-next-line deprecation/deprecation + data.transactionName = transactionName; + } + + if (span) { + data.span = span; + } + + if (breadcrumbs.length) { + data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs]; + } + + if (fingerprint.length) { + data.fingerprint = [...data.fingerprint, ...fingerprint]; + } + + if (eventProcessors.length) { + data.eventProcessors = [...data.eventProcessors, ...eventProcessors]; + } + + if (attachments.length) { + data.attachments = [...data.attachments, ...attachments]; + } + + data.propagationContext = { ...data.propagationContext, ...propagationContext }; } /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" - * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public + * Merges certain scope data. Undefined values will overwrite any existing values. + * Exported only for tests. */ +function mergeAndOverwriteScopeData -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] +(data, prop, mergeVal) { + if (mergeVal && Object.keys(mergeVal).length) { + // Clone object + data[prop] = { ...data[prop] }; + for (const key in mergeVal) { + if (Object.prototype.hasOwnProperty.call(mergeVal, key)) { + data[prop][key] = mergeVal[key]; + } } } +} - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() +function applyDataToEvent(event, data) { + const { + extra, + tags, + user, + contexts, + level, + // eslint-disable-next-line deprecation/deprecation + transactionName, + } = data; + + const cleanedExtra = utils.dropUndefinedKeys(extra); + if (cleanedExtra && Object.keys(cleanedExtra).length) { + event.extra = { ...cleanedExtra, ...event.extra }; } - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] + const cleanedTags = utils.dropUndefinedKeys(tags); + if (cleanedTags && Object.keys(cleanedTags).length) { + event.tags = { ...cleanedTags, ...event.tags }; } - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] + const cleanedUser = utils.dropUndefinedKeys(user); + if (cleanedUser && Object.keys(cleanedUser).length) { + event.user = { ...cleanedUser, ...event.user }; + } - return first - ? types[mimes.indexOf(first)] - : false + const cleanedContexts = utils.dropUndefinedKeys(contexts); + if (cleanedContexts && Object.keys(cleanedContexts).length) { + event.contexts = { ...cleanedContexts, ...event.contexts }; + } + + if (level) { + event.level = level; + } + + if (transactionName) { + event.transaction = transactionName; + } } -/** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public - */ +function applyBreadcrumbsToEvent(event, breadcrumbs) { + const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs]; + event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined; +} -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ +function applySdkMetadataToEvent(event, sdkProcessingMetadata) { + event.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + ...sdkProcessingMetadata, + }; +} - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] +function applySpanToEvent(event, span) { + event.contexts = { trace: spanUtils.spanToTraceContext(span), ...event.contexts }; + const rootSpan = getRootSpan.getRootSpan(span); + if (rootSpan) { + event.sdkProcessingMetadata = { + dynamicSamplingContext: dynamicSamplingContext.getDynamicSamplingContextFromSpan(span), + ...event.sdkProcessingMetadata, + }; + const transactionName = spanUtils.spanToJSON(rootSpan).description; + if (transactionName) { + event.tags = { transaction: transactionName, ...event.tags }; } } +} - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() +/** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ +function applyFingerprintToEvent(event, fingerprint) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint ? utils.arrayify(event.fingerprint) : []; + + // If we have something on the scope, then merge it with event + if (fingerprint) { + event.fingerprint = event.fingerprint.concat(fingerprint); } - return this.negotiator.encodings(encodings)[0] || false + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; + } } +exports.applyScopeDataToEvent = applyScopeDataToEvent; +exports.mergeAndOverwriteScopeData = mergeAndOverwriteScopeData; +exports.mergeScopeData = mergeScopeData; +//# sourceMappingURL=applyScopeDataToEvent.js.map + + +/***/ }), + +/***/ 55660: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + /** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: + * Returns the root span of a given span. * - * ['utf-8', 'utf-7', 'iso-8859-1'] + * As long as we use `Transaction`s internally, the returned root span + * will be a `Transaction` but be aware that this might change in the future. * - * @param {String|Array} charsets... - * @return {String|Array} - * @public + * If the given span has no root span or transaction, `undefined` is returned. */ +function getRootSpan(span) { + // TODO (v8): Remove this check and just return span + // eslint-disable-next-line deprecation/deprecation + return span.transaction; +} -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ +exports.getRootSpan = getRootSpan; +//# sourceMappingURL=getRootSpan.js.map - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } - } - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } +/***/ }), - return this.negotiator.charsets(charsets)[0] || false -} +/***/ 46544: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); /** - * Return accepted languages or best fit based on `langs`. + * Wrap a callback function with error handling. + * If an error is thrown, it will be passed to the `onError` callback and re-thrown. * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] + * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`. * - * @param {String|Array} langs... - * @return {Array|String} - * @public + * If an `onFinally` callback is provided, this will be called when the callback has finished + * - so if it returns a promise, once the promise resolved/rejected, + * else once the callback has finished executing. + * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not. */ +function handleCallbackErrors -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ - - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] - } +( + fn, + onError, + // eslint-disable-next-line @typescript-eslint/no-empty-function + onFinally = () => {}, +) { + let maybePromiseResult; + try { + maybePromiseResult = fn(); + } catch (e) { + onError(e); + onFinally(); + throw e; } - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() + return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally); +} + +/** + * Maybe handle a promise rejection. + * This expects to be given a value that _may_ be a promise, or any other value. + * If it is a promise, and it rejects, it will call the `onError` callback. + * Other than this, it will generally return the given value as-is. + */ +function maybeHandlePromiseRejection( + value, + onError, + onFinally, +) { + if (utils.isThenable(value)) { + // @ts-expect-error - the isThenable check returns the "wrong" type here + return value.then( + res => { + onFinally(); + return res; + }, + e => { + onError(e); + onFinally(); + throw e; + }, + ); } - return this.negotiator.languages(languages)[0] || false + onFinally(); + return value; } +exports.handleCallbackErrors = handleCallbackErrors; +//# sourceMappingURL=handleCallbackErrors.js.map + + +/***/ }), + +/***/ 1295: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const exports$1 = __nccwpck_require__(61117); + +// Treeshakable guard to remove all code related to tracing + /** - * Convert extnames to mime. + * Determines if tracing is currently enabled. * - * @param {String} type - * @return {String} - * @private + * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. */ +function hasTracingEnabled( + maybeOptions, +) { + if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) { + return false; + } -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type + const client = exports$1.getClient(); + const options = maybeOptions || (client && client.getOptions()); + return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options); } +exports.hasTracingEnabled = hasTracingEnabled; +//# sourceMappingURL=hasTracingEnabled.js.map + + +/***/ }), + +/***/ 27687: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + /** - * Check if mime is valid. + * Checks whether given url points to Sentry server + * @param url url to verify * - * @param {String} type - * @return {String} - * @private + * TODO(v8): Remove Hub fallback type */ +// eslint-disable-next-line deprecation/deprecation +function isSentryRequestUrl(url, hubOrClient) { + const client = + hubOrClient && isHub(hubOrClient) + ? // eslint-disable-next-line deprecation/deprecation + hubOrClient.getClient() + : hubOrClient; + const dsn = client && client.getDsn(); + const tunnel = client && client.getOptions().tunnel; -function validMime (type) { - return typeof type === 'string' + return checkDsn(url, dsn) || checkTunnel(url, tunnel); } +function checkTunnel(url, tunnel) { + if (!tunnel) { + return false; + } -/***/ }), - -/***/ 49690: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + return removeTrailingSlash(url) === removeTrailingSlash(tunnel); +} -"use strict"; +function checkDsn(url, dsn) { + return dsn ? url.includes(dsn.host) : false; +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __nccwpck_require__(82361); -const debug_1 = __importDefault(__nccwpck_require__(98282)); -const promisify_1 = __importDefault(__nccwpck_require__(66570)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +function removeTrailingSlash(str) { + return str[str.length - 1] === '/' ? str.slice(0, -1) : str; } -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); + +// eslint-disable-next-line deprecation/deprecation +function isHub(hubOrClient) { + // eslint-disable-next-line deprecation/deprecation + return (hubOrClient ).getClient !== undefined; } -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } - } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map + +exports.isSentryRequestUrl = isSentryRequestUrl; +//# sourceMappingURL=isSentryRequestUrl.js.map + /***/ }), -/***/ 66570: +/***/ 98877: /***/ ((__unused_webpack_module, exports) => { -"use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); - }; + +/** + * Tagged template function which returns paramaterized representation of the message + * For example: parameterize`This is a log statement with ${x} and ${y} params`, would return: + * "__sentry_template_string__": 'This is a log statement with %s and %s params', + * "__sentry_template_values__": ['first', 'second'] + * @param strings An array of string values splitted between expressions + * @param values Expressions extracted from template string + * @returns String with template information in __sentry_template_string__ and __sentry_template_values__ properties + */ +function parameterize(strings, ...values) { + const formatted = new String(String.raw(strings, ...values)) ; + formatted.__sentry_template_string__ = strings.join('\x00').replace(/%/g, '%%').replace(/\0/g, '%s'); + formatted.__sentry_template_values__ = values; + return formatted; } -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map + +exports.parameterize = parameterize; +//# sourceMappingURL=parameterize.js.map + /***/ }), -/***/ 24332: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 64867: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* eslint-env browser */ +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const utils = __nccwpck_require__(25304); +const constants = __nccwpck_require__(647); +const eventProcessors = __nccwpck_require__(57155); +const scope = __nccwpck_require__(80022); +const applyScopeDataToEvent = __nccwpck_require__(47103); +const spanUtils = __nccwpck_require__(19925); /** - * This is the web browser implementation of `debug()`. + * This type makes sure that we get either a CaptureContext, OR an EventHint. + * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed: + * { user: { id: '123' }, mechanism: { handled: false } } */ -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - /** - * Colors. + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. + * @hidden */ +function prepareEvent( + options, + event, + hint, + scope$1, + client, + isolationScope, +) { + const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options; + const prepared = { + ...event, + event_id: event.event_id || hint.event_id || utils.uuid4(), + timestamp: event.timestamp || utils.dateTimestampInSeconds(), + }; + const integrations = hint.integrations || options.integrations.map(i => i.name); -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + applyClientOptions(prepared, options); + applyIntegrationsMetadata(prepared, integrations); + + // Only put debug IDs onto frames for error events. + if (event.type === undefined) { + applyDebugIds(prepared, options.stackParser); + } + + // If we have scope given to us, use it as the base for further modifications. + // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. + const finalScope = getFinalScope(scope$1, hint.captureContext); + + if (hint.mechanism) { + utils.addExceptionMechanism(prepared, hint.mechanism); + } + + const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : []; + + // This should be the last thing called, since we want that + // {@link Hub.addEventProcessor} gets the finished prepared event. + // Merge scope data together + const data = scope.getGlobalScope().getScopeData(); + + if (isolationScope) { + const isolationData = isolationScope.getScopeData(); + applyScopeDataToEvent.mergeScopeData(data, isolationData); + } + + if (finalScope) { + const finalScopeData = finalScope.getScopeData(); + applyScopeDataToEvent.mergeScopeData(data, finalScopeData); + } + + const attachments = [...(hint.attachments || []), ...data.attachments]; + if (attachments.length) { + hint.attachments = attachments; + } + + applyScopeDataToEvent.applyScopeDataToEvent(prepared, data); + + // TODO (v8): Update this order to be: Global > Client > Scope + const eventProcessors$1 = [ + ...clientEventProcessors, + // eslint-disable-next-line deprecation/deprecation + ...eventProcessors.getGlobalEventProcessors(), + // Run scope event processors _after_ all other processors + ...data.eventProcessors, + ]; + + const result = eventProcessors.notifyEventProcessors(eventProcessors$1, prepared, hint); + + return result.then(evt => { + if (evt) { + // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified + // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed. + // This should not cause any PII issues, since we're only moving data that is already on the event and not adding + // any new data + applyDebugMeta(evt); + } + + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); + } + return evt; + }); +} /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * Enhances event using the client configuration. + * It takes care of all "static" values like environment, release and `dist`, + * as well as truncating overly long values. + * @param event event instance to be enhanced */ +function applyClientOptions(event, options) { + const { environment, release, dist, maxValueLength = 250 } = options; -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + if (!('environment' in event)) { + event.environment = 'environment' in options ? environment : constants.DEFAULT_ENVIRONMENT; + } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + if (event.release === undefined && release !== undefined) { + event.release = release; + } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + if (event.dist === undefined && dist !== undefined) { + event.dist = dist; + } + + if (event.message) { + event.message = utils.truncate(event.message, maxValueLength); + } + + const exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = utils.truncate(exception.value, maxValueLength); + } + + const request = event.request; + if (request && request.url) { + request.url = utils.truncate(request.url, maxValueLength); + } } +const debugIdStackParserCache = new WeakMap(); + /** - * Colorize log arguments if enabled. - * - * @api public + * Puts debug IDs into the stack frames of an error event. */ +function applyDebugIds(event, stackParser) { + const debugIdMap = utils.GLOBAL_OBJ._sentryDebugIds; -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + if (!debugIdMap) { + return; + } - if (!this.useColors) { - return; - } + let debugIdStackFramesCache; + const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser); + if (cachedDebugIdStackFrameCache) { + debugIdStackFramesCache = cachedDebugIdStackFrameCache; + } else { + debugIdStackFramesCache = new Map(); + debugIdStackParserCache.set(stackParser, debugIdStackFramesCache); + } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + // Build a map of filename -> debug_id + const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => { + let parsedStack; + const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace); + if (cachedParsedStack) { + parsedStack = cachedParsedStack; + } else { + parsedStack = stackParser(debugIdStackTrace); + debugIdStackFramesCache.set(debugIdStackTrace, parsedStack); + } - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + for (let i = parsedStack.length - 1; i >= 0; i--) { + const stackFrame = parsedStack[i]; + if (stackFrame.filename) { + acc[stackFrame.filename] = debugIdMap[debugIdStackTrace]; + break; + } + } + return acc; + }, {}); - args.splice(lastC, 0, c); + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values.forEach(exception => { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + exception.stacktrace.frames.forEach(frame => { + if (frame.filename) { + frame.debug_id = filenameDebugIdMap[frame.filename]; + } + }); + }); + } catch (e) { + // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. + } } /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public + * Moves debug IDs from the stack frames of an error event into the debug_meta field. */ -exports.log = console.debug || console.log || (() => {}); +function applyDebugMeta(event) { + // Extract debug IDs and filenames from the stack frames on the event. + const filenameDebugIdMap = {}; + try { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values.forEach(exception => { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + exception.stacktrace.frames.forEach(frame => { + if (frame.debug_id) { + if (frame.abs_path) { + filenameDebugIdMap[frame.abs_path] = frame.debug_id; + } else if (frame.filename) { + filenameDebugIdMap[frame.filename] = frame.debug_id; + } + delete frame.debug_id; + } + }); + }); + } catch (e) { + // To save bundle size we're just try catching here instead of checking for the existence of all the different objects. + } + + if (Object.keys(filenameDebugIdMap).length === 0) { + return; + } + + // Fill debug_meta information + event.debug_meta = event.debug_meta || {}; + event.debug_meta.images = event.debug_meta.images || []; + const images = event.debug_meta.images; + Object.keys(filenameDebugIdMap).forEach(filename => { + images.push({ + type: 'sourcemap', + code_file: filename, + debug_id: filenameDebugIdMap[filename], + }); + }); +} /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * This function adds all used integrations to the SDK info in the event. + * @param event The event that will be filled with all integrations. */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function applyIntegrationsMetadata(event, integrationNames) { + if (integrationNames.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames]; + } } /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. + * Normalized keys: + * - `breadcrumbs.data` + * - `user` + * - `contexts` + * - `extra` + * @param event Event + * @returns Normalized event */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function normalizeEvent(event, depth, maxBreadth) { + if (!event) { + return null; + } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + const normalized = { + ...event, + ...(event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map(b => ({ + ...b, + ...(b.data && { + data: utils.normalize(b.data, depth, maxBreadth), + }), + })), + }), + ...(event.user && { + user: utils.normalize(event.user, depth, maxBreadth), + }), + ...(event.contexts && { + contexts: utils.normalize(event.contexts, depth, maxBreadth), + }), + ...(event.extra && { + extra: utils.normalize(event.extra, depth, maxBreadth), + }), + }; - return r; + // event.contexts.trace stores information about a Transaction. Similarly, + // event.spans[] stores information about child Spans. Given that a + // Transaction is conceptually a Span, normalization should apply to both + // Transactions and Spans consistently. + // For now the decision is to skip normalization of Transactions and Spans, + // so this block overwrites the normalized event to add back the original + // Transaction information prior to normalization. + if (event.contexts && event.contexts.trace && normalized.contexts) { + normalized.contexts.trace = event.contexts.trace; + + // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it + if (event.contexts.trace.data) { + normalized.contexts.trace.data = utils.normalize(event.contexts.trace.data, depth, maxBreadth); + } + } + + // event.spans[].data may contain circular/dangerous data so we need to normalize it + if (event.spans) { + normalized.spans = event.spans.map(span => { + const data = spanUtils.spanToJSON(span).data; + + if (data) { + // This is a bit weird, as we generally have `Span` instances here, but to be safe we do not assume so + // eslint-disable-next-line deprecation/deprecation + span.data = utils.normalize(data, depth, maxBreadth); + } + + return span; + }); + } + + return normalized; +} + +function getFinalScope(scope$1, captureContext) { + if (!captureContext) { + return scope$1; + } + + const finalScope = scope$1 ? scope$1.clone() : new scope.Scope(); + finalScope.update(captureContext); + return finalScope; } /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`. + * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`. */ +function parseEventHintOrCaptureContext( + hint, +) { + if (!hint) { + return undefined; + } -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext + if (hintIsScopeOrFunction(hint)) { + return { captureContext: hint }; + } + + if (hintIsScopeContext(hint)) { + return { + captureContext: hint, + }; + } + + return hint; } -module.exports = __nccwpck_require__(46548)(exports); +function hintIsScopeOrFunction( + hint, +) { + return hint instanceof scope.Scope || typeof hint === 'function'; +} -const {formatters} = module.exports; +const captureContextKeys = [ + 'user', + 'level', + 'extra', + 'contexts', + 'tags', + 'fingerprint', + 'requestSession', + 'propagationContext', +] ; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +function hintIsScopeContext(hint) { + return Object.keys(hint).some(key => captureContextKeys.includes(key )); +} -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; +exports.applyDebugIds = applyDebugIds; +exports.applyDebugMeta = applyDebugMeta; +exports.parseEventHintOrCaptureContext = parseEventHintOrCaptureContext; +exports.prepareEvent = prepareEvent; +//# sourceMappingURL=prepareEvent.js.map /***/ }), -/***/ 46548: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 30169: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const version = __nccwpck_require__(53986); /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * A builder for the SDK metadata in the options for the SDK initialization. + * + * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit. + * We don't extract it for bundle size reasons. + * @see https://github.com/getsentry/sentry-javascript/pull/7404 + * @see https://github.com/getsentry/sentry-javascript/pull/4196 + * + * If you make changes to this function consider updating the others as well. + * + * @param options SDK options object that gets mutated + * @param names list of package names */ +function applySdkMetadata(options, name, names = [name], source = 'npm') { + const metadata = options._metadata || {}; -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(62188); - createDebug.destroy = destroy; + if (!metadata.sdk) { + metadata.sdk = { + name: `sentry.javascript.${name}`, + packages: names.map(name => ({ + name: `${source}:@sentry/${name}`, + version: version.SDK_VERSION, + })), + version: version.SDK_VERSION, + }; + } - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); + options._metadata = metadata; +} - /** - * The currently active debug mode names, and names to skip. - */ +exports.applySdkMetadata = applySdkMetadata; +//# sourceMappingURL=sdkMetadata.js.map - createDebug.names = []; - createDebug.skips = []; - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +/***/ }), - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +/***/ 19925: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; +const utils = __nccwpck_require__(25304); - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +// These are aligned with OpenTelemetry trace flags +const TRACE_FLAG_NONE = 0x0; +const TRACE_FLAG_SAMPLED = 0x1; - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } +/** + * Convert a span to a trace context, which can be sent as the `trace` context in an event. + */ +function spanToTraceContext(span) { + const { spanId: span_id, traceId: trace_id } = span.spanContext(); + const { data, op, parent_span_id, status, tags, origin } = spanToJSON(span); - const self = debug; + return utils.dropUndefinedKeys({ + data, + op, + parent_span_id, + span_id, + status, + tags, + trace_id, + origin, + }); +} - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/** + * Convert a Span to a Sentry trace header. + */ +function spanToTraceHeader(span) { + const { traceId, spanId } = span.spanContext(); + const sampled = spanIsSampled(span); + return utils.generateSentryTraceHeader(traceId, spanId, sampled); +} - args[0] = createDebug.coerce(args[0]); +/** + * Convert a span time input intp a timestamp in seconds. + */ +function spanTimeInputToSeconds(input) { + if (typeof input === 'number') { + return ensureTimestampInSeconds(input); + } - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + if (Array.isArray(input)) { + // See {@link HrTime} for the array-based time format + return input[0] + input[1] / 1e9; + } - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + if (input instanceof Date) { + return ensureTimestampInSeconds(input.getTime()); + } - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + return utils.timestampInSeconds(); +} - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +/** + * Converts a timestamp to second, if it was in milliseconds, or keeps it as second. + */ +function ensureTimestampInSeconds(timestamp) { + const isMs = timestamp > 9999999999; + return isMs ? timestamp / 1000 : timestamp; +} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +/** + * Convert a span to a JSON representation. + * Note that all fields returned here are optional and need to be guarded against. + * + * Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json). + * This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility. + * And `spanToJSON` needs the Span class from `span.ts` to check here. + * TODO v8: When we remove the deprecated stuff from `span.ts`, we can remove the circular dependency again. + */ +function spanToJSON(span) { + if (spanIsSpanClass(span)) { + return span.getSpanJSON(); + } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + // Fallback: We also check for `.toJSON()` here... + // eslint-disable-next-line deprecation/deprecation + if (typeof span.toJSON === 'function') { + // eslint-disable-next-line deprecation/deprecation + return span.toJSON(); + } - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } + return {}; +} - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); +/** + * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof. + * :( So instead we approximate this by checking if it has the `getSpanJSON` method. + */ +function spanIsSpanClass(span) { + return typeof (span ).getSpanJSON === 'function'; +} - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } +/** + * Returns true if a span is sampled. + * In most cases, you should just use `span.isRecording()` instead. + * However, this has a slightly different semantic, as it also returns false if the span is finished. + * So in the case where this distinction is important, use this method. + */ +function spanIsSampled(span) { + // We align our trace flags with the ones OpenTelemetry use + // So we also check for sampled the same way they do. + const { traceFlags } = span.spanContext(); + // eslint-disable-next-line no-bitwise + return Boolean(traceFlags & TRACE_FLAG_SAMPLED); +} - return debug; - } +exports.TRACE_FLAG_NONE = TRACE_FLAG_NONE; +exports.TRACE_FLAG_SAMPLED = TRACE_FLAG_SAMPLED; +exports.spanIsSampled = spanIsSampled; +exports.spanTimeInputToSeconds = spanTimeInputToSeconds; +exports.spanToJSON = spanToJSON; +exports.spanToTraceContext = spanToTraceContext; +exports.spanToTraceHeader = spanToTraceHeader; +//# sourceMappingURL=spanUtils.js.map - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; +/***/ }), - createDebug.names = []; - createDebug.skips = []; +/***/ 53986: +/***/ ((__unused_webpack_module, exports) => { - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +Object.defineProperty(exports, "__esModule", ({ value: true })); - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +const SDK_VERSION = '7.120.2'; - namespaces = split[i].replace(/\*/g, '.*?'); +exports.SDK_VERSION = SDK_VERSION; +//# sourceMappingURL=version.js.map - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +/***/ }), - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } +/***/ 44887: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let i; - let len; +Object.defineProperty(exports, "__esModule", ({ value: true })); - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +const INTEGRATION_NAME = 'CaptureConsole'; - return false; - } +const _captureConsoleIntegration = ((options = {}) => { + const levels = options.levels || utils.CONSOLE_LEVELS; - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + if (!('console' in utils.GLOBAL_OBJ)) { + return; + } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + utils.addConsoleInstrumentationHandler(({ args, level }) => { + if (core.getClient() !== client || !levels.includes(level)) { + return; + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + consoleHandler(args, level); + }); + }, + }; +}) ; - createDebug.enable(createDebug.load()); +const captureConsoleIntegration = core.defineIntegration(_captureConsoleIntegration); - return createDebug; -} +/** + * Send Console API calls as Sentry Events. + * @deprecated Use `captureConsoleIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const CaptureConsole = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + captureConsoleIntegration, +) + +; + +function consoleHandler(args, level) { + const captureContext = { + level: utils.severityLevelFromString(level), + extra: { + arguments: args, + }, + }; -module.exports = setup; + core.withScope(scope => { + scope.addEventProcessor(event => { + event.logger = 'console'; + utils.addExceptionMechanism(event, { + handled: false, + type: 'console', + }); -/***/ }), + return event; + }); -/***/ 98282: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (level === 'assert' && args[0] === false) { + const message = `Assertion failed: ${utils.safeJoin(args.slice(1), ' ') || 'console.assert'}`; + scope.setExtra('arguments', args.slice(1)); + core.captureMessage(message, captureContext); + return; + } -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + const error = args.find(arg => arg instanceof Error); + if (level === 'error' && error) { + core.captureException(error, captureContext); + return; + } -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(24332); -} else { - module.exports = __nccwpck_require__(81284); + const message = utils.safeJoin(args, ' '); + core.captureMessage(message, captureContext); + }); } +exports.CaptureConsole = CaptureConsole; +exports.captureConsoleIntegration = captureConsoleIntegration; +//# sourceMappingURL=captureconsole.js.map + /***/ }), -/***/ 81284: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 34418: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Module dependencies. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); -/** - * This is the Node.js implementation of `debug()`. - */ +const WINDOW = utils.GLOBAL_OBJ ; -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +const DEFAULT_LINES_OF_CONTEXT = 7; -/** - * Colors. - */ +const INTEGRATION_NAME = 'ContextLines'; -exports.colors = [6, 2, 3, 4, 5, 1]; +const _contextLinesIntegration = ((options = {}) => { + const contextLines = options.frameContextLines != null ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + return addSourceContext(event, contextLines); + }, + }; +}) ; - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} +const contextLinesIntegration = core.defineIntegration(_contextLinesIntegration); /** - * Build up the default `inspectOpts` object from the environment variables. + * Collects source context lines around the lines of stackframes pointing to JS embedded in + * the current page's HTML. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * This integration DOES NOT work for stack frames pointing to JS files that are loaded by the browser. + * For frames pointing to files, context lines are added during ingestion and symbolication + * by attempting to download the JS files to the Sentry backend. + * + * Use this integration if you have inline JS code in HTML pages that can't be accessed + * by our backend (e.g. due to a login-protected page). + * + * @deprecated Use `contextLinesIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const ContextLines = core.convertIntegrationFnToClass(INTEGRATION_NAME, contextLinesIntegration) -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); +; /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Processes an event and adds context lines. */ +function addSourceContext(event, contextLines) { + const doc = WINDOW.document; + const htmlFilename = WINDOW.location && utils.stripUrlQueryAndFragment(WINDOW.location.href); + if (!doc || !htmlFilename) { + return event; + } -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + const exceptions = event.exception && event.exception.values; + if (!exceptions || !exceptions.length) { + return event; + } -function formatArgs(args) { - const {namespace: name, useColors} = this; + const html = doc.documentElement.innerHTML; + if (!html) { + return event; + } - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + const htmlLines = ['', '', ...html.split('\n'), '']; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + exceptions.forEach(exception => { + const stacktrace = exception.stacktrace; + if (stacktrace && stacktrace.frames) { + stacktrace.frames = stacktrace.frames.map(frame => + applySourceContextToFrame(frame, htmlLines, htmlFilename, contextLines), + ); + } + }); -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; + return event; } /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Only exported for testing */ +function applySourceContextToFrame( + frame, + htmlLines, + htmlFilename, + linesOfContext, +) { + if (frame.filename !== htmlFilename || !frame.lineno || !htmlLines.length) { + return frame; + } -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} + utils.addContextToFrame(htmlLines, frame, linesOfContext); -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } + return frame; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +exports.ContextLines = ContextLines; +exports.applySourceContextToFrame = applySourceContextToFrame; +exports.contextLinesIntegration = contextLinesIntegration; +//# sourceMappingURL=contextlines.js.map -function load() { - return process.env.DEBUG; -} + +/***/ }), + +/***/ 58456: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Init logic for `debug` instances. + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ +const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); -function init(debug) { - debug.inspectOpts = {}; +exports.DEBUG_BUILD = DEBUG_BUILD; +//# sourceMappingURL=debug-build.js.map - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} -module.exports = __nccwpck_require__(46548)(exports); +/***/ }), -const {formatters} = module.exports; +/***/ 33917: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Map %o to `util.inspect()`, all on a single line. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); + +const INTEGRATION_NAME = 'Debug'; + +const _debugIntegration = ((options = {}) => { + const _options = { + debugger: false, + stringify: false, + ...options, + }; + + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + if (!client.on) { + return; + } + + client.on('beforeSendEvent', (event, hint) => { + if (_options.debugger) { + // eslint-disable-next-line no-debugger + debugger; + } + + /* eslint-disable no-console */ + utils.consoleSandbox(() => { + if (_options.stringify) { + console.log(JSON.stringify(event, null, 2)); + if (hint && Object.keys(hint).length) { + console.log(JSON.stringify(hint, null, 2)); + } + } else { + console.log(event); + if (hint && Object.keys(hint).length) { + console.log(hint); + } + } + }); + /* eslint-enable no-console */ + }); + }, + }; +}) ; + +const debugIntegration = core.defineIntegration(_debugIntegration); /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Integration to debug sent Sentry events. + * This integration should not be used in production. + * + * @deprecated Use `debugIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const Debug = core.convertIntegrationFnToClass(INTEGRATION_NAME, debugIntegration) -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +; + +exports.Debug = Debug; +exports.debugIntegration = debugIntegration; +//# sourceMappingURL=debug.js.map /***/ }), -/***/ 62188: -/***/ ((module) => { +/***/ 44435: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Helpers. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(58456); -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +const INTEGRATION_NAME = 'Dedupe'; -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +const _dedupeIntegration = (() => { + let previousEvent; + + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(currentEvent) { + // We want to ignore any non-error type events, e.g. transactions or replays + // These should never be deduped, and also not be compared against as _previousEvent. + if (currentEvent.type) { + return currentEvent; + } + + // Juuust in case something goes wrong + try { + if (_shouldDropEvent(currentEvent, previousEvent)) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Event dropped due to being a duplicate of previously captured event.'); + return null; + } + } catch (_oO) {} // eslint-disable-line no-empty + + return (previousEvent = currentEvent); + }, + }; +}) ; + +const dedupeIntegration = core.defineIntegration(_dedupeIntegration); /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private + * Deduplication filter. + * @deprecated Use `dedupeIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const Dedupe = core.convertIntegrationFnToClass(INTEGRATION_NAME, dedupeIntegration) -function parse(str) { - str = String(str); - if (str.length > 100) { - return; +; + +/** only exported for tests. */ +function _shouldDropEvent(currentEvent, previousEvent) { + if (!previousEvent) { + return false; } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; + + if (_isSameMessageEvent(currentEvent, previousEvent)) { + return true; } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + + if (_isSameExceptionEvent(currentEvent, previousEvent)) { + return true; } + + return false; } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function _isSameMessageEvent(currentEvent, previousEvent) { + const currentMessage = currentEvent.message; + const previousMessage = previousEvent.message; -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; + // If neither event has a message property, they were both exceptions, so bail out + if (!currentMessage && !previousMessage) { + return false; } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; + + // If only one event has a stacktrace, but not the other one, they are not the same + if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) { + return false; } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; + + if (currentMessage !== previousMessage) { + return false; } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; + + if (!_isSameFingerprint(currentEvent, previousEvent)) { + return false; } - return ms + 'ms'; + + if (!_isSameStacktrace(currentEvent, previousEvent)) { + return false; + } + + return true; } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function _isSameExceptionEvent(currentEvent, previousEvent) { + const previousException = _getExceptionFromEvent(previousEvent); + const currentException = _getExceptionFromEvent(currentEvent); -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); + if (!previousException || !currentException) { + return false; } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); + + if (previousException.type !== currentException.type || previousException.value !== currentException.value) { + return false; } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); + + if (!_isSameFingerprint(currentEvent, previousEvent)) { + return false; } - return ms + ' ms'; -} -/** - * Pluralization helper. - */ + if (!_isSameStacktrace(currentEvent, previousEvent)) { + return false; + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + return true; } +function _isSameStacktrace(currentEvent, previousEvent) { + let currentFrames = _getFramesFromEvent(currentEvent); + let previousFrames = _getFramesFromEvent(previousEvent); -/***/ }), + // If neither event has a stacktrace, they are assumed to be the same + if (!currentFrames && !previousFrames) { + return true; + } -/***/ 61231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // If only one event has a stacktrace, but not the other one, they are not the same + if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) { + return false; + } -"use strict"; + currentFrames = currentFrames ; + previousFrames = previousFrames ; -const indentString = __nccwpck_require__(98043); -const cleanStack = __nccwpck_require__(27972); + // If number of frames differ, they are not the same + if (previousFrames.length !== currentFrames.length) { + return false; + } -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); + // Otherwise, compare the two + for (let i = 0; i < previousFrames.length; i++) { + const frameA = previousFrames[i]; + const frameB = currentFrames[i]; -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } + if ( + frameA.filename !== frameB.filename || + frameA.lineno !== frameB.lineno || + frameA.colno !== frameB.colno || + frameA.function !== frameB.function + ) { + return false; + } + } - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } + return true; +} - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } +function _isSameFingerprint(currentEvent, previousEvent) { + let currentFingerprint = currentEvent.fingerprint; + let previousFingerprint = previousEvent.fingerprint; - return new Error(error); - }); + // If neither event has a fingerprint, they are assumed to be the same + if (!currentFingerprint && !previousFingerprint) { + return true; + } - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); + // If only one event has a fingerprint, but not the other one, they are not the same + if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) { + return false; + } - this.name = 'AggregateError'; + currentFingerprint = currentFingerprint ; + previousFingerprint = previousFingerprint ; - Object.defineProperty(this, '_errors', {value: errors}); - } + // Otherwise, compare the two + try { + return !!(currentFingerprint.join('') === previousFingerprint.join('')); + } catch (_oO) { + return false; + } +} - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } +function _getExceptionFromEvent(event) { + return event.exception && event.exception.values && event.exception.values[0]; } -module.exports = AggregateError; +function _getFramesFromEvent(event) { + const exception = event.exception; + if (exception) { + try { + // @ts-expect-error Object could be undefined + return exception.values[0].stacktrace.frames; + } catch (_oO) { + return undefined; + } + } + return undefined; +} -/***/ }), +exports.Dedupe = Dedupe; +exports._shouldDropEvent = _shouldDropEvent; +exports.dedupeIntegration = dedupeIntegration; +//# sourceMappingURL=dedupe.js.map -/***/ 62003: -/***/ ((module) => { -"use strict"; +/***/ }), +/***/ 51148: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} - */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(58456); - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } +const INTEGRATION_NAME = 'ExtraErrorData'; - return result -} +const _extraErrorDataIntegration = ((options = {}) => { + const depth = options.depth || 3; -/** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} - */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] + // TODO(v8): Flip the default for this option to true + const captureErrorCause = options.captureErrorCause || false; - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event, hint) { + return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause); + }, + }; +}) ; - return result -} +const extraErrorDataIntegration = core.defineIntegration(_extraErrorDataIntegration); /** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} + * Extract additional data for from original exceptions. + * @deprecated Use `extraErrorDataIntegration()` instead. */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) +// eslint-disable-next-line deprecation/deprecation +const ExtraErrorData = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + extraErrorDataIntegration, +) + +; + +function _enhanceEventWithErrorData( + event, + hint = {}, + depth, + captureErrorCause, +) { + if (!hint.originalException || !utils.isError(hint.originalException)) { + return event; } + const exceptionName = (hint.originalException ).name || hint.originalException.constructor.name; - return flattenWithDepth(array, [], depth) -} + const errorData = _extractErrorData(hint.originalException , captureErrorCause); + if (errorData) { + const contexts = { + ...event.contexts, + }; -/***/ }), + const normalizedErrorData = utils.normalize(errorData, depth); -/***/ 86950: -/***/ ((module) => { + if (utils.isPlainObject(normalizedErrorData)) { + // We mark the error data as "already normalized" here, because we don't want other normalization procedures to + // potentially truncate the data we just already normalized, with a certain depth setting. + utils.addNonEnumerableProperty(normalizedErrorData, '__sentry_skip_normalization__', true); + contexts[exceptionName] = normalizedErrorData; + } -"use strict"; + return { + ...event, + contexts, + }; + } + return event; +} -/* global SharedArrayBuffer, Atomics */ +/** + * Extract extra information from the Error object + */ +function _extractErrorData(error, captureErrorCause) { + // We are trying to enhance already existing event, so no harm done if it won't succeed + try { + const nativeKeys = [ + 'name', + 'message', + 'stack', + 'line', + 'column', + 'fileName', + 'lineNumber', + 'columnNumber', + 'toJSON', + ]; -if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { - const nil = new Int32Array(new SharedArrayBuffer(4)) + const extraErrorInfo = {}; - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') + // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway. + for (const key of Object.keys(error)) { + if (nativeKeys.indexOf(key) !== -1) { + continue; } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + const value = error[key]; + extraErrorInfo[key] = utils.isError(value) ? value.toString() : value; } - Atomics.wait(nil, 0, 0, Number(ms)) - } - module.exports = sleep -} else { + // Error.cause is a standard property that is non enumerable, we therefore need to access it separately. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause + if (captureErrorCause && error.cause !== undefined) { + extraErrorInfo.cause = utils.isError(error.cause) ? error.cause.toString() : error.cause; + } - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') + // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that) + if (typeof error.toJSON === 'function') { + const serializedError = error.toJSON() ; + + for (const key of Object.keys(serializedError)) { + const value = serializedError[key]; + extraErrorInfo[key] = utils.isError(value) ? value.toString() : value; } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') } - const target = Date.now() + Number(ms) - while (target > Date.now()){} - } - module.exports = sleep + return extraErrorInfo; + } catch (oO) { + debugBuild.DEBUG_BUILD && utils.logger.error('Unable to extract extra data from the Error object:', oO); + } + return null; } +exports.ExtraErrorData = ExtraErrorData; +exports.extraErrorDataIntegration = extraErrorDataIntegration; +//# sourceMappingURL=extraerrordata.js.map + /***/ }), -/***/ 9417: -/***/ ((module) => { +/***/ 2739: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(58456); - var r = range(a, b, str); +const INTEGRATION_NAME = 'HttpClient'; - 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) +const _httpClientIntegration = ((options = {}) => { + const _options = { + failedRequestStatusCodes: [[500, 599]], + failedRequestTargets: [/.*/], + ...options, }; -} -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + _wrapFetch(client, _options); + _wrapXHR(client, _options); + }, + }; +}) ; -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; +const httpClientIntegration = core.defineIntegration(_httpClientIntegration); - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; - } - begs = []; - left = str.length; +/** + * Create events for failed client side HTTP requests. + * @deprecated Use `httpClientIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const HttpClient = core.convertIntegrationFnToClass(INTEGRATION_NAME, httpClientIntegration) - 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); - } +/** + * Interceptor function for fetch requests + * + * @param requestInfo The Fetch API request info + * @param response The Fetch API response + * @param requestInit The request init object + */ +function _fetchResponseHandler( + options, + requestInfo, + response, + requestInit, +) { + if (_shouldCaptureResponse(options, response.status, response.url)) { + const request = _getRequest(requestInfo, requestInit); - i = ai < bi && ai >= 0 ? ai : bi; - } + let requestHeaders, responseHeaders, requestCookies, responseCookies; + + if (_shouldSendDefaultPii()) { + [{ headers: requestHeaders, cookies: requestCookies }, { headers: responseHeaders, cookies: responseCookies }] = [ + { cookieHeader: 'Cookie', obj: request }, + { cookieHeader: 'Set-Cookie', obj: response }, + ].map(({ cookieHeader, obj }) => { + const headers = _extractFetchHeaders(obj.headers); + let cookies; - if (begs.length) { - result = [ left, right ]; + try { + const cookieString = headers[cookieHeader] || headers[cookieHeader.toLowerCase()] || undefined; + + if (cookieString) { + cookies = _parseCookieString(cookieString); + } + } catch (e) { + debugBuild.DEBUG_BUILD && utils.logger.log(`Could not extract cookies from header ${cookieHeader}`); + } + + return { + headers, + cookies, + }; + }); } - } - return result; -} + const event = _createEvent({ + url: request.url, + method: request.method, + status: response.status, + requestHeaders, + responseHeaders, + requestCookies, + responseCookies, + }); + core.captureEvent(event); + } +} -/***/ }), +/** + * Interceptor function for XHR requests + * + * @param xhr The XHR request + * @param method The HTTP method + * @param headers The HTTP headers + */ +function _xhrResponseHandler( + options, + xhr, + method, + headers, +) { + if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) { + let requestHeaders, responseCookies, responseHeaders; -/***/ 83682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (_shouldSendDefaultPii()) { + try { + const cookieString = xhr.getResponseHeader('Set-Cookie') || xhr.getResponseHeader('set-cookie') || undefined; -var register = __nccwpck_require__(44670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) + if (cookieString) { + responseCookies = _parseCookieString(cookieString); + } + } catch (e) { + debugBuild.DEBUG_BUILD && utils.logger.log('Could not extract cookies from response headers'); + } -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) + try { + responseHeaders = _getXHRResponseHeaders(xhr); + } catch (e) { + debugBuild.DEBUG_BUILD && utils.logger.log('Could not extract headers from response'); + } -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef + requestHeaders = headers; + } - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} + const event = _createEvent({ + url: xhr.responseURL, + method, + status: xhr.status, + requestHeaders, + // Can't access request cookies from XHR + responseHeaders, + responseCookies, + }); -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} + core.captureEvent(event); } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook } -function HookCollection () { - var state = { - registry: {} - } +/** + * Extracts response size from `Content-Length` header when possible + * + * @param headers + * @returns The response size in bytes or undefined + */ +function _getResponseSizeFromHeaders(headers) { + if (headers) { + const contentLength = headers['Content-Length'] || headers['content-length']; - var hook = register.bind(null, state) - bindApi(hook, state) + if (contentLength) { + return parseInt(contentLength, 10); + } + } - return hook + return undefined; } -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true - } - return HookCollection() +/** + * Creates an object containing cookies from the given cookie string + * + * @param cookieString The cookie string to parse + * @returns The parsed cookies + */ +function _parseCookieString(cookieString) { + return cookieString.split('; ').reduce((acc, cookie) => { + const [key, value] = cookie.split('='); + acc[key] = value; + return acc; + }, {}); } -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - +/** + * Extracts the headers as an object from the given Fetch API request or response object + * + * @param headers The headers to extract + * @returns The extracted headers as an object + */ +function _extractFetchHeaders(headers) { + const result = {}; -/***/ }), + headers.forEach((value, key) => { + result[key] = value; + }); -/***/ 5549: -/***/ ((module) => { + return result; +} -module.exports = addHook; +/** + * Extracts the response headers as an object from the given XHR object + * + * @param xhr The XHR object to extract the response headers from + * @returns The response headers as an object + */ +function _getXHRResponseHeaders(xhr) { + const headers = xhr.getAllResponseHeaders(); -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + if (!headers) { + return {}; } - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } + return headers.split('\r\n').reduce((acc, line) => { + const [key, value] = line.split(': '); + acc[key] = value; + return acc; + }, {}); +} - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } +/** + * Checks if the given target url is in the given list of targets + * + * @param target The target url to check + * @returns true if the target url is in the given list of targets, false otherwise + */ +function _isInGivenRequestTargets( + failedRequestTargets, + target, +) { + return failedRequestTargets.some((givenRequestTarget) => { + if (typeof givenRequestTarget === 'string') { + return target.includes(givenRequestTarget); + } - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } + return givenRequestTarget.test(target); + }); +} - state.registry[name].push({ - hook: hook, - orig: orig, +/** + * Checks if the given status code is in the given range + * + * @param status The status code to check + * @returns true if the status code is in the given range, false otherwise + */ +function _isInGivenStatusRanges( + failedRequestStatusCodes, + status, +) { + return failedRequestStatusCodes.some((range) => { + if (typeof range === 'number') { + return range === status; + } + + return status >= range[0] && status <= range[1]; }); } +/** + * Wraps `fetch` function to capture request and response data + */ +function _wrapFetch(client, options) { + if (!utils.supportsNativeFetch()) { + return; + } -/***/ }), + utils.addFetchInstrumentationHandler(handlerData => { + if (core.getClient() !== client) { + return; + } -/***/ 44670: -/***/ ((module) => { + const { response, args } = handlerData; + const [requestInfo, requestInit] = args ; -module.exports = register; + if (!response) { + return; + } -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } + _fetchResponseHandler(options, requestInfo, response , requestInit); + }); +} - if (!options) { - options = {}; +/** + * Wraps XMLHttpRequest to capture request and response data + */ +function _wrapXHR(client, options) { + if (!('XMLHttpRequest' in utils.GLOBAL_OBJ)) { + return; } - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } + utils.addXhrInstrumentationHandler(handlerData => { + if (core.getClient() !== client) { + return; + } - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); + const xhr = handlerData.xhr ; + + const sentryXhrData = xhr[utils.SENTRY_XHR_DATA_KEY]; + + if (!sentryXhrData) { + return; } - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); + const { method, request_headers: headers } = sentryXhrData; + + try { + _xhrResponseHandler(options, xhr, method, headers); + } catch (e) { + debugBuild.DEBUG_BUILD && utils.logger.warn('Error while extracting response event form XHR response', e); + } }); } +/** + * Checks whether to capture given response as an event + * + * @param status response status code + * @param url response url + */ +function _shouldCaptureResponse(options, status, url) { + return ( + _isInGivenStatusRanges(options.failedRequestStatusCodes, status) && + _isInGivenRequestTargets(options.failedRequestTargets, url) && + !core.isSentryRequestUrl(url, core.getClient()) + ); +} -/***/ }), +/** + * Creates a synthetic Sentry event from given response data + * + * @param data response data + * @returns event + */ +function _createEvent(data -/***/ 6819: -/***/ ((module) => { +) { + const message = `HTTP Client Error with status code: ${data.status}`; -module.exports = removeHook; + const event = { + message, + exception: { + values: [ + { + type: 'Error', + value: message, + }, + ], + }, + request: { + url: data.url, + method: data.method, + headers: data.requestHeaders, + cookies: data.requestCookies, + }, + contexts: { + response: { + status_code: data.status, + headers: data.responseHeaders, + cookies: data.responseCookies, + body_size: _getResponseSizeFromHeaders(data.responseHeaders), + }, + }, + }; -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } + utils.addExceptionMechanism(event, { + type: 'http.client', + handled: false, + }); - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); + return event; +} - if (index === -1) { - return; +function _getRequest(requestInfo, requestInit) { + if (!requestInit && requestInfo instanceof Request) { + return requestInfo; } - state.registry[name].splice(index, 1); + // If both are set, we try to construct a new Request with the given arguments + // However, if e.g. the original request has a `body`, this will throw an error because it was already accessed + // In this case, as a fallback, we just use the original request - using both is rather an edge case + if (requestInfo instanceof Request && requestInfo.bodyUsed) { + return requestInfo; + } + + return new Request(requestInfo, requestInit); } +function _shouldSendDefaultPii() { + const client = core.getClient(); + return client ? Boolean(client.getOptions().sendDefaultPii) : false; +} -/***/ }), +exports.HttpClient = HttpClient; +exports.httpClientIntegration = httpClientIntegration; +//# sourceMappingURL=httpclient.js.map -/***/ 97076: -/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ }), +/***/ 54506: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Module dependencies. - * @private - */ +const captureconsole = __nccwpck_require__(44887); +const debug = __nccwpck_require__(33917); +const dedupe = __nccwpck_require__(44435); +const extraerrordata = __nccwpck_require__(51148); +const offline = __nccwpck_require__(57581); +const reportingobserver = __nccwpck_require__(49022); +const rewriteframes = __nccwpck_require__(15788); +const sessiontiming = __nccwpck_require__(15700); +const transaction = __nccwpck_require__(22190); +const httpclient = __nccwpck_require__(2739); +const contextlines = __nccwpck_require__(34418); + + + +exports.CaptureConsole = captureconsole.CaptureConsole; +exports.captureConsoleIntegration = captureconsole.captureConsoleIntegration; +exports.Debug = debug.Debug; +exports.debugIntegration = debug.debugIntegration; +exports.Dedupe = dedupe.Dedupe; +exports.dedupeIntegration = dedupe.dedupeIntegration; +exports.ExtraErrorData = extraerrordata.ExtraErrorData; +exports.extraErrorDataIntegration = extraerrordata.extraErrorDataIntegration; +exports.Offline = offline.Offline; +exports.ReportingObserver = reportingobserver.ReportingObserver; +exports.reportingObserverIntegration = reportingobserver.reportingObserverIntegration; +exports.RewriteFrames = rewriteframes.RewriteFrames; +exports.rewriteFramesIntegration = rewriteframes.rewriteFramesIntegration; +exports.SessionTiming = sessiontiming.SessionTiming; +exports.sessionTimingIntegration = sessiontiming.sessionTimingIntegration; +exports.Transaction = transaction.Transaction; +exports.HttpClient = httpclient.HttpClient; +exports.httpClientIntegration = httpclient.httpClientIntegration; +exports.ContextLines = contextlines.ContextLines; +exports.contextLinesIntegration = contextlines.contextLinesIntegration; +//# sourceMappingURL=index.js.map -var deprecate = __nccwpck_require__(18883)('body-parser') -/** - * Cache of loaded parsers. - * @private - */ +/***/ }), -var parsers = Object.create(null) +/***/ 57581: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Module exports. - * @type {Parsers} - */ +const utils = __nccwpck_require__(25304); +const localForage = __nccwpck_require__(64795); +const debugBuild = __nccwpck_require__(58456); -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') +const WINDOW = utils.GLOBAL_OBJ ; /** - * JSON parser. - * @public + * cache offline errors and send when connected + * @deprecated The offline integration has been deprecated in favor of the offline transport wrapper. + * + * http://docs.sentry.io/platforms/javascript/configuration/transports/#offline-caching */ +class Offline { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Offline';} -Object.defineProperty(exports, "json", ({ - configurable: true, - enumerable: true, - get: createParserGetter('json') -})) + /** + * @inheritDoc + */ -/** - * Raw parser. - * @public - */ + /** + * the current hub instance + */ -Object.defineProperty(exports, "raw", ({ - configurable: true, - enumerable: true, - get: createParserGetter('raw') -})) + /** + * maximum number of events to store while offline + */ -/** - * Text parser. - * @public - */ + /** + * event cache + */ -Object.defineProperty(exports, "text", ({ - configurable: true, - enumerable: true, - get: createParserGetter('text') -})) + /** + * @inheritDoc + */ + constructor(options = {}) { + this.name = Offline.id; -/** - * URL-encoded parser. - * @public - */ + this.maxStoredEvents = options.maxStoredEvents || 30; // set a reasonable default + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + this.offlineEventStore = localForage.createInstance({ + name: 'sentry/offlineEventStore', + }); + } -Object.defineProperty(exports, "urlencoded", ({ - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -})) + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + this.hub = getCurrentHub(); -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ + if ('addEventListener' in WINDOW) { + WINDOW.addEventListener('online', () => { + void this._sendEvents().catch(() => { + debugBuild.DEBUG_BUILD && utils.logger.warn('could not send cached events'); + }); + }); + } -function bodyParser (options) { - var opts = {} + const eventProcessor = event => { + // eslint-disable-next-line deprecation/deprecation + if (this.hub && this.hub.getIntegration(Offline)) { + // cache if we are positively offline + if ('navigator' in WINDOW && 'onLine' in WINDOW.navigator && !WINDOW.navigator.onLine) { + debugBuild.DEBUG_BUILD && utils.logger.log('Event dropped due to being a offline - caching instead'); - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] + void this._cacheEvent(event) + .then((_event) => this._enforceMaxEvents()) + .catch((_error) => { + debugBuild.DEBUG_BUILD && utils.logger.warn('could not cache event while offline'); + }); + + // return null on success or failure, because being offline will still result in an error + return null; + } } + + return event; + }; + + eventProcessor.id = this.name; + addGlobalEventProcessor(eventProcessor); + + // if online now, send any events stored in a previous offline session + if ('navigator' in WINDOW && 'onLine' in WINDOW.navigator && WINDOW.navigator.onLine) { + void this._sendEvents().catch(() => { + debugBuild.DEBUG_BUILD && utils.logger.warn('could not send cached events'); + }); } } - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) + /** + * cache an event to send later + * @param event an event + */ + async _cacheEvent(event) { + return this.offlineEventStore.setItem(utils.uuid4(), utils.normalize(event)); + } - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} - -/** - * Create a getter for loading a parser. - * @private - */ + /** + * purge excess events if necessary + */ + async _enforceMaxEvents() { + const events = []; -function createParserGetter (name) { - return function get () { - return loadParser(name) + return this.offlineEventStore + .iterate((event, cacheKey, _index) => { + // aggregate events + events.push({ cacheKey, event }); + }) + .then( + () => + // this promise resolves when the iteration is finished + this._purgeEvents( + // purge all events past maxStoredEvents in reverse chronological order + events + .sort((a, b) => (b.event.timestamp || 0) - (a.event.timestamp || 0)) + .slice(this.maxStoredEvents < events.length ? this.maxStoredEvents : events.length) + .map(event => event.cacheKey), + ), + ) + .catch((_error) => { + debugBuild.DEBUG_BUILD && utils.logger.warn('could not enforce max events'); + }); } -} - -/** - * Load a parser module. - * @private - */ -function loadParser (parserName) { - var parser = parsers[parserName] + /** + * purge event from cache + */ + async _purgeEvent(cacheKey) { + return this.offlineEventStore.removeItem(cacheKey); + } - if (parser !== undefined) { - return parser + /** + * purge events from cache + */ + async _purgeEvents(cacheKeys) { + // trail with .then to ensure the return type as void and not void|void[] + return Promise.all(cacheKeys.map(cacheKey => this._purgeEvent(cacheKey))).then(); } - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = __nccwpck_require__(20859) - break - case 'raw': - parser = __nccwpck_require__(49609) - break - case 'text': - parser = __nccwpck_require__(26382) - break - case 'urlencoded': - parser = __nccwpck_require__(76100) - break + /** + * send all events + */ + async _sendEvents() { + return this.offlineEventStore.iterate((event, cacheKey, _index) => { + if (this.hub) { + this.hub.captureEvent(event); + + void this._purgeEvent(cacheKey).catch((_error) => { + debugBuild.DEBUG_BUILD && utils.logger.warn('could not purge event from cache'); + }); + } else { + debugBuild.DEBUG_BUILD && utils.logger.warn('no hub found - could not send cached event'); + } + }); } +} Offline.__initStatic(); - // store to prevent invoking require() - return (parsers[parserName] = parser) -} +exports.Offline = Offline; +//# sourceMappingURL=offline.js.map /***/ }), -/***/ 88862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 49022: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const WINDOW = utils.GLOBAL_OBJ ; -/** - * Module dependencies. - * @private - */ +const INTEGRATION_NAME = 'ReportingObserver'; -var createError = __nccwpck_require__(95193) -var getBody = __nccwpck_require__(47742) -var iconv = __nccwpck_require__(19032) -var onFinished = __nccwpck_require__(24694) -var zlib = __nccwpck_require__(59796) +const SETUP_CLIENTS = new WeakMap(); -/** - * Module exports. - */ +const _reportingObserverIntegration = ((options = {}) => { + const types = options.types || ['crash', 'deprecation', 'intervention']; -module.exports = read + /** Handler for the reporting observer. */ + function handler(reports) { + if (!SETUP_CLIENTS.has(core.getClient() )) { + return; + } -/** - * Read a request into a buffer and parse. - * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private - */ + for (const report of reports) { + core.withScope(scope => { + scope.setExtra('url', report.url); -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream + const label = `ReportingObserver [${report.type}]`; + let details = 'No details available'; - // flag as parsed - req._body = true + if (report.body) { + // Object.keys doesn't work on ReportBody, as all properties are inheirted + const plainBody - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify + = {}; - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } + // eslint-disable-next-line guard-for-in + for (const prop in report.body) { + plainBody[prop] = report.body[prop]; + } - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding + scope.setExtra('body', plainBody); - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } + if (report.type === 'crash') { + const body = report.body ; + // A fancy way to create a message out of crashId OR reason OR both OR fallback + details = [body.crashId || '', body.reason || ''].join(' ').trim() || details; + } else { + const body = report.body ; + details = body.message || details; + } + } - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error + core.captureMessage(`${label}: ${details}`); + }); + } + } - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) + return { + name: INTEGRATION_NAME, + setupOnce() { + if (!utils.supportsReportingObserver()) { + return; } - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + const observer = new (WINDOW ).ReportingObserver(handler, { + buffered: true, + types, + }); - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return - } - } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + observer.observe(); + }, - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return - } + setup(client) { + SETUP_CLIENTS.set(client, true); + }, + }; +}) ; - next() - }) -} +const reportingObserverIntegration = core.defineIntegration(_reportingObserverIntegration); /** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private + * Reporting API integration - https://w3c.github.io/reporting/ + * @deprecated Use `reportingObserverIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const ReportingObserver = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + reportingObserverIntegration, +) -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream +; - debug('content-encoding "%s"', encoding) +exports.ReportingObserver = ReportingObserver; +exports.reportingObserverIntegration = reportingObserverIntegration; +//# sourceMappingURL=reportingobserver.js.map - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) + +/***/ }), + +/***/ 15788: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); + +const INTEGRATION_NAME = 'RewriteFrames'; + +const _rewriteFramesIntegration = ((options = {}) => { + const root = options.root; + const prefix = options.prefix || 'app:///'; + + const iteratee = + options.iteratee || + ((frame) => { + if (!frame.filename) { + return frame; + } + // Determine if this is a Windows frame by checking for a Windows-style prefix such as `C:\` + const isWindowsFrame = + /^[a-zA-Z]:\\/.test(frame.filename) || + // or the presence of a backslash without a forward slash (which are not allowed on Windows) + (frame.filename.includes('\\') && !frame.filename.includes('/')); + // Check if the frame filename begins with `/` + const startsWithSlash = /^\//.test(frame.filename); + if (isWindowsFrame || startsWithSlash) { + const filename = isWindowsFrame + ? frame.filename + .replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix + .replace(/\\/g, '/') // replace all `\\` instances with `/` + : frame.filename; + const base = root ? utils.relative(root, filename) : utils.basename(filename); + frame.filename = `${prefix}${base}`; + } + return frame; + }); + + /** Process an exception event. */ + function _processExceptionsEvent(event) { + try { + return { + ...event, + exception: { + ...event.exception, + // The check for this is performed inside `process` call itself, safe to skip here + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + values: event.exception.values.map(value => ({ + ...value, + ...(value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }), + })), + }, + }; + } catch (_oO) { + return event; + } } - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) + /** Process a stack trace. */ + function _processStacktrace(stacktrace) { + return { + ...stacktrace, + frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => iteratee(f)), + }; } - return stream -} + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(originalEvent) { + let processedEvent = originalEvent; + if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) { + processedEvent = _processExceptionsEvent(processedEvent); + } -/***/ }), + return processedEvent; + }, + }; +}) ; -/***/ 20859: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const rewriteFramesIntegration = core.defineIntegration(_rewriteFramesIntegration); -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +/** + * Rewrite event frames paths. + * @deprecated Use `rewriteFramesIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const RewriteFrames = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + rewriteFramesIntegration, +) +; +exports.RewriteFrames = RewriteFrames; +exports.rewriteFramesIntegration = rewriteFramesIntegration; +//# sourceMappingURL=rewriteframes.js.map -/** - * Module dependencies. - * @private - */ -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(38237)('body-parser:json') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +/***/ }), -/** - * Module exports. - */ +/***/ 15700: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = json +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * RegExp to match the first non-space in a string. - * - * Allowed whitespace is defined in RFC 7159: - * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return - */ +const core = __nccwpck_require__(75062); + +const INTEGRATION_NAME = 'SessionTiming'; + +const _sessionTimingIntegration = (() => { + const startTime = Date.now(); -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + const now = Date.now(); + + return { + ...event, + extra: { + ...event.extra, + ['session:start']: startTime, + ['session:duration']: now - startTime, + ['session:end']: now, + }, + }; + }, + }; +}) ; + +const sessionTimingIntegration = core.defineIntegration(_sessionTimingIntegration); /** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public + * This function adds duration since Sentry was initialized till the time event was sent. + * @deprecated Use `sessionTimingIntegration()` instead. */ +// eslint-disable-next-line deprecation/deprecation +const SessionTiming = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + sessionTimingIntegration, +) ; -function json (options) { - var opts = options || {} +exports.SessionTiming = SessionTiming; +exports.sessionTimingIntegration = sessionTimingIntegration; +//# sourceMappingURL=sessiontiming.js.map - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +/***/ }), - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +/***/ 22190: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (strict) { - var first = firstchar(body) +const core = __nccwpck_require__(75062); - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) +const INTEGRATION_NAME = 'Transaction'; + +const transactionIntegration = (() => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + const frames = _getFramesFromEvent(event); + + // use for loop so we don't have to reverse whole frames array + for (let i = frames.length - 1; i >= 0; i--) { + const frame = frames[i]; + + if (frame.in_app === true) { + event.transaction = _getTransaction(frame); + break; + } } - } - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } - } + return event; + }, + }; +}) ; - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } +/** + * Add node transaction to the event. + * @deprecated This integration will be removed in v8. + */ +// eslint-disable-next-line deprecation/deprecation +const Transaction = core.convertIntegrationFnToClass(INTEGRATION_NAME, transactionIntegration) - req.body = req.body || {} +; - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +function _getFramesFromEvent(event) { + const exception = event.exception && event.exception.values && event.exception.values[0]; + return (exception && exception.stacktrace && exception.stacktrace.frames) || []; +} - debug('content-type %j', req.headers['content-type']) +function _getTransaction(frame) { + return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : ''; +} - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} +/***/ }), -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ +/***/ 14556: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' +var { + _optionalChain +} = __nccwpck_require__(25304); - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) - } -} +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ +const domain = __nccwpck_require__(73167); +const core = __nccwpck_require__(75062); -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] +function getActiveDomain() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + return (domain ).active ; } -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ +// eslint-disable-next-line deprecation/deprecation +function getCurrentHub() { + const activeDomain = getActiveDomain(); -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined + // If there's no active domain, just return undefined and the global hub will be used + if (!activeDomain) { + return undefined; } + + core.ensureHubOnCarrier(activeDomain); + + return core.getHubFromCarrier(activeDomain); } -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ +// eslint-disable-next-line deprecation/deprecation +function createNewHub(parent) { + const carrier = {}; + core.ensureHubOnCarrier(carrier, parent); + return core.getHubFromCarrier(carrier); +} -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) +function runWithAsyncContext(callback, options) { + const activeDomain = getActiveDomain(); - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] - } + if (activeDomain && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) { + // We're already in a domain, so we don't need to create a new one, just call the callback with the current hub + return callback(); } - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message + const local = domain.create() ; - return error + const parentHub = activeDomain ? core.getHubFromCarrier(activeDomain) : undefined; + const newHub = createNewHub(parentHub); + core.setHubOnCarrier(local, newHub); + + return local.bind(() => { + return callback(); + })(); } /** - * Get the simple type checker. - * - * @param {string} type - * @return {function} + * Sets the async context strategy to use Node.js domains. */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function setDomainAsyncContextStrategy() { + core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext }); } +exports.setDomainAsyncContextStrategy = setDomainAsyncContextStrategy; +//# sourceMappingURL=domain.js.map -/***/ }), -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ 54382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Module dependencies. - */ +const core = __nccwpck_require__(75062); +const async_hooks = __nccwpck_require__(90290); -var bytes = __nccwpck_require__(86966) -var debug = __nccwpck_require__(38237)('body-parser:raw') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +// eslint-disable-next-line deprecation/deprecation +let asyncStorage; /** - * Module exports. + * Sets the async context strategy to use AsyncLocalStorage which requires Node v12.17.0 or v13.10.0. */ +function setHooksAsyncContextStrategy() { + if (!asyncStorage) { + // eslint-disable-next-line deprecation/deprecation + asyncStorage = new (async_hooks ).AsyncLocalStorage(); + } -module.exports = raw + // eslint-disable-next-line deprecation/deprecation + function getCurrentHub() { + return asyncStorage.getStore(); + } -/** - * Create a middleware to parse raw bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ + // eslint-disable-next-line deprecation/deprecation + function createNewHub(parent) { + const carrier = {}; + core.ensureHubOnCarrier(carrier, parent); + return core.getHubFromCarrier(carrier); + } -function raw (options) { - var opts = options || {} + function runWithAsyncContext(callback, options) { + const existingHub = getCurrentHub(); - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false + if (existingHub && _optionalChain([options, 'optionalAccess', _ => _.reuseExisting])) { + // We're already in an async context, so we don't need to create a new one + // just call the callback with the current hub + return callback(); + } - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') + const newHub = createNewHub(existingHub); + + return asyncStorage.run(newHub, () => { + return callback(); + }); } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + core.setAsyncContextStrategy({ getCurrentHub, runWithAsyncContext }); +} - function parse (buf) { - return buf - } +exports.setHooksAsyncContextStrategy = setHooksAsyncContextStrategy; +//# sourceMappingURL=hooks.js.map - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - req.body = req.body || {} +/***/ }), - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +/***/ 15850: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - debug('content-type %j', req.headers['content-type']) +Object.defineProperty(exports, "__esModule", ({ value: true })); - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +const nodeVersion = __nccwpck_require__(29421); +const domain = __nccwpck_require__(14556); +const hooks = __nccwpck_require__(54382); - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) +/** + * Sets the correct async context strategy for Node.js + * + * Node.js >= 14 uses AsyncLocalStorage + * Node.js < 14 uses domains + */ +function setNodeAsyncContextStrategy() { + if (nodeVersion.NODE_VERSION.major >= 14) { + hooks.setHooksAsyncContextStrategy(); + } else { + domain.setDomainAsyncContextStrategy(); } } +exports.setNodeAsyncContextStrategy = setNodeAsyncContextStrategy; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 36458: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const os = __nccwpck_require__(70857); +const util = __nccwpck_require__(39023); +const core = __nccwpck_require__(75062); + /** - * Get the simple type checker. + * The Sentry Node SDK Client. * - * @param {string} type - * @return {function} + * @see NodeClientOptions for documentation on configuration options. + * @see SentryClient for usage documentation. */ +class NodeClient extends core.ServerRuntimeClient { + /** + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. + */ + constructor(options) { + core.applySdkMetadata(options, 'node'); -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) + // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util + options.transportOptions = { + textEncoder: new util.TextEncoder(), + ...options.transportOptions, + }; + + const clientOptions = { + ...options, + platform: 'node', + runtime: { name: 'node', version: global.process.version }, + serverName: options.serverName || global.process.env.SENTRY_NAME || os.hostname(), + }; + + super(clientOptions); } } +exports.NodeClient = NodeClient; +//# sourceMappingURL=client.js.map -/***/ }), -/***/ 26382: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ 20509: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +const replacements = [ + ['january', '1'], + ['february', '2'], + ['march', '3'], + ['april', '4'], + ['may', '5'], + ['june', '6'], + ['july', '7'], + ['august', '8'], + ['september', '9'], + ['october', '10'], + ['november', '11'], + ['december', '12'], + ['jan', '1'], + ['feb', '2'], + ['mar', '3'], + ['apr', '4'], + ['may', '5'], + ['jun', '6'], + ['jul', '7'], + ['aug', '8'], + ['sep', '9'], + ['oct', '10'], + ['nov', '11'], + ['dec', '12'], + ['sunday', '0'], + ['monday', '1'], + ['tuesday', '2'], + ['wednesday', '3'], + ['thursday', '4'], + ['friday', '5'], + ['saturday', '6'], + ['sun', '0'], + ['mon', '1'], + ['tue', '2'], + ['wed', '3'], + ['thu', '4'], + ['fri', '5'], + ['sat', '6'], +]; /** - * Module dependencies. + * Replaces names in cron expressions */ +function replaceCronNames(cronExpression) { + return replacements.reduce( + // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor + (acc, [name, replacement]) => acc.replace(new RegExp(name, 'gi'), replacement), + cronExpression, + ); +} -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var debug = __nccwpck_require__(38237)('body-parser:text') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +exports.replaceCronNames = replaceCronNames; +//# sourceMappingURL=common.js.map -/** - * Module exports. - */ -module.exports = text +/***/ }), + +/***/ 36780: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const core = __nccwpck_require__(75062); +const common = __nccwpck_require__(20509); + +const ERROR_TEXT = 'Automatic instrumentation of CronJob only supports crontab string'; /** - * Create a middleware to parse text bodies. + * Instruments the `cron` library to send a check-in event to Sentry for each job execution. * - * @param {object} [options] - * @return {function} - * @api public + * ```ts + * import * as Sentry from '@sentry/node'; + * import { CronJob } from 'cron'; + * + * const CronJobWithCheckIn = Sentry.cron.instrumentCron(CronJob, 'my-cron-job'); + * + * // use the constructor + * const job = new CronJobWithCheckIn('* * * * *', () => { + * console.log('You will see this message every minute'); + * }); + * + * // or from + * const job = CronJobWithCheckIn.from({ cronTime: '* * * * *', onTick: () => { + * console.log('You will see this message every minute'); + * }); + * ``` */ +function instrumentCron(lib, monitorSlug) { + let jobScheduled = false; -function text (options) { - var opts = options || {} - - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false + return new Proxy(lib, { + construct(target, args) { + const [cronTime, onTick, onComplete, start, timeZone, ...rest] = args; - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } + if (typeof cronTime !== 'string') { + throw new Error(ERROR_TEXT); + } - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type + if (jobScheduled) { + throw new Error(`A job named '${monitorSlug}' has already been scheduled`); + } - function parse (buf) { - return buf - } + jobScheduled = true; - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } + const cronString = common.replaceCronNames(cronTime); - req.body = req.body || {} + function monitoredTick(context, onComplete) { + return core.withMonitor( + monitorSlug, + () => { + return onTick(context, onComplete); + }, + { + schedule: { type: 'crontab', value: cronString }, + timezone: timeZone || undefined, + }, + ); + } - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } + return new target(cronTime, monitoredTick, onComplete, start, timeZone, ...rest); + }, + get(target, prop) { + if (prop === 'from') { + return (param) => { + const { cronTime, onTick, timeZone } = param; - debug('content-type %j', req.headers['content-type']) + if (typeof cronTime !== 'string') { + throw new Error(ERROR_TEXT); + } - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } + if (jobScheduled) { + throw new Error(`A job named '${monitorSlug}' has already been scheduled`); + } - // get charset - var charset = getCharset(req) || defaultCharset + jobScheduled = true; - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} + const cronString = common.replaceCronNames(cronTime); -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ + param.onTick = (context, onComplete) => { + return core.withMonitor( + monitorSlug, + () => { + return onTick(context, onComplete); + }, + { + schedule: { type: 'crontab', value: cronString }, + timezone: timeZone || undefined, + }, + ); + }; -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } + return target.from(param); + }; + } else { + return target[prop]; + } + }, + }); } -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} +exports.instrumentCron = instrumentCron; +//# sourceMappingURL=cron.js.map /***/ }), -/***/ 76100: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 53777: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const common = __nccwpck_require__(20509); /** - * Module dependencies. - * @private + * Wraps the `node-cron` library with check-in monitoring. + * + * ```ts + * import * as Sentry from "@sentry/node"; + * import cron from "node-cron"; + * + * const cronWithCheckIn = Sentry.cron.instrumentNodeCron(cron); + * + * cronWithCheckIn.schedule( + * "* * * * *", + * () => { + * console.log("running a task every minute"); + * }, + * { name: "my-cron-job" }, + * ); + * ``` */ +function instrumentNodeCron(lib) { + return new Proxy(lib, { + get(target, prop) { + if (prop === 'schedule' && target.schedule) { + // When 'get' is called for schedule, return a proxied version of the schedule function + return new Proxy(target.schedule, { + apply(target, thisArg, argArray) { + const [expression, , options] = argArray; + + if (!_optionalChain([options, 'optionalAccess', _ => _.name])) { + throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.'); + } -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(38237)('body-parser:urlencoded') -var deprecate = __nccwpck_require__(18883)('body-parser') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) + return core.withMonitor( + options.name, + () => { + return target.apply(thisArg, argArray); + }, + { + schedule: { type: 'crontab', value: common.replaceCronNames(expression) }, + timezone: _optionalChain([options, 'optionalAccess', _2 => _2.timezone]), + }, + ); + }, + }); + } else { + return target[prop]; + } + }, + }); +} -/** - * Module exports. - */ +exports.instrumentNodeCron = instrumentNodeCron; +//# sourceMappingURL=node-cron.js.map -module.exports = urlencoded -/** - * Cache of parser modules. - */ +/***/ }), -var parsers = Object.create(null) +/***/ 51844: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const core = __nccwpck_require__(75062); +const common = __nccwpck_require__(20509); /** - * Create a middleware to parse urlencoded bodies. + * Instruments the `node-schedule` library to send a check-in event to Sentry for each job execution. * - * @param {object} [options] - * @return {function} - * @public + * ```ts + * import * as Sentry from '@sentry/node'; + * import * as schedule from 'node-schedule'; + * + * const scheduleWithCheckIn = Sentry.cron.instrumentNodeSchedule(schedule); + * + * const job = scheduleWithCheckIn.scheduleJob('my-cron-job', '* * * * *', () => { + * console.log('You will see this message every minute'); + * }); + * ``` */ +function instrumentNodeSchedule(lib) { + return new Proxy(lib, { + get(target, prop) { + if (prop === 'scheduleJob') { + // eslint-disable-next-line @typescript-eslint/unbound-method + return new Proxy(target.scheduleJob, { + apply(target, thisArg, argArray) { + const [nameOrExpression, expressionOrCallback] = argArray; -function urlencoded (options) { - var opts = options || {} + if (typeof nameOrExpression !== 'string' || typeof expressionOrCallback !== 'string') { + throw new Error( + "Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string", + ); + } - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') - } + const monitorSlug = nameOrExpression; + const expression = expressionOrCallback; + + return core.withMonitor( + monitorSlug, + () => { + return target.apply(thisArg, argArray); + }, + { + schedule: { type: 'crontab', value: common.replaceCronNames(expression) }, + }, + ); + }, + }); + } - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false + return target[prop]; + }, + }); +} - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } +exports.instrumentNodeSchedule = instrumentNodeSchedule; +//# sourceMappingURL=node-schedule.js.map - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type +/***/ }), - function parse (body) { - return body.length - ? queryparse(body) - : {} - } +/***/ 32767: +/***/ ((__unused_webpack_module, exports) => { - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - req.body = req.body || {} +/** + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. + * + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. + */ +const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } +exports.DEBUG_BUILD = DEBUG_BUILD; +//# sourceMappingURL=debug-build.js.map - debug('content-type %j', req.headers['content-type']) - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } +/***/ }), - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } +/***/ 67376: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} +var { + _optionalChain +} = __nccwpck_require__(25304); -/** - * Get the extended query parser. - * - * @param {object} options - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(32767); +const sdk = __nccwpck_require__(89149); +const trpc = __nccwpck_require__(98074); +const requestDataDeprecated = __nccwpck_require__(34161); - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } +/** + * Express-compatible tracing handler. + * @see Exposed as `Handlers.tracingHandler` + */ +function tracingHandler() - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } + { + return function sentryTracingMiddleware( + req, + res, + next, + ) { + const options = _optionalChain([core.getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3()]); - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + if ( + !options || + options.instrumenter !== 'sentry' || + _optionalChain([req, 'access', _4 => _4.method, 'optionalAccess', _5 => _5.toUpperCase, 'call', _6 => _6()]) === 'OPTIONS' || + _optionalChain([req, 'access', _7 => _7.method, 'optionalAccess', _8 => _8.toUpperCase, 'call', _9 => _9()]) === 'HEAD' + ) { + return next(); + } - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) + const sentryTrace = req.headers && utils.isString(req.headers['sentry-trace']) ? req.headers['sentry-trace'] : undefined; + const baggage = _optionalChain([req, 'access', _10 => _10.headers, 'optionalAccess', _11 => _11.baggage]); + if (!core.hasTracingEnabled(options)) { + return next(); } - var arrayLimit = Math.max(100, paramCount) + const [name, source] = utils.extractPathForTransaction(req, { path: true, method: true }); + const transaction = core.continueTrace({ sentryTrace, baggage }, ctx => + // TODO: Refactor this to use `startSpan()` + // eslint-disable-next-line deprecation/deprecation + core.startTransaction( + { + name, + op: 'http.server', + origin: 'auto.http.node.tracingHandler', + ...ctx, + data: { + [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source, + }, + metadata: { + // eslint-disable-next-line deprecation/deprecation + ...ctx.metadata, + // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become + // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the + // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to + // be sure + request: req, + }, + }, + // extra context passed to the tracesSampler + { request: utils.extractRequestData(req) }, + ), + ); - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } -} + // We put the transaction on the scope so users can attach children to it + // eslint-disable-next-line deprecation/deprecation + core.getCurrentScope().setSpan(transaction); -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ + // We also set __sentry_transaction on the response so people can grab the transaction there to add + // spans to it later. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).__sentry_transaction = transaction; -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } + res.once('finish', () => { + // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction + // closes + setImmediate(() => { + // eslint-disable-next-line deprecation/deprecation + utils.addRequestDataToTransaction(transaction, req); + core.setHttpStatus(transaction, res.statusCode); + transaction.end(); + }); + }); + + next(); + }; } /** - * Count the number of parameters, stopping once limit reached + * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the + * `AddRequestDataToEventOptions` interface. * - * @param {string} body - * @param {number} limit - * @api private + * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. */ +function convertReqHandlerOptsToAddReqDataOpts( + reqHandlerOptions = {}, +) { + let addRequestDataOptions; -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ + if ('include' in reqHandlerOptions) { + addRequestDataOptions = { include: reqHandlerOptions.include }; + } else { + // eslint-disable-next-line deprecation/deprecation + const { ip, request, transaction, user } = reqHandlerOptions ; - if (count === limit) { - return undefined + if (ip || request || transaction || user) { + addRequestDataOptions = { include: utils.dropUndefinedKeys({ ip, request, transaction, user }) }; } } - return count + return addRequestDataOptions; } /** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` */ +function requestHandler( + options, +) { + // TODO (v8): Get rid of this + const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); + + const client = core.getClient(); + // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the + // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode + if (client && sdk.isAutoSessionTrackingEnabled(client)) { + client.initSessionFlusher(); + + // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode + const scope = core.getCurrentScope(); + if (scope.getSession()) { + scope.setSession(); + } + } + + return function sentryRequestMiddleware( + req, + res, + next, + ) { + if (options && options.flushTimeout && options.flushTimeout > 0) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _end = res.end; + res.end = function (chunk, encoding, cb) { + void core.flush(options.flushTimeout) + .then(() => { + _end.call(this, chunk, encoding, cb); + }) + .then(null, e => { + debugBuild.DEBUG_BUILD && utils.logger.error(e); + _end.call(this, chunk, encoding, cb); + }); + }; + } + core.runWithAsyncContext(() => { + const scope = core.getCurrentScope(); + scope.setSDKProcessingMetadata({ + request: req, + // TODO (v8): Stop passing this + requestDataOptionsFromExpressHandler: requestDataOptions, + }); -function parser (name) { - var mod = parsers[name] + const client = core.getClient(); + if (sdk.isAutoSessionTrackingEnabled(client)) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope.setRequestSession({ status: 'ok' }); + } - if (mod !== undefined) { - return mod.parse - } + res.once('finish', () => { + const client = core.getClient(); + if (sdk.isAutoSessionTrackingEnabled(client)) { + setImmediate(() => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (client && (client )._captureRequestSession) { + // Calling _captureRequestSession to capture request session at the end of the request by incrementing + // the correct SessionAggregates bucket i.e. crashed, errored or exited + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (client )._captureRequestSession(); + } + }); + } + }); + next(); + }); + }; +} - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = __nccwpck_require__(22760) - break - case 'querystring': - mod = __nccwpck_require__(63477) - break - } +/** JSDoc */ - // store to prevent invoking require() - parsers[name] = mod +/** JSDoc */ +function getStatusCodeFromResponse(error) { + const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); + return statusCode ? parseInt(statusCode , 10) : 500; +} - return mod.parse +/** Returns true if response code is internal server error */ +function defaultShouldHandleError(error) { + const status = getStatusCodeFromResponse(error); + return status >= 500; } /** - * Get the simple query parser. - * - * @param {object} options + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` */ +function errorHandler(options -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } +) - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } + { + return function sentryErrorMiddleware( + error, + _req, + res, + next, + ) { + const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; + + if (shouldHandleError(error)) { + core.withScope(_scope => { + // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, + // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't + // hurt to be sure + _scope.setSDKProcessingMetadata({ request: _req }); + + // For some reason we need to set the transaction on the scope again + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const transaction = (res ).__sentry_transaction ; + if (transaction && !core.getActiveSpan()) { + // eslint-disable-next-line deprecation/deprecation + _scope.setSpan(transaction); + } + + const client = core.getClient(); + if (client && sdk.isAutoSessionTrackingEnabled(client)) { + // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the + // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only + // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be + // running in SessionAggregates mode + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; + if (isSessionAggregatesMode) { + const requestSession = _scope.getRequestSession(); + // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a + // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within + // the bounds of a request, and if so the status is updated + if (requestSession && requestSession.status !== undefined) { + requestSession.status = 'crashed'; + } + } + } - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) + const eventId = core.captureException(error, { mechanism: { type: 'middleware', handled: false } }); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).sentry = eventId; + next(error); + }); - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) + return; } - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) - } + next(error); + }; } /** - * Get the simple type checker. + * Sentry tRPC middleware that names the handling transaction after the called procedure. * - * @param {string} type - * @return {function} + * Use the Sentry tRPC middleware in combination with the Sentry server integration, + * e.g. Express Request Handlers or Next.js SDK. + * + * @deprecated Please use the top level export instead: + * ``` + * // OLD + * import * as Sentry from '@sentry/node'; + * Sentry.Handlers.trpcMiddleware(); + * + * // NEW + * import * as Sentry from '@sentry/node'; + * Sentry.trpcMiddleware(); + * ``` */ +// eslint-disable-next-line deprecation/deprecation +const trpcMiddleware = trpc.trpcMiddleware; -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} +exports.extractRequestData = requestDataDeprecated.extractRequestData; +exports.parseRequest = requestDataDeprecated.parseRequest; +exports.errorHandler = errorHandler; +exports.requestHandler = requestHandler; +exports.tracingHandler = tracingHandler; +exports.trpcMiddleware = trpcMiddleware; +//# sourceMappingURL=handlers.js.map /***/ }), -/***/ 85442: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const index = __nccwpck_require__(19504); +const client = __nccwpck_require__(36458); +const http = __nccwpck_require__(94098); +const sdk = __nccwpck_require__(89149); +const utils = __nccwpck_require__(25304); +const utils$1 = __nccwpck_require__(67036); +const module$1 = __nccwpck_require__(76137); +const legacy = __nccwpck_require__(67770); +const handlers = __nccwpck_require__(67376); +const index$5 = __nccwpck_require__(63293); +const integrations$1 = __nccwpck_require__(52501); +const integrations = __nccwpck_require__(54506); +const console = __nccwpck_require__(66572); +const onuncaughtexception = __nccwpck_require__(83790); +const onunhandledrejection = __nccwpck_require__(28798); +const modules = __nccwpck_require__(94288); +const contextlines = __nccwpck_require__(11367); +const context = __nccwpck_require__(54090); +const index$1 = __nccwpck_require__(8705); +const spotlight = __nccwpck_require__(16733); +const index$2 = __nccwpck_require__(19137); +const index$3 = __nccwpck_require__(48322); +const index$4 = __nccwpck_require__(32094); +const http$1 = __nccwpck_require__(32649); +const trpc = __nccwpck_require__(98074); +const cron$1 = __nccwpck_require__(36780); +const nodeCron = __nccwpck_require__(53777); +const nodeSchedule = __nccwpck_require__(51844); + +/** + * @deprecated use `createGetModuleFromFilename` instead. + */ +const getModuleFromFilename = module$1.createGetModuleFromFilename(); + +// TODO: Deprecate this once we migrated tracing integrations +const Integrations = { + // eslint-disable-next-line deprecation/deprecation + ...core.Integrations, + ...index$5, + ...integrations$1, +}; + +/** Methods to instrument cron libraries for Sentry check-ins */ +const cron = { + instrumentCron: cron$1.instrumentCron, + instrumentNodeCron: nodeCron.instrumentNodeCron, + instrumentNodeSchedule: nodeSchedule.instrumentNodeSchedule, +}; + +exports.Hub = core.Hub; +exports.SDK_VERSION = core.SDK_VERSION; +exports.SEMANTIC_ATTRIBUTE_SENTRY_OP = core.SEMANTIC_ATTRIBUTE_SENTRY_OP; +exports.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE; +exports.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE; +exports.Scope = core.Scope; +exports.addBreadcrumb = core.addBreadcrumb; +exports.addEventProcessor = core.addEventProcessor; +exports.addGlobalEventProcessor = core.addGlobalEventProcessor; +exports.addIntegration = core.addIntegration; +exports.captureCheckIn = core.captureCheckIn; +exports.captureEvent = core.captureEvent; +exports.captureException = core.captureException; +exports.captureMessage = core.captureMessage; +exports.captureSession = core.captureSession; +exports.close = core.close; +exports.configureScope = core.configureScope; +exports.continueTrace = core.continueTrace; +exports.createTransport = core.createTransport; +exports.endSession = core.endSession; +exports.extractTraceparentData = core.extractTraceparentData; +exports.flush = core.flush; +exports.functionToStringIntegration = core.functionToStringIntegration; +exports.getActiveSpan = core.getActiveSpan; +exports.getActiveTransaction = core.getActiveTransaction; +exports.getClient = core.getClient; +exports.getCurrentHub = core.getCurrentHub; +exports.getCurrentScope = core.getCurrentScope; +exports.getGlobalScope = core.getGlobalScope; +exports.getHubFromCarrier = core.getHubFromCarrier; +exports.getIsolationScope = core.getIsolationScope; +exports.getSpanStatusFromHttpCode = core.getSpanStatusFromHttpCode; +exports.inboundFiltersIntegration = core.inboundFiltersIntegration; +exports.isInitialized = core.isInitialized; +exports.lastEventId = core.lastEventId; +exports.linkedErrorsIntegration = core.linkedErrorsIntegration; +exports.makeMain = core.makeMain; +exports.metrics = core.metrics; +exports.parameterize = core.parameterize; +exports.requestDataIntegration = core.requestDataIntegration; +exports.runWithAsyncContext = core.runWithAsyncContext; +exports.setContext = core.setContext; +exports.setCurrentClient = core.setCurrentClient; +exports.setExtra = core.setExtra; +exports.setExtras = core.setExtras; +exports.setHttpStatus = core.setHttpStatus; +exports.setMeasurement = core.setMeasurement; +exports.setTag = core.setTag; +exports.setTags = core.setTags; +exports.setUser = core.setUser; +exports.spanStatusfromHttpCode = core.spanStatusfromHttpCode; +exports.startActiveSpan = core.startActiveSpan; +exports.startInactiveSpan = core.startInactiveSpan; +exports.startSession = core.startSession; +exports.startSpan = core.startSpan; +exports.startSpanManual = core.startSpanManual; +exports.startTransaction = core.startTransaction; +exports.trace = core.trace; +exports.withActiveSpan = core.withActiveSpan; +exports.withIsolationScope = core.withIsolationScope; +exports.withMonitor = core.withMonitor; +exports.withScope = core.withScope; +exports.autoDiscoverNodePerformanceMonitoringIntegrations = index.autoDiscoverNodePerformanceMonitoringIntegrations; +exports.NodeClient = client.NodeClient; +exports.makeNodeTransport = http.makeNodeTransport; +exports.defaultIntegrations = sdk.defaultIntegrations; +exports.defaultStackParser = sdk.defaultStackParser; +exports.getDefaultIntegrations = sdk.getDefaultIntegrations; +exports.getSentryRelease = sdk.getSentryRelease; +exports.init = sdk.init; +exports.DEFAULT_USER_INCLUDES = utils.DEFAULT_USER_INCLUDES; +exports.addRequestDataToEvent = utils.addRequestDataToEvent; +exports.extractRequestData = utils.extractRequestData; +exports.deepReadDirSync = utils$1.deepReadDirSync; +exports.createGetModuleFromFilename = module$1.createGetModuleFromFilename; +exports.enableAnrDetection = legacy.enableAnrDetection; +exports.Handlers = handlers; +exports.captureConsoleIntegration = integrations.captureConsoleIntegration; +exports.debugIntegration = integrations.debugIntegration; +exports.dedupeIntegration = integrations.dedupeIntegration; +exports.extraErrorDataIntegration = integrations.extraErrorDataIntegration; +exports.httpClientIntegration = integrations.httpClientIntegration; +exports.reportingObserverIntegration = integrations.reportingObserverIntegration; +exports.rewriteFramesIntegration = integrations.rewriteFramesIntegration; +exports.sessionTimingIntegration = integrations.sessionTimingIntegration; +exports.consoleIntegration = console.consoleIntegration; +exports.onUncaughtExceptionIntegration = onuncaughtexception.onUncaughtExceptionIntegration; +exports.onUnhandledRejectionIntegration = onunhandledrejection.onUnhandledRejectionIntegration; +exports.modulesIntegration = modules.modulesIntegration; +exports.contextLinesIntegration = contextlines.contextLinesIntegration; +exports.nodeContextIntegration = context.nodeContextIntegration; +exports.localVariablesIntegration = index$1.localVariablesIntegration; +exports.spotlightIntegration = spotlight.spotlightIntegration; +exports.anrIntegration = index$2.anrIntegration; +exports.hapiErrorPlugin = index$3.hapiErrorPlugin; +exports.hapiIntegration = index$3.hapiIntegration; +exports.Undici = index$4.Undici; +exports.nativeNodeFetchintegration = index$4.nativeNodeFetchintegration; +exports.Http = http$1.Http; +exports.httpIntegration = http$1.httpIntegration; +exports.trpcMiddleware = trpc.trpcMiddleware; +exports.Integrations = Integrations; +exports.cron = cron; +exports.getModuleFromFilename = getModuleFromFilename; +//# sourceMappingURL=index.js.map -var Batcher, Events, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Batcher = function () { - class Batcher { - constructor(options = {}) { - this.options = options; - parser.load(this.options, this.defaults, this); - this.Events = new Events(this); - this._arr = []; +/***/ }), - this._resetPromise(); +/***/ 19137: +/***/ ((module, exports, __nccwpck_require__) => { - this._lastFlush = Date.now(); - } +/* module decorator */ module = __nccwpck_require__.nmd(module); +var { + _optionalChain, + _optionalChainDelete +} = __nccwpck_require__(25304); - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); +const url = __nccwpck_require__(87016); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const nodeVersion = __nccwpck_require__(29421); +const workerScript = __nccwpck_require__(59451); - this._resolve(); +const DEFAULT_INTERVAL = 50; +const DEFAULT_HANG_THRESHOLD = 5000; - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } +function log(message, ...args) { + utils.logger.log(`[ANR] ${message}`, ...args); +} - add(data) { - var ret; +function globalWithScopeFetchFn() { + return utils.GLOBAL_OBJ; +} - this._arr.push(data); +/** Fetches merged scope data */ +function getScopeData() { + const scope = core.getGlobalScope().getScopeData(); + core.mergeScopeData(scope, core.getIsolationScope().getScopeData()); + core.mergeScopeData(scope, core.getCurrentScope().getScopeData()); - ret = this._promise; + // We remove attachments because they likely won't serialize well as json + scope.attachments = []; + // We can't serialize event processor functions + scope.eventProcessors = []; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if (this.maxTime != null && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } + return scope; +} - return ret; - } +/** + * We need to use dynamicRequire because worker_threads is not available in node < v12 and webpack error will when + * targeting those versions + */ +function getWorkerThreads() { + return utils.dynamicRequire(module, 'worker_threads'); +} - } +/** + * Gets contexts by calling all event processors. This relies on being called after all integrations are setup + */ +async function getContexts(client) { + let event = { message: 'ANR' }; + const eventHint = {}; - ; - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; -}.call(void 0); + for (const processor of client.getEventProcessors()) { + if (event === null) break; + event = await processor(event, eventHint); + } -module.exports = Batcher; + return _optionalChain([event, 'optionalAccess', _2 => _2.contexts]) || {}; +} -/***/ }), +const INTEGRATION_NAME = 'Anr'; -/***/ 83911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const _anrIntegration = ((options = {}) => { + if (nodeVersion.NODE_VERSION.major < 16 || (nodeVersion.NODE_VERSION.major === 16 && nodeVersion.NODE_VERSION.minor < 17)) { + throw new Error('ANR detection requires Node 16.17.0 or later'); + } -"use strict"; + let worker; + let client; + // Hookup the scope fetch function to the global object so that it can be called from the worker thread via the + // debugger when it pauses + const gbl = globalWithScopeFetchFn(); + gbl.__SENTRY_GET_SCOPES__ = getScopeData; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + startWorker: () => { + if (worker) { + return; + } -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + if (client) { + worker = _startWorker(client, options); + } + }, + stopWorker: () => { + if (worker) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.then(stop => { + stop(); + worker = undefined; + }); + } + }, + setup(initClient) { + client = initClient; -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } + // setImmediate is used to ensure that all other integrations have had their setup called first. + // This allows us to call into all integrations to fetch the full context + setImmediate(() => this.startWorker()); + }, + } ; +}) ; -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +const anrIntegration = core.defineIntegration(_anrIntegration) ; -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } +/** + * Starts a thread to detect App Not Responding (ANR) events + * + * ANR detection requires Node 16.17.0 or later + * + * @deprecated Use `anrIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Anr = core.convertIntegrationFnToClass(INTEGRATION_NAME, anrIntegration) -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +// eslint-disable-next-line deprecation/deprecation -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +/** + * Starts the ANR worker thread + */ +async function _startWorker( + client, + integrationOptions, +) { + const dsn = client.getDsn(); -var Bottleneck, - DEFAULT_PRIORITY, - Events, - Job, - LocalDatastore, - NUM_PRIORITIES, - Queues, - RedisDatastore, - States, - Sync, - parser, - splice = [].splice; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -Queues = __nccwpck_require__(65893); -Job = __nccwpck_require__(25949); -LocalDatastore = __nccwpck_require__(38979); -RedisDatastore = __nccwpck_require__(4946); -Events = __nccwpck_require__(107); -States = __nccwpck_require__(2527); -Sync = __nccwpck_require__(56029); + if (!dsn) { + return () => { + // + }; + } -Bottleneck = function () { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); + const contexts = await getContexts(client); - this._validateOptions(options, invalid); + // These will not be accurate if sent later from the worker thread + _optionalChainDelete([contexts, 'access', _3 => _3.app, 'optionalAccess', _4 => delete _4.app_memory]); + _optionalChainDelete([contexts, 'access', _5 => _5.device, 'optionalAccess', _6 => delete _6.free_memory]); - parser.load(options, this.instanceDefaults, this); - this._queues = new Queues(NUM_PRIORITIES); - this._scheduled = {}; - this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events(this); - this._submitLock = new Sync("submit", this.Promise); - this._registerLock = new Sync("register", this.Promise); - storeOptions = parser.load(options, this.storeDefaults, {}); + const initOptions = client.getOptions(); - this._store = function () { - if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { - storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); - return new LocalDatastore(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }.call(this); + const sdkMetadata = client.getSdkMetadata() || {}; + if (sdkMetadata.sdk) { + sdkMetadata.sdk.integrations = initOptions.integrations.map(i => i.name); + } - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); + const options = { + debug: utils.logger.isEnabled(), + dsn, + environment: initOptions.environment || 'production', + release: initOptions.release, + dist: initOptions.dist, + sdkMetadata, + appRootPath: integrationOptions.appRootPath, + pollInterval: integrationOptions.pollInterval || DEFAULT_INTERVAL, + anrThreshold: integrationOptions.anrThreshold || DEFAULT_HANG_THRESHOLD, + captureStackTrace: !!integrationOptions.captureStackTrace, + staticTags: integrationOptions.staticTags || {}, + contexts, + }; - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); + if (options.captureStackTrace) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const inspector = __nccwpck_require__(50264); + if (!inspector.url()) { + inspector.open(0); } + } - _validateOptions(options, invalid) { - if (!(options != null && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } + const { Worker } = getWorkerThreads(); - ready() { - return this._store.ready; - } + const worker = new Worker(new url.URL(`data:application/javascript;base64,${workerScript.base64WorkerScript}`), { + workerData: options, + }); - clients() { - return this._store.clients; - } + process.on('exit', () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + }); - channel() { - return `b_${this.id}`; + const timer = setInterval(() => { + try { + const currentSession = core.getCurrentScope().getSession(); + // We need to copy the session object and remove the toJSON method so it can be sent to the worker + // serialized without making it a SerializedSession + const session = currentSession ? { ...currentSession, toJSON: undefined } : undefined; + // message the worker to tell it the main event loop is still running + worker.postMessage({ session }); + } catch (_) { + // } + }, options.pollInterval); + // Timer should not block exit + timer.unref(); - channel_client() { - return `b_${this.id}_${this._store.clientId}`; + worker.on('message', (msg) => { + if (msg === 'session-ended') { + log('ANR event sent from ANR worker. Clearing session in this thread.'); + core.getCurrentScope().setSession(undefined); } + }); - publish(message) { - return this._store.__publish__(message); - } + worker.once('error', (err) => { + clearInterval(timer); + log('ANR worker error', err); + }); - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + worker.once('exit', (code) => { + clearInterval(timer); + log('ANR worker exit', code); + }); - chain(_limiter) { - this._limiter = _limiter; - return this; - } + // Ensure this thread can't block app exit + worker.unref(); - queued(priority) { - return this._queues.queued(priority); - } + return () => { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + clearInterval(timer); + }; +} - clusterQueued() { - return this._store.__queued__(); - } +exports.Anr = Anr; +exports.anrIntegration = anrIntegration; +//# sourceMappingURL=index.js.map - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } - running() { - return this._store.__running__(); - } +/***/ }), - done() { - return this._store.__done__(); - } +/***/ 67770: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - jobStatus(id) { - return this._states.jobStatus(id); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - jobs(status) { - return this._states.statusJobs(status); - } +const core = __nccwpck_require__(75062); +const index = __nccwpck_require__(19137); - counts() { - return this._states.statusCounts(); - } +// TODO (v8): Remove this entire file and the `enableAnrDetection` export - _randomIndex() { - return Math.random().toString(36).slice(2); - } +/** + * @deprecated Use the `Anr` integration instead. + * + * ```ts + * import * as Sentry from '@sentry/node'; + * + * Sentry.init({ + * dsn: '__DSN__', + * integrations: [new Sentry.Integrations.Anr({ captureStackTrace: true })], + * }); + * ``` + */ +function enableAnrDetection(options) { + const client = core.getClient() ; + // eslint-disable-next-line deprecation/deprecation + const integration = new index.Anr(options); + integration.setup(client); + return Promise.resolve(); +} - check(weight = 1) { - return this._store.__check__(weight); - } +exports.enableAnrDetection = enableAnrDetection; +//# sourceMappingURL=legacy.js.map - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } - _free(index, job, options, eventInfo) { - var _this = this; +/***/ }), - return _asyncToGenerator(function* () { - var e, running; +/***/ 59451: +/***/ ((__unused_webpack_module, exports) => { - try { - var _ref = yield _this._store.__free__(index, options.weight); +/*! @sentry/node 7.120.2 (85a3cac) | https://github.com/getsentry/sentry-javascript */ +exports.base64WorkerScript="aW1wb3J0IHsgU2Vzc2lvbiB9IGZyb20gJ2luc3BlY3Rvcic7CmltcG9ydCB7IHdvcmtlckRhdGEsIHBhcmVudFBvcnQgfSBmcm9tICd3b3JrZXJfdGhyZWFkcyc7CmltcG9ydCB7IHBvc2l4LCBzZXAgfSBmcm9tICdwYXRoJzsKaW1wb3J0ICogYXMgaHR0cCBmcm9tICdodHRwJzsKaW1wb3J0ICogYXMgaHR0cHMgZnJvbSAnaHR0cHMnOwppbXBvcnQgeyBSZWFkYWJsZSB9IGZyb20gJ3N0cmVhbSc7CmltcG9ydCB7IFVSTCB9IGZyb20gJ3VybCc7CmltcG9ydCB7IGNyZWF0ZUd6aXAgfSBmcm9tICd6bGliJzsKaW1wb3J0ICogYXMgbmV0IGZyb20gJ25ldCc7CmltcG9ydCAqIGFzIHRscyBmcm9tICd0bHMnOwoKLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIEB0eXBlc2NyaXB0LWVzbGludC91bmJvdW5kLW1ldGhvZApjb25zdCBvYmplY3RUb1N0cmluZyA9IE9iamVjdC5wcm90b3R5cGUudG9TdHJpbmc7CgovKioKICogQ2hlY2tzIHdoZXRoZXIgZ2l2ZW4gdmFsdWUncyB0eXBlIGlzIG9uZSBvZiBhIGZldyBFcnJvciBvciBFcnJvci1saWtlCiAqIHtAbGluayBpc0Vycm9yfS4KICoKICogQHBhcmFtIHdhdCBBIHZhbHVlIHRvIGJlIGNoZWNrZWQuCiAqIEByZXR1cm5zIEEgYm9vbGVhbiByZXByZXNlbnRpbmcgdGhlIHJlc3VsdC4KICovCmZ1bmN0aW9uIGlzRXJyb3Iod2F0KSB7CiAgc3dpdGNoIChvYmplY3RUb1N0cmluZ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XQzLmNhbGwodGhpcyk7U3luY1Byb21pc2UucHJvdG90eXBlLl9faW5pdDQuY2FsbCh0aGlzKTsKICAgIHRoaXMuX3N0YXRlID0gU3RhdGVzLlBFTkRJTkc7CiAgICB0aGlzLl9oYW5kbGVycyA9IFtdOwoKICAgIHRyeSB7CiAgICAgIGV4ZWN1dG9yKHRoaXMuX3Jlc29sdmUsIHRoaXMuX3JlamVjdCk7CiAgICB9IGNhdGNoIChlKSB7CiAgICAgIHRoaXMuX3JlamVjdChlKTsKICAgIH0KICB9CgogIC8qKiBKU0RvYyAqLwogICB0aGVuKAogICAgb25mdWxmaWxsZWQsCiAgICBvbnJlamVjdGVkLAogICkgewogICAgcmV0dXJuIG5ldyBTeW5jUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7CiAgICAgIHRoaXMuX2hhbmRsZXJzLnB1c2goWwogICAgICAgIGZhbHNlLAogICAgICAgIHJlc3VsdCA9PiB7CiAgICAgICAgICBpZiAoIW9uZnVsZmlsbGVkKSB7CiAgICAgICAgICAgIC8vIFRPRE86IMKvXF8o44OEKV8vwq8KICAgICAgICAgICAgLy8gVE9ETzogRklYTUUKICAgICAgICAgICAgcmVzb2x2ZShyZXN1bHQgKTsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgcmVzb2x2ZShvbmZ1bGZpbGxlZChyZXN1bHQpKTsKICAgICAgICAgICAgfSBjYXRjaCAoZSkgewogICAgICAgICAgICAgIHJlamVjdChlKTsKICAgICAgICAgICAgfQogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICAgcmVhc29uID0+IHsKICAgICAgICAgIGlmICghb25yZWplY3RlZCkgewogICAgICAgICAgICByZWplY3QocmVhc29uKTsKICAgICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgcmVzb2x2ZShvbnJlamVjdGVkKHJlYXNvbikpOwogICAgICAgICAgICB9IGNhdGNoIChlKSB7CiAgICAgICAgICAgICAgcmVqZWN0KGUpOwogICAgICAgICAgICB9CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgXSk7CiAgICAgIHRoaXMuX2V4ZWN1dGVIYW5kbGVycygpOwogICAgfSk7CiAgfQoKICAvKiogSlNEb2MgKi8KICAgY2F0Y2goCiAgICBvbnJlamVjdGVkLAogICkgewogICAgcmV0dXJuIHRoaXMudGhlbih2YWwgPT4gdmFsLCBvbnJlamVjdGVkKTsKICB9CgogIC8qKiBKU0RvYyAqLwogICBmaW5hbGx5KG9uZmluYWxseSkgewogICAgcmV0dXJuIG5ldyBTeW5jUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7CiAgICAgIGxldCB2YWw7CiAgICAgIGxldCBpc1JlamVjdGVkOwoKICAgICAgcmV0dXJuIHRoaXMudGhlbigKICAgICAgICB2YWx1ZSA9PiB7CiAgICAgICAgICBpc1JlamVjdGVkID0gZmFsc2U7CiAgICAgICAgICB2YWwgPSB2YWx1ZTsKICAgICAgICAgIGlmIChvbmZpbmFsbHkpIHsKICAgICAgICAgICAgb25maW5hbGx5KCk7CiAgICAgICAgICB9CiAgICAgICAgfSwKICAgICAgICByZWFzb24gPT4gewogICAgICAgICAgaXNSZWplY3RlZCA9IHRydWU7CiAgICAgICAgICB2YWwgPSByZWFzb247CiAgICAgICAgICBpZiAob25maW5hbGx5KSB7CiAgICAgICAgICAgIG9uZmluYWxseSgpOwogICAgICAgICAgfQogICAgICAgIH0sCiAgICAgICkudGhlbigoKSA9PiB7CiAgICAgICAgaWYgKGlzUmVqZWN0ZWQpIHsKICAgICAgICAgIHJlamVjdCh2YWwpOwogICAgICAgICAgcmV0dXJuOwogICAgICAgIH0KCiAgICAgICAgcmVzb2x2ZSh2YWwgKTsKICAgICAgfSk7CiAgICB9KTsKICB9CgogIC8qKiBKU0RvYyAqLwogICAgX19pbml0KCkge3RoaXMuX3Jlc29sdmUgPSAodmFsdWUpID0+IHsKICAg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xdWVzdFNlc3Npb24oKSB7CiAgICByZXR1cm4gdGhpcy5fcmVxdWVzdFNlc3Npb247CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqLwogICBzZXRSZXF1ZXN0U2Vzc2lvbihyZXF1ZXN0U2Vzc2lvbikgewogICAgdGhpcy5fcmVxdWVzdFNlc3Npb24gPSByZXF1ZXN0U2Vzc2lvbjsKICAgIHJldHVybiB0aGlzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKi8KICAgc2V0VGFncyh0YWdzKSB7CiAgICB0aGlzLl90YWdzID0gewogICAgICAuLi50aGlzLl90YWdzLAogICAgICAuLi50YWdzLAogICAgfTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldFRhZyhrZXksIHZhbHVlKSB7CiAgICB0aGlzLl90YWdzID0geyAuLi50aGlzLl90YWdzLCBba2V5XTogdmFsdWUgfTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldEV4dHJhcyhleHRyYXMpIHsKICAgIHRoaXMuX2V4dHJhID0gewogICAgICAuLi50aGlzLl9leHRyYSwKICAgICAgLi4uZXh0cmFzLAogICAgfTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldEV4dHJhKGtleSwgZXh0cmEpIHsKICAgIHRoaXMuX2V4dHJhID0geyAuLi50aGlzLl9leHRyYSwgW2tleV06IGV4dHJhIH07CiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwogICAgcmV0dXJuIHRoaXM7CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqLwogICBzZXRGaW5nZXJwcmludChmaW5nZXJwcmludCkgewogICAgdGhpcy5fZmluZ2VycHJpbnQgPSBmaW5nZXJwcmludDsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIHNldExldmVsKAogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICBsZXZlbCwKICApIHsKICAgIHRoaXMuX2xldmVsID0gbGV2ZWw7CiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwogICAgcmV0dXJuIHRoaXM7CiAgfQoKICAvKioKICAgKiBTZXRzIHRoZSB0cmFuc2FjdGlvbiBuYW1lIG9uIHRoZSBzY29wZSBmb3IgZnV0dXJlIGV2ZW50cy4KICAgKi8KICAgc2V0VHJhbnNhY3Rpb25OYW1lKG5hbWUpIHsKICAgIHRoaXMuX3RyYW5zYWN0aW9uTmFtZSA9IG5hbWU7CiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwogICAgcmV0dXJuIHRoaXM7CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqLwogICBzZXRDb250ZXh0KGtleSwgY29udGV4dCkgewogICAgaWYgKGNvbnRleHQgPT09IG51bGwpIHsKICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIEB0eXBlc2NyaXB0LWVzbGludC9uby1keW5hbWljLWRlbGV0ZQogICAgICBkZWxldGUgdGhpcy5fY29udGV4dHNba2V5XTsKICAgIH0gZWxzZSB7CiAgICAgIHRoaXMuX2NvbnRleHRzW2tleV0gPSBjb250ZXh0OwogICAgfQoKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKg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oaXMuX3RhZ3MsIC4uLnNjb3BlQ29udGV4dC50YWdzIH07CiAgICAgIHRoaXMuX2V4dHJhID0geyAuLi50aGlzLl9leHRyYSwgLi4uc2NvcGVDb250ZXh0LmV4dHJhIH07CiAgICAgIHRoaXMuX2NvbnRleHRzID0geyAuLi50aGlzLl9jb250ZXh0cywgLi4uc2NvcGVDb250ZXh0LmNvbnRleHRzIH07CiAgICAgIGlmIChzY29wZUNvbnRleHQudXNlcikgewogICAgICAgIHRoaXMuX3VzZXIgPSBzY29wZUNvbnRleHQudXNlcjsKICAgICAgfQogICAgICBpZiAoc2NvcGVDb250ZXh0LmxldmVsKSB7CiAgICAgICAgdGhpcy5fbGV2ZWwgPSBzY29wZUNvbnRleHQubGV2ZWw7CiAgICAgIH0KICAgICAgaWYgKHNjb3BlQ29udGV4dC5maW5nZXJwcmludCkgewogICAgICAgIHRoaXMuX2ZpbmdlcnByaW50ID0gc2NvcGVDb250ZXh0LmZpbmdlcnByaW50OwogICAgICB9CiAgICAgIGlmIChzY29wZUNvbnRleHQucmVxdWVzdFNlc3Npb24pIHsKICAgICAgICB0aGlzLl9yZXF1ZXN0U2Vzc2lvbiA9IHNjb3BlQ29udGV4dC5yZXF1ZXN0U2Vzc2lvbjsKICAgICAgfQogICAgICBpZiAoc2NvcGVDb250ZXh0LnByb3BhZ2F0aW9uQ29udGV4dCkgewogICAgICAgIHRoaXMuX3Byb3BhZ2F0aW9uQ29udGV4dCA9IHNjb3BlQ29udGV4dC5wcm9wYWdhdGlvbkNvbnRleHQ7CiAgICAgIH0KICAgIH0KCiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIGNsZWFyKCkgewogICAgdGhpcy5fYnJlYWRjcnVtYnMgPSBbXTsKICAgIHRoaXMuX3RhZ3MgPSB7fTsKICAgIHRoaXMuX2V4dHJhID0ge307CiAgICB0aGlzLl91c2VyID0ge307CiAgICB0aGlzLl9jb250ZXh0cyA9IHt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KTsKICAgIHRoaXMuX2JyZWFkY3J1bWJzID0gYnJlYWRjcnVtYnMubGVuZ3RoID4gbWF4Q3J1bWJzID8gYnJlYWRjcnVtYnMuc2xpY2UoLW1heENydW1icykgOiBicmVhZGNydW1iczsKCiAgICB0aGlzLl9ub3RpZnlTY29wZUxpc3RlbmVycygpOwoKICAgIHJldHVybiB0aGlzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKi8KICAgZ2V0TGFzdEJyZWFkY3J1bWIoKSB7CiAgICByZXR1cm4gdGhpcy5fYnJlYWRjcnVtYnNbdGhpcy5fYnJlYWRjcnVtYnMubGVuZ3RoIC0gMV07CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqLwogICBjbGVhckJyZWFkY3J1bWJzKCkgewogICAgdGhpcy5fYnJlYWRjcnVtYnMgPSBbXTsKICAgIHRoaXMuX25vdGlmeVNjb3BlTGlzdGVuZXJzKCk7CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgIGFkZEF0dGFjaG1lbnQoYXR0YWNobWVudCkgewogICAgdGhpcy5fYXR0YWNobWVudHMucHVzaChhdHRhY2htZW50KTsKICAgIHJldHVybiB0aGlzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKiBAZGVwcmVjYXRlZCBVc2UgYGdldFNjb3BlRGF0YSgpYCBpbnN0ZWFkLgogICAqLwogICBnZXRBdHRhY2htZW50cygpIHsKICAgIGNvbnN0IGRhdGEgPSB0aGlzLmdldFNjb3BlRGF0YSgpOwoKICAgIHJldHVybiBkYXRhLmF0dGFjaG1lbnRzOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKi8KICAgY2xlYXJBdHRhY2htZW50cygpIHsKICAgIHRoaXMuX2F0dGFjaG1lbnRzID0gW107CiAgICByZXR1cm4gdGhpczsKICB9CgogIC8qKiBAaW5oZXJpdERvYyAqLwogICBnZXRTY29wZURhdGEoKSB7CiAgICBjb25zdCB7CiAgICAgIF9icmVhZGNydW1icywKICAgICAgX2F0dGFjaG1lbnRzLAogICAgICBfY29udGV4dHMsCiAgICAgIF90YWdzLAogICAgICBfZXh0cmEsCiAgICAgIF91c2VyLAogICAgICBfbGV2ZWwsCiAgICAgIF9maW5nZXJwcmludCwKICAgICAgX2V2ZW50UHJvY2Vzc29ycywKICAgICAgX3Byb3BhZ2F0aW9uQ29udGV4dCwKICAgICAgX3Nka1Byb2Nlc3NpbmdNZXRhZGF0YSwKICAgICAgX3RyYW5zYWN0aW9uTmFtZSwKICAgICAgX3NwYW4sCiAgICB9ID0gdGhpczsKCiAgICByZXR1cm4gewogICAgICBicmVhZGNydW1iczogX2JyZWFkY3J1bWJzLAogICAgICBhdHRhY2htZW50czogX2F0dGFjaG1lbnRzLAogICAgICBjb250ZXh0czogX2NvbnRleHRzLAogICAgICB0YWdzOiBfdGFncywKICAgICAgZXh0cmE6IF9leHRyYSwKICAgICAgdXNlcjogX3VzZXIsCiAgICAgIGxldmVsOiBfbGV2ZWwsCiAgICAgIGZpbmdlcnByaW50OiBfZmluZ2VycHJpbnQgfHwgW10sCiAgICAgIGV2ZW50UHJvY2Vzc29yczogX2V2ZW50UHJvY2Vzc29ycywKICAgICAgcHJvcGFnYXRpb25Db250ZXh0OiBfcHJvcGFnYXRpb25Db250ZXh0LAogICAgICBzZGtQcm9jZXNzaW5nTWV0YWRhdGE6IF9zZGtQcm9jZXNzaW5nTWV0YWRhdGEsCiAgICAgIHRyYW5zYWN0aW9uTmFtZTogX3RyYW5zYWN0aW9uTmFtZSwKICAgICAgc3BhbjogX3NwYW4sCiAgICB9OwogIH0KCiAgLyoqCiAgICogQXBwbGllcyBkYXRhIGZyb20gdGhlIHNjb3BlIHRvIHRoZSBldmVudCBhbmQgcnVucyBhbGwgZXZlbnQgcHJvY2Vzc29ycyBvbiBpdC4KICAgKgogICAqIEBwYXJhbSBldmVudCBFdmVudAogICAqIEBwYXJhbSBoaW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gogICAqCiAgICogSWYgeW91IGFyZSBjdXJyZW50bHkgdXNpbmcgdGhlIEh1YiBmb3IgbXVsdGktY2xpZW50IHVzZSBsaWtlIHNvOgogICAqCiAgICogYGBgCiAgICogLy8gT0xECiAgICogY29uc3QgaHViID0gbmV3IEh1YigpOwogICAqIGh1Yi5iaW5kQ2xpZW50KGNsaWVudCk7CiAgICogbWFrZU1haW4oaHViKQogICAqIGBgYAogICAqCiAgICogaW5zdGVhZCBpbml0aWFsaXplIHRoZSBjbGllbnQgYXMgZm9sbG93czoKICAgKgogICAqIGBgYAogICAqIC8vIE5FVwogICAqIFNlbnRyeS53aXRoSXNvbGF0aW9uU2NvcGUoKCkgPT4gewogICAqICAgIFNlbnRyeS5zZXRDdXJyZW50Q2xpZW50KGNsaWVudCk7CiAgICogICAgY2xpZW50LmluaXQoKTsKICAgKiB9KTsKICAgKiBgYGAKICAgKgogICAqIElmIHlvdSBhcmUgdXNpbmcgdGhlIEh1YiB0byBjYXB0dXJlIGV2ZW50cyBsaWtlIHNvOgogICAqCiAgICogYGBgCiAgICogLy8gT0xECiAgICogY29uc3QgY2xpZW50ID0gbmV3IENsaWVudCgpOwogICAqIGNvbnN0IGh1YiA9IG5ldyBIdWIoY2xpZW50KTsKICAgKiBodWIuY2FwdHVyZUV4Y2VwdGlvbigpCiAgICogYGBgCiAgICoKICAgKiBpbnN0ZWFkIGNhcHR1cmUgaXNvbGF0ZWQgZXZlbnRzIGFzIGZvbGxvd3M6CiAgICoKICAgKiBgYGAKICAgKiAvLyBORVcKICAgKiBjb25zdCBjbGllbnQgPSBuZXcgQ2xpZW50KCk7CiAgICogY29uc3Qgc2NvcGUgPSBuZXcgU2NvcGUoKTsKICAgKiBzY29wZS5zZXRDbGllbnQoY2xpZW50KTsKICAgKiBzY29wZS5jYXB0dXJlRXhjZXB0aW9uKCk7CiAgICogYGBgCiAgICovCiAgIGNvbnN0cnVjdG9yKAogICAgY2xpZW50LAogICAgc2NvcGUsCiAgICBpc29sYXR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U2NvcGUoKSB7CiAgICAvLyBXZSB3YW50IHRvIGNsb25lIHRoZSBjb250ZW50IG9mIHByZXYgc2NvcGUKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgY29uc3Qgc2NvcGUgPSB0aGlzLmdldFNjb3BlKCkuY2xvbmUoKTsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgdGhpcy5nZXRTdGFjaygpLnB1c2goewogICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgZGVwcmVjYXRpb24vZGVwcmVjYXRpb24KICAgICAgY2xpZW50OiB0aGlzLmdldENsaWVudCgpLAogICAgICBzY29wZSwKICAgIH0pOwogICAgcmV0dXJuIHNjb3BlOwogIH0KCiAgLyoqCiAgICogQGluaGVyaXREb2MKICAgKgogICAqIEBkZXByZWNhdGVkIFVzZSBgd2l0aFNjb3BlYCBpbnN0ZWFkLgogICAqLwogICBwb3BTY29wZSgpIHsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgaWYgKHRoaXMuZ2V0U3RhY2soKS5sZW5ndGggPD0gMSkgcmV0dXJuIGZhbHNlOwogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICByZXR1cm4gISF0aGlzLmdldFN0YWNrKCkucG9wKCk7CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqCiAgICogQGRlcHJlY2F0ZWQgVXNlIGBTZW50cnkud2l0aFNjb3BlKClgIGluc3RlYWQuCiAgICovCiAgIHdpdGhTY29wZShjYWxsYmFjaykgewogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICBjb25zdCBzY29wZSA9IHRoaXMucHVzaFNjb3BlKCk7CgogICAgbGV0IG1heWJlUHJvbWlzZVJlc3VsdDsKICAgIHRyeSB7CiAgICAgIG1heWJlUHJvbWlzZVJlc3VsdCA9IGNhbGxiYWNrKHNjb3BlKTsKICAgIH0gY2F0Y2ggKGUpIHsKICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICAgIHRoaXMucG9wU2NvcGUoKTsKICAgICAgdGhyb3cgZTsKICAgIH0KCiAgICBpZiAoaXNUaGVuYWJsZShtYXliZVByb21pc2VSZXN1bHQpKSB7CiAgICAgIC8vIEB0cy1leHBlY3QtZXJyb3IgLSBpc1RoZW5hYmxlIHJldHVybnMgdGhlIHdyb25nIHR5cGUKICAgICAgcmV0dXJuIG1heWJlUHJvbWlzZVJlc3VsdC50aGVuKAogICAgICAgIHJlcyA9PiB7CiAgICAgICAgICAvLyBlc2xpbnQtZGlzYWJsZS1uZXh0LWxpbmUgZGVwcmVjYXRpb24vZGVwcmVjYXRpb24KICAgICAgICAgIHRoaXMucG9wU2NvcGUoKTsKICAgICAgICAgIHJldHVybiByZXM7CiAgICAgICAgfSwKICAgICAgICBlID0+IHsKICAgICAgICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgICAgICAgdGhpcy5wb3BTY29wZSgpOwogICAgICAgICAgdGhyb3cgZTsKICAgICAgICB9LAogICAgICApOwogICAgfQoKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgdGhpcy5wb3BTY29wZSgpOwogICAgcmV0dXJuIG1heWJlUHJvbWlzZVJlc3VsdDsKICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICoKICAgKiBAZGVwcmVjYXRlZCBVc2UgYFNlbnRyeS5nZXRDbGllbnQoKWA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0KTsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgdGhpcy5nZXRJc29sYXRpb25TY29wZSgpLnNldENvbnRleHQobmFtZSwgY29udGV4dCk7CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqCiAgICogQGRlcHJlY2F0ZWQgVXNlIGBnZXRTY29wZSgpYCBkaXJlY3RseS4KICAgKi8KICAgY29uZmlndXJlU2NvcGUoY2FsbGJhY2spIHsKICAgIC8vIGVzbGludC1kaXNhYmxlLW5leHQtbGluZSBkZXByZWNhdGlvbi9kZXByZWNhdGlvbgogICAgY29uc3QgeyBzY29wZSwgY2xpZW50IH0gPSB0aGlzLmdldFN0YWNrVG9wKCk7CiAgICBpZiAoY2xpZW50KSB7CiAgICAgIGNhbGxiYWNrKHNjb3BlKTsKICAgIH0KICB9CgogIC8qKgogICAqIEBpbmhlcml0RG9jCiAgICovCiAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgIHJ1bihjYWxsYmFjaykgewogICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICBjb25zdCBvbGRIdWIgPSBtYWtlTWFpbih0aGlzKTsKICAgIHRyeSB7CiAgICAgIGNhbGxiYWNrKHRoaXMpOwogICAgfSBmaW5hbGx5IHsKICAgICAgLy8gZXNsaW50LWRpc2FibGUtbmV4dC1saW5lIGRlcHJlY2F0aW9uL2RlcHJlY2F0aW9uCiAgICAgIG1ha2VNYWluKG9sZEh1Yik7CiAgICB9CiAgfQoKICAvKioKICAgKiBAaW5oZXJpdERvYwogICAqIEBkZXByZWNhdGVkIFVzZSBgU2VudHJ5LmdldENsaWVudCgpLmdldEludGVncmF0aW9uQnlOYW1lKClgIGluc3RlYWQuCiAgICovCiAgIGdldEludGVncmF0aW9uKGludGVnc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ICAgICAgY29uc3QgZmlyc3RDb2xvbiA9IGhlYWRlci5pbmRleE9mKCc6Jyk7CiAgICAgICAgaWYgKGZpcnN0Q29sb24gPT09IC0xKSB7CiAgICAgICAgICBzb2NrZXQuZGVzdHJveSgpOwogICAgICAgICAgcmV0dXJuIHJlamVjdChuZXcgRXJyb3IoYEludmFsaWQgaGVhZGVyIGZyb20gcHJveHkgQ09OTkVDVCByZXNwb25zZTogIiR7aGVhZGVyfSJgKSk7CiAgICAgICAgfQogICAgICAgIGNvbnN0IGtleSA9IGhlYWRlci5zbGljZSgwLCBmaXJzdENvbG9uKS50b0xvd2VyQ2FzZSgpOwogICAgICAgIGNvbnN0IHZhbHVlID0gaGVhZGVyLnNsaWNlKGZpcnN0Q29sb24gKyAxKS50cmltU3RhcnQoKTsKICAgICAgICBjb25zdCBjdXJyZW50ID0gaGVhZGVyc1trZXldOwogICAgICAgIGlmICh0eXBlb2YgY3VycmVudCA9PT0gJ3N0cmluZycpIHsKICAgICAgICAgIGhlYWRlcnNba2V5XSA9IFtjdXJyZW50LCB2YWx1ZV07CiAgICAgICAgfSBlbHNlIGlmIChBcnJheS5pc0FycmF5KGN1cnJlbnQpKSB7CiAgICAgICAgICBjdXJyZW50LnB1c2godmFsdWUpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICBoZWFkZXJzW2tleV0gPSB2YWx1ZTsKICAgICAgICB9CiAgICAgIH0KICAgICAgZGVidWckMSgnZ290IHByb3h5IHNlcnZlciByZXNwb25zZTogJW8gJW8nLCBmaXJzdExpbmUsIGhlYWRlcnMpOwogICAgICBjbGVhbnVwKCk7CiAgICAgIHJlc29sdmUoewogICAgICAgIGNvbm5lY3Q6IHsKICAgICAgICAgIHN0YXR1c0NvZGUsCiAgICAgICAgICBzdGF0dXNUZXh0LAogICAgICAgICAgaGVhZGVycywKICAgICAgICB9LAogICAgICAgIGJ1ZmZlcmVkLAogICAgICB9KTsKICAgIH0KCiAgICBzb2NrZXQub24oJ2Vycm9yJyw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KHJlc29sdmUsIHJlamVjdCkgPT4gewogICAgICBsZXQgYm9keSA9IHN0cmVhbUZyb21Cb2R5KHJlcXVlc3QuYm9keSk7CgogICAgICBjb25zdCBoZWFkZXJzID0geyAuLi5vcHRpb25zLmhlYWRlcnMgfTsKCiAgICAgIGlmIChyZXF1ZXN0LmJvZHkubGVuZ3RoID4gR1pJUF9USFJFU0hPTEQpIHsKICAgICAgICBoZWFkZXJzWydjb250ZW50LWVuY29kaW5nJ10gPSAnZ3ppcCc7CiAgICAgICAgYm9keSA9IGJvZHkucGlwZShjcmVhdGVHemlwKCkpOwogICAgICB9CgogICAgICBjb25zdCByZXEgPSBodHRwTW9kdWxlLnJlcXVlc3QoCiAgICAgICAgewogICAgICAgICAgbWV0aG9kOiAnUE9TVCcsCiAgICAgICAgICBhZ2VudCwKICAgICAgICAgIGhlYWRlcnMsCiAgICAgICAgICBob3N0bmFtZSwKICAgICAgICAgIHBhdGg6IGAke3BhdGhuYW1lfSR7c2VhcmNofWAsCiAgICAgICAgICBwb3J0LAogICAgICAgICAgcHJvdG9jb2wsCiAgICAgICAgICBjYTogb3B0aW9ucy5jYUNlcnRzLAogICAgICAgIH0sCiAgICAgICAgcmVzID0+IHsKICAgICAgICAgIHJlcy5vbignZGF0YScsICgpID0+IHsKICAgICAgICAgICAgLy8gRHJhaW4gc29ja2V0CiAgICAgICAgICB9KTsKCiAgICAgICAgICByZXMub24oJ2VuZCcsICgpID0+IHsKICAgICAgICAgICAgLy8gRHJhaW4gc29ja2V0CiAgICAgICAgICB9KTsKCiAgICAgICAgICByZXMuc2V0RW5jb2RpbmcoJ3V0ZjgnKTsKCiAgICAgICAgICAvLyAiS2V5LXZhbHVlIHBhaXJzIG9mIGhlYWRlciBuYW1lcyBhbmQgdmFsdWVzLiBIZWFkZXIgbmFtZXMgYXJlIGxvd2VyLWNhc2VkLiIKICAgICAgICAgIC8vIGh0dHBzOi8vbm9kZWpzLm9yZy9hcGkvaHR0cC5odG1sI2h0dHBfbWV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Agc2lsZW50OiB0cnVlLAogICAgICAgICAgLy8gU2VyaWFsaXplIHRoZSByZXN1bHQgdG8ganNvbiBvdGhlcndpc2Ugb25seSBwcmltaXRpdmVzIGFyZSBzdXBwb3J0ZWQKICAgICAgICAgIHJldHVybkJ5VmFsdWU6IHRydWUsCiAgICAgICAgfSwKICAgICAgICAoZXJyLCBwYXJhbSkgPT4gewogICAgICAgICAgaWYgKGVycikgewogICAgICAgICAgICBsb2coYEVycm9yIGV4ZWN1dGluZyBzY3JpcHQ6ICcke2Vyci5tZXNzYWdlfSdgKTsKICAgICAgICAgIH0KCiAgICAgICAgICBjb25zdCBzY29wZXMgPSBwYXJhbSAmJiBwYXJhbS5yZXN1bHQgPyAocGFyYW0ucmVzdWx0LnZhbHVlICkgOiB1bmRlZmluZWQ7CgogICAgICAgICAgc2Vzc2lvbi5wb3N0KCdEZWJ1Z2dlci5yZXN1bWUnKTsKICAgICAgICAgIHNlc3Npb24ucG9zdCgnRGVidWdnZXIuZGlzYWJsZScpOwoKICAgICAgICAgIHNlbmRBbnJFdmVudChzdGFja0ZyYW1lcywgc2NvcGVzKS50aGVuKG51bGwsICgpID0+IHsKICAgICAgICAgICAgbG9nKCdTZW5kaW5nIEFOUiBldmVudCBmYWlsZWQuJyk7CiAgICAgICAgICB9KTsKICAgICAgICB9LAogICAgICApOwogICAgfSBjYXRjaCAoZSkgewogICAgICBzZXNzaW9uLnBvc3QoJ0RlYnVnZ2VyLnJlc3VtZScpOwogICAgICBzZXNzaW9uLnBvc3QoJ0RlYnVnZ2VyLmRpc2FibGUnKTsKICAgICAgdGhyb3cgZTsKICAgIH0KICB9KTsKCiAgZGVidWdnZXJQYXVzZSA9ICgpID0+IHsKICAgIHRyeSB7CiAgICAgIHNlc3Npb24ucG9zdCgnRGVidWdnZXIuZW5hYmxlJywgKCkgPT4gewogICAgICAgIHNlc3Npb24ucG9zdCgnRGVidWdnZXIucGF1c2UnKTsKICAgICAgfSk7CiAgICB9IGNhdGNoIChfKS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2hkb2dUaW1lb3V0KTsKCl9vcHRpb25hbENoYWluKFtwYXJlbnRQb3J0LCAnb3B0aW9uYWxBY2Nlc3MnLCBfNiA9PiBfNi5vbiwgJ2NhbGwnLCBfNyA9PiBfNygnbWVzc2FnZScsIChtc2cpID0+IHsKICBpZiAobXNnLnNlc3Npb24pIHsKICAgIHNlc3Npb24gPSBtYWtlU2Vzc2lvbihtc2cuc2Vzc2lvbik7CiAgfQoKICBwb2xsKCk7Cn0pXSk7"; - running = _ref.running; - _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); +/***/ }), - if (running === 0 && _this.empty()) { - return _this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return _this.Events.trigger("error", e); - } - })(); - } +/***/ 66572: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function () { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; +const util = __nccwpck_require__(39023); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - if (this.queued() === 0) { - return this.Promise.resolve(null); +const INTEGRATION_NAME = 'Console'; + +const _consoleIntegration = (() => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + utils.addConsoleInstrumentationHandler(({ args, level }) => { + if (core.getClient() !== client) { + return; } - queue = this._queues.getFirst(); + core.addBreadcrumb( + { + category: 'console', + level: utils.severityLevelFromString(level), + message: util.format.apply(undefined, args), + }, + { + input: [...args], + level, + }, + ); + }); + }, + }; +}) ; - var _next2 = next = queue.first(); +const consoleIntegration = core.defineIntegration(_consoleIntegration); - options = _next2.options; - args = _next2.args; +/** + * Console module integration. + * @deprecated Use `consoleIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Console = core.convertIntegrationFnToClass(INTEGRATION_NAME, consoleIntegration) - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } +; - this.Events.trigger("debug", `Draining ${options.id}`, { - args, - options - }); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({ - success, - wait, - reservoir - }) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, { - success, - args, - options - }); +// eslint-disable-next-line deprecation/deprecation - if (success) { - queue.shift(); - empty = this.empty(); +exports.Console = Console; +exports.consoleIntegration = consoleIntegration; +//# sourceMappingURL=console.js.map - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } +/***/ }), - this._run(index, next, wait); +/***/ 54090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } +var { + _optionalChain +} = __nccwpck_require__(25304); - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then(drained => { - var newCapacity; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch(e => { - return this.Events.trigger("error", e); - }); - } +const child_process = __nccwpck_require__(35317); +const fs = __nccwpck_require__(79896); +const os = __nccwpck_require__(70857); +const path = __nccwpck_require__(16928); +const util = __nccwpck_require__(39023); +const core = __nccwpck_require__(75062); - _dropAllQueued(message) { - return this._queues.shiftAll(function (job) { - return job.doDrop({ - message - }); - }); - } +/* eslint-disable max-lines */ - stop(options = {}) { - var done, waitForExecuting; - options = parser.load(options, this.stopDefaults); +// TODO: Required until we drop support for Node v8 +const readFileAsync = util.promisify(fs.readFile); +const readDirAsync = util.promisify(fs.readdir); - waitForExecuting = at => { - var finished; +const INTEGRATION_NAME = 'Context'; - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; +const _nodeContextIntegration = ((options = {}) => { + let cachedContext; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; + const _options = { + app: true, + os: true, + device: true, + culture: true, + cloudResource: true, + ...options, + }; - done = options.dropWaitingJobs ? (this._run = function (index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; + /** Add contexts to the event. Caches the context so we only look it up once. */ + async function addContext(event) { + if (cachedContext === undefined) { + cachedContext = _getContexts(); + } - for (k in ref) { - v = ref[k]; + const updatedContext = _updateContext(await cachedContext); - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } + event.contexts = { + ...event.contexts, + app: { ...updatedContext.app, ..._optionalChain([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, + os: { ...updatedContext.os, ..._optionalChain([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, + device: { ...updatedContext.device, ..._optionalChain([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, + culture: { ...updatedContext.culture, ..._optionalChain([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, + cloud_resource: { ...updatedContext.cloud_resource, ..._optionalChain([event, 'access', _9 => _9.contexts, 'optionalAccess', _10 => _10.cloud_resource]) }, + }; - this._dropAllQueued(options.dropErrorMessage); + return event; + } - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); + /** Get the contexts from node. */ + async function _getContexts() { + const contexts = {}; - this._receive = function (job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; + if (_options.os) { + contexts.os = await getOsContext(); + } - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; + if (_options.app) { + contexts.app = getAppContext(); + } - return done; + if (_options.device) { + contexts.device = getDeviceContext(_options.device); } - _addToQueue(job) { - var _this2 = this; + if (_options.culture) { + const culture = getCultureContext(); - return _asyncToGenerator(function* () { - var args, blocked, error, options, reachedHWM, shifted, strategy; - args = job.args; - options = job.options; + if (culture) { + contexts.culture = culture; + } + } - try { - var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); + if (_options.cloudResource) { + contexts.cloud_resource = getCloudResourceContext(); + } - reachedHWM = _ref2.reachedHWM; - blocked = _ref2.blocked; - strategy = _ref2.strategy; - } catch (error1) { - error = error1; + return contexts; + } - _this2.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error - }); + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + return addContext(event); + }, + }; +}) ; - job.doDrop({ - error - }); - return false; - } +const nodeContextIntegration = core.defineIntegration(_nodeContextIntegration); - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; +/** + * Add node modules / packages to the event. + * @deprecated Use `nodeContextIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Context = core.convertIntegrationFnToClass(INTEGRATION_NAME, nodeContextIntegration) - if (shifted != null) { - shifted.doDrop(); - } +; - if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } +// eslint-disable-next-line deprecation/deprecation - return reachedHWM; - } - } +/** + * Updates the context with dynamic values that can change + */ +function _updateContext(contexts) { + // Only update properties if they exist + if (_optionalChain([contexts, 'optionalAccess', _11 => _11.app, 'optionalAccess', _12 => _12.app_memory])) { + contexts.app.app_memory = process.memoryUsage().rss; + } - job.doQueue(reachedHWM, blocked); + if (_optionalChain([contexts, 'optionalAccess', _13 => _13.device, 'optionalAccess', _14 => _14.free_memory])) { + contexts.device.free_memory = os.freemem(); + } - _this2._queues.push(job); + return contexts; +} - yield _this2._drainAll(); - return reachedHWM; - })(); +/** + * Returns the operating system context. + * + * Based on the current platform, this uses a different strategy to provide the + * most accurate OS information. Since this might involve spawning subprocesses + * or accessing the file system, this should only be executed lazily and cached. + * + * - On macOS (Darwin), this will execute the `sw_vers` utility. The context + * has a `name`, `version`, `build` and `kernel_version` set. + * - On Linux, this will try to load a distribution release from `/etc` and set + * the `name`, `version` and `kernel_version` fields. + * - On all other platforms, only a `name` and `version` will be returned. Note + * that `version` might actually be the kernel version. + */ +async function getOsContext() { + const platformId = os.platform(); + switch (platformId) { + case 'darwin': + return getDarwinInfo(); + case 'linux': + return getLinuxInfo(); + default: + return { + name: PLATFORM_NAMES[platformId] || platformId, + version: os.release(), + }; + } +} + +function getCultureContext() { + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (typeof (process.versions ).icu !== 'string') { + // Node was built without ICU support + return; } - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + // Check that node was built with full Intl support. Its possible it was built without support for non-English + // locales which will make resolvedOptions inaccurate + // + // https://nodejs.org/api/intl.html#detecting-internationalization-support + const january = new Date(9e8); + const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); + if (spanish.format(january) === 'enero') { + const options = Intl.DateTimeFormat().resolvedOptions(); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } + return { + locale: options.locale, + timezone: options.timeZone, + }; } + } catch (err) { + // + } - submit(...args) { - var cb, fn, job, options, ref, ref1, task; + return; +} - if (typeof args[0] === "function") { - var _ref3, _ref4, _splice$call, _splice$call2; +function getAppContext() { + const app_memory = process.memoryUsage().rss; + const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); - options = parser.load({}, this.jobDefaults); - } else { - var _ref5, _ref6, _splice$call3, _splice$call4; + return { app_start_time, app_memory }; +} - ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - options = parser.load(options, this.jobDefaults); - } +/** + * Gets device information from os + */ +function getDeviceContext(deviceOpt) { + const device = {}; - task = (...args) => { - return new this.Promise(function (resolve, reject) { - return fn(...args, function (...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - - job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function (args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function (args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } - - schedule(...args) { - var job, options, task; + // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202 + let uptime; + try { + uptime = os.uptime && os.uptime(); + } catch (e) { + // noop + } - if (typeof args[0] === "function") { - var _args = args; + // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). + // Hence, we only set boot time, if we get a valid uptime value. + // @see https://github.com/getsentry/sentry-javascript/issues/5856 + if (typeof uptime === 'number') { + device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); + } - var _args2 = _toArray(_args); + device.arch = os.arch(); - task = _args2[0]; - args = _args2.slice(1); - options = {}; - } else { - var _args3 = args; + if (deviceOpt === true || deviceOpt.memory) { + device.memory_size = os.totalmem(); + device.free_memory = os.freemem(); + } - var _args4 = _toArray(_args3); + if (deviceOpt === true || deviceOpt.cpu) { + const cpuInfo = os.cpus(); + if (cpuInfo && cpuInfo.length) { + const firstCpu = cpuInfo[0]; - options = _args4[0]; - task = _args4[1]; - args = _args4.slice(2); - } + device.processor_count = cpuInfo.length; + device.cpu_description = firstCpu.model; + device.processor_frequency = firstCpu.speed; + } + } - job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + return device; +} - this._receive(job); +/** Mapping of Node's platform names to actual OS names. */ +const PLATFORM_NAMES = { + aix: 'IBM AIX', + freebsd: 'FreeBSD', + openbsd: 'OpenBSD', + sunos: 'SunOS', + win32: 'Windows', +}; - return job.promise; - } +/** Linux version file to check for a distribution. */ - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); +/** Mapping of linux release files located in /etc to distributions. */ +const LINUX_DISTROS = [ + { name: 'fedora-release', distros: ['Fedora'] }, + { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, + { name: 'redhat_version', distros: ['Red Hat Linux'] }, + { name: 'SuSE-release', distros: ['SUSE Linux'] }, + { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, + { name: 'debian_version', distros: ['Debian'] }, + { name: 'debian_release', distros: ['Debian'] }, + { name: 'arch-release', distros: ['Arch Linux'] }, + { name: 'gentoo-release', distros: ['Gentoo Linux'] }, + { name: 'novell-release', distros: ['SUSE Linux'] }, + { name: 'alpine-release', distros: ['Alpine Linux'] }, +]; - wrapped = function wrapped(...args) { - return schedule(fn.bind(this), ...args); - }; +/** Functions to extract the OS version from Linux release files. */ +const LINUX_VERSIONS - wrapped.withOptions = function (options, ...args) { - return schedule(options, fn, ...args); - }; + = { + alpine: content => content, + arch: content => matchFirst(/distrib_release=(.*)/, content), + centos: content => matchFirst(/release ([^ ]+)/, content), + debian: content => content, + fedora: content => matchFirst(/release (..)/, content), + mint: content => matchFirst(/distrib_release=(.*)/, content), + red: content => matchFirst(/release ([^ ]+)/, content), + suse: content => matchFirst(/VERSION = (.*)\n/, content), + ubuntu: content => matchFirst(/distrib_release=(.*)/, content), +}; - return wrapped; - } +/** + * Executes a regular expression with one capture group. + * + * @param regex A regular expression to execute. + * @param text Content to execute the RegEx on. + * @returns The captured string if matched; otherwise undefined. + */ +function matchFirst(regex, text) { + const match = regex.exec(text); + return match ? match[1] : undefined; +} - updateSettings(options = {}) { - var _this3 = this; +/** Loads the macOS operating system context. */ +async function getDarwinInfo() { + // Default values that will be used in case no operating system information + // can be loaded. The default version is computed via heuristics from the + // kernel version, but the build ID is missing. + const darwinInfo = { + kernel_version: os.release(), + name: 'Mac OS X', + version: `10.${Number(os.release().split('.')[0]) - 4}`, + }; - return _asyncToGenerator(function* () { - yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); - parser.overwrite(options, _this3.instanceDefaults, _this3); - return _this3; - })(); - } + try { + // We try to load the actual macOS version by executing the `sw_vers` tool. + // This tool should be available on every standard macOS installation. In + // case this fails, we stick with the values computed above. + + const output = await new Promise((resolve, reject) => { + child_process.execFile('/usr/bin/sw_vers', (error, stdout) => { + if (error) { + reject(error); + return; + } + resolve(stdout); + }); + }); - currentReservoir() { - return this._store.__currentReservoir__(); - } + darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); + darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); + darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); + } catch (e) { + // ignore + } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } + return darwinInfo; +} - } +/** Returns a distribution identifier to look up version callbacks. */ +function getLinuxDistroId(name) { + return name.split(' ')[0].toLowerCase(); +} - ; - Bottleneck.default = Bottleneck; - Bottleneck.Events = Events; - Bottleneck.version = Bottleneck.prototype.version = (__nccwpck_require__(82636)/* .version */ .i); - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(93529); - Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(53068); - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(29992); - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(47710); - Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(85442); - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." +/** Loads the Linux operating system context. */ +async function getLinuxInfo() { + // By default, we cannot assume anything about the distribution or Linux + // version. `os.release()` returns the kernel version and we assume a generic + // "Linux" name, which will be replaced down below. + const linuxInfo = { + kernel_version: os.release(), + name: 'Linux', }; - return Bottleneck; -}.call(void 0); - -module.exports = Bottleneck; -/***/ }), + try { + // We start guessing the distribution by listing files in the /etc + // directory. This is were most Linux distributions (except Knoppix) store + // release files with certain distribution-dependent meta data. We search + // for exactly one known file defined in `LINUX_DISTROS` and exit if none + // are found. In case there are more than one file, we just stick with the + // first one. + const etcFiles = await readDirAsync('/etc'); + const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); + if (!distroFile) { + return linuxInfo; + } + + // Once that file is known, load its contents. To make searching in those + // files easier, we lowercase the file contents. Since these files are + // usually quite small, this should not allocate too much memory and we only + // hold on to it for a very short amount of time. + const distroPath = path.join('/etc', distroFile.name); + const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); + + // Some Linux distributions store their release information in the same file + // (e.g. RHEL and Centos). In those cases, we scan the file for an + // identifier, that basically consists of the first word of the linux + // distribution name (e.g. "red" for Red Hat). In case there is no match, we + // just assume the first distribution in our list. + const { distros } = distroFile; + linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; + + // Based on the found distribution, we can now compute the actual version + // number. This is different for every distribution, so several strategies + // are computed in `LINUX_VERSIONS`. + const id = getLinuxDistroId(linuxInfo.name); + linuxInfo.version = LINUX_VERSIONS[id](contents); + } catch (e) { + // ignore + } -/***/ 93529: -/***/ ((module) => { + return linuxInfo; +} -"use strict"; +/** + * Grabs some information about hosting provider based on best effort. + */ +function getCloudResourceContext() { + if (process.env.VERCEL) { + // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables + return { + 'cloud.provider': 'vercel', + 'cloud.region': process.env.VERCEL_REGION, + }; + } else if (process.env.AWS_REGION) { + // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html + return { + 'cloud.provider': 'aws', + 'cloud.region': process.env.AWS_REGION, + 'cloud.platform': process.env.AWS_EXECUTION_ENV, + }; + } else if (process.env.GCP_PROJECT) { + // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables + return { + 'cloud.provider': 'gcp', + }; + } else if (process.env.ALIYUN_REGION_ID) { + // TODO: find where I found these environment variables - at least gc.github.com returns something + return { + 'cloud.provider': 'alibaba_cloud', + 'cloud.region': process.env.ALIYUN_REGION_ID, + }; + } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) { + // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment + return { + 'cloud.provider': 'azure', + 'cloud.region': process.env.REGION_NAME, + }; + } else if (process.env.IBM_CLOUD_REGION) { + // TODO: find where I found these environment variables - at least gc.github.com returns something + return { + 'cloud.provider': 'ibm_cloud', + 'cloud.region': process.env.IBM_CLOUD_REGION, + }; + } else if (process.env.TENCENTCLOUD_REGION) { + // https://www.tencentcloud.com/document/product/583/32748 + return { + 'cloud.provider': 'tencent_cloud', + 'cloud.region': process.env.TENCENTCLOUD_REGION, + 'cloud.account.id': process.env.TENCENTCLOUD_APPID, + 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE, + }; + } else if (process.env.NETLIFY) { + // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables + return { + 'cloud.provider': 'netlify', + }; + } else if (process.env.FLY_REGION) { + // https://fly.io/docs/reference/runtime-environment/ + return { + 'cloud.provider': 'fly.io', + 'cloud.region': process.env.FLY_REGION, + }; + } else if (process.env.DYNO) { + // https://devcenter.heroku.com/articles/dynos#local-environment-variables + return { + 'cloud.provider': 'heroku', + }; + } else { + return undefined; + } +} +exports.Context = Context; +exports.getDeviceContext = getDeviceContext; +exports.nodeContextIntegration = nodeContextIntegration; +exports.readDirAsync = readDirAsync; +exports.readFileAsync = readFileAsync; +//# sourceMappingURL=context.js.map -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; /***/ }), -/***/ 38579: -/***/ ((module) => { +/***/ 11367: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +var { + _optionalChain +} = __nccwpck_require__(25304); +Object.defineProperty(exports, "__esModule", ({ value: true })); -var DLList; -DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } +const fs = __nccwpck_require__(79896); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - push(value) { - var node; - this.length++; +const FILE_CONTENT_CACHE = new utils.LRUMap(100); +const DEFAULT_LINES_OF_CONTEXT = 7; +const INTEGRATION_NAME = 'ContextLines'; - if (typeof this.incr === "function") { - this.incr(); - } +// TODO: Replace with promisify when minimum supported node >= v8 +function readTextFileAsync(path) { + return new Promise((resolve, reject) => { + fs.readFile(path, 'utf8', (err, data) => { + if (err) reject(err); + else resolve(data); + }); + }); +} - node = { - value, - prev: this._last, - next: null - }; +const _contextLinesIntegration = ((options = {}) => { + const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + return addSourceContext(event, contextLines); + }, + }; +}) ; - return void 0; - } +const contextLinesIntegration = core.defineIntegration(_contextLinesIntegration); - shift() { - var value; +/** + * Add node modules / packages to the event. + * @deprecated Use `contextLinesIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const ContextLines = core.convertIntegrationFnToClass(INTEGRATION_NAME, contextLinesIntegration) - if (this._first == null) { - return; - } else { - this.length--; +; - if (typeof this.decr === "function") { - this.decr(); - } - } +async function addSourceContext(event, contextLines) { + // keep a lookup map of which files we've already enqueued to read, + // so we don't enqueue the same file multiple times which would cause multiple i/o reads + const enqueuedReadSourceFileTasks = {}; + const readSourceFileTasks = []; - value = this._first.value; + if (contextLines > 0 && _optionalChain([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { + for (const exception of event.exception.values) { + if (!_optionalChain([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { + continue; + } - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; + // We want to iterate in reverse order as calling cache.get will bump the file in our LRU cache. + // This ends up prioritizes source context for frames at the top of the stack instead of the bottom. + for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) { + const frame = exception.stacktrace.frames[i]; + // Call cache.get to bump the file to the top of the cache and ensure we have not already + // enqueued a read operation for this filename + if (frame.filename && !enqueuedReadSourceFileTasks[frame.filename] && !FILE_CONTENT_CACHE.get(frame.filename)) { + readSourceFileTasks.push(_readSourceFile(frame.filename)); + enqueuedReadSourceFileTasks[frame.filename] = 1; + } + } } + } - return value; + // check if files to read > 0, if so, await all of them to be read before adding source contexts. + // Normally, Promise.all here could be short circuited if one of the promises rejects, but we + // are guarding from that by wrapping the i/o read operation in a try/catch. + if (readSourceFileTasks.length > 0) { + await Promise.all(readSourceFileTasks); } - first() { - if (this._first != null) { - return this._first.value; + // Perform the same loop as above, but this time we can assume all files are in the cache + // and attempt to add source context to frames. + if (contextLines > 0 && _optionalChain([event, 'access', _6 => _6.exception, 'optionalAccess', _7 => _7.values])) { + for (const exception of event.exception.values) { + if (exception.stacktrace && exception.stacktrace.frames) { + await addSourceContextToFrames(exception.stacktrace.frames, contextLines); + } } } - getArray() { - var node, ref, results; - node = this._first; - results = []; + return event; +} - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } +/** Adds context lines to frames */ +function addSourceContextToFrames(frames, contextLines) { + for (const frame of frames) { + // Only add context if we have a filename and it hasn't already been added + if (frame.filename && frame.context_line === undefined) { + const sourceFileLines = FILE_CONTENT_CACHE.get(frame.filename); - return results; + if (sourceFileLines) { + try { + utils.addContextToFrame(sourceFileLines, frame, contextLines); + } catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + } } +} - forEachShift(cb) { - var node; - node = this.shift(); +// eslint-disable-next-line deprecation/deprecation - while (node != null) { - cb(node), node = this.shift(); - } +/** + * Reads file contents and caches them in a global LRU cache. + * If reading fails, mark the file as null in the cache so we don't try again. + * + * @param filename filepath to read content from. + */ +async function _readSourceFile(filename) { + const cachedFile = FILE_CONTENT_CACHE.get(filename); - return void 0; + // We have already attempted to read this file and failed, do not try again + if (cachedFile === null) { + return null; } - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; + // We have a cache hit, return it + if (cachedFile !== undefined) { + return cachedFile; + } - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } + // Guard from throwing if readFile fails, this enables us to use Promise.all and + // not have it short circuiting if one of the promises rejects + since context lines are added + // on a best effort basis, we want to throw here anyways. - return results; + // If we made it to here, it means that our file is not cache nor marked as failed, so attempt to read it + let content = null; + try { + const rawFileContents = await readTextFileAsync(filename); + content = rawFileContents.split('\n'); + } catch (_) { + // if we fail, we will mark the file as null in the cache and short circuit next time we try to read it } -}; -module.exports = DLList; + FILE_CONTENT_CACHE.set(filename, content); + return content; +} + +exports.ContextLines = ContextLines; +exports.contextLinesIntegration = contextLinesIntegration; +//# sourceMappingURL=contextlines.js.map + /***/ }), -/***/ 107: -/***/ ((module) => { +/***/ 48322: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function isResponseObject(response) { + return response && (response ).statusCode !== undefined; +} -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function isErrorEvent(event) { + return event && (event ).error !== undefined; +} -var Events; -Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; +function sendErrorToSentry(errorData) { + core.captureException(errorData, { + mechanism: { + type: 'hapi', + handled: false, + data: { + function: 'hapiErrorPlugin', + }, + }, + }); +} - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } +const hapiErrorPlugin = { + name: 'SentryHapiErrorPlugin', + version: core.SDK_VERSION, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + register: async function (serverArg) { + const server = serverArg ; - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; + server.events.on('request', (request, event) => { + // eslint-disable-next-line deprecation/deprecation + const transaction = core.getActiveTransaction(); - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; + if (isErrorEvent(event)) { + sendErrorToSentry(event.error); + } - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; + if (transaction) { + transaction.setStatus('internal_error'); + transaction.end(); } - }; - } + }); + }, +}; - _addListener(name, status, cb) { - var base; +const hapiTracingPlugin = { + name: 'SentryHapiTracingPlugin', + version: core.SDK_VERSION, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + register: async function (serverArg) { + const server = serverArg ; - if ((base = this._events)[name] == null) { - base[name] = []; - } + server.ext('onPreHandler', (request, h) => { + const transaction = core.continueTrace( + { + sentryTrace: request.headers['sentry-trace'] || undefined, + baggage: request.headers['baggage'] || undefined, + }, + transactionContext => { + // eslint-disable-next-line deprecation/deprecation + return core.startTransaction({ + ...transactionContext, + op: 'hapi.request', + name: request.route.path, + description: `${request.route.method} ${request.path}`, + }); + }, + ); - this._events[name].push({ - cb, - status - }); + // eslint-disable-next-line deprecation/deprecation + core.getCurrentScope().setSpan(transaction); - return this.instance; - } + return h.continue; + }); - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + server.ext('onPreResponse', (request, h) => { + // eslint-disable-next-line deprecation/deprecation + const transaction = core.getActiveTransaction(); - trigger(name, ...args) { - var _this = this; + if (request.response && isResponseObject(request.response) && transaction) { + const response = request.response ; + response.header('sentry-trace', core.spanToTraceHeader(transaction)); - return _asyncToGenerator(function* () { - var e, promises; + const dynamicSamplingContext = utils.dynamicSamplingContextToSentryBaggageHeader( + core.getDynamicSamplingContextFromSpan(transaction), + ); - try { - if (name !== "debug") { - _this.trigger("debug", `Event triggered: ${name}`, args); + if (dynamicSamplingContext) { + response.header('baggage', dynamicSamplingContext); } + } - if (_this._events[name] == null) { - return; - } + return h.continue; + }); - _this._events[name] = _this._events[name].filter(function (listener) { - return listener.status !== "none"; - }); - promises = _this._events[name].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (listener) { - var e, returned; + server.ext('onPostHandler', (request, h) => { + // eslint-disable-next-line deprecation/deprecation + const transaction = core.getActiveTransaction(); - if (listener.status === "none") { - return; - } + if (transaction) { + if (request.response && isResponseObject(request.response)) { + core.setHttpStatus(transaction, request.response.statusCode); + } - if (listener.status === "once") { - listener.status = "none"; - } + transaction.end(); + } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + return h.continue; + }); + }, +}; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return yield returned; - } else { - return returned; - } - } catch (error) { - e = error; +const INTEGRATION_NAME = 'Hapi'; - if (true) { - _this.trigger("error", e); - } +const _hapiIntegration = ((options = {}) => { + const server = options.server ; - return null; - } - }); + return { + name: INTEGRATION_NAME, + setupOnce() { + if (!server) { + return; + } - return function (_x) { - return _ref.apply(this, arguments); - }; - }()); - return (yield Promise.all(promises)).find(function (x) { - return x != null; - }); - } catch (error) { - e = error; + utils.fill(server, 'start', (originalStart) => { + return async function () { + await this.register(hapiTracingPlugin); + await this.register(hapiErrorPlugin); + const result = originalStart.apply(this); + return result; + }; + }); + }, + }; +}) ; - if (true) { - _this.trigger("error", e); - } +const hapiIntegration = core.defineIntegration(_hapiIntegration); - return null; - } - })(); - } +/** + * Hapi Framework Integration. + * @deprecated Use `hapiIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Hapi = core.convertIntegrationFnToClass(INTEGRATION_NAME, hapiIntegration); -}; -module.exports = Events; +// eslint-disable-next-line deprecation/deprecation -/***/ }), +exports.Hapi = Hapi; +exports.hapiErrorPlugin = hapiErrorPlugin; +exports.hapiIntegration = hapiIntegration; +exports.hapiTracingPlugin = hapiTracingPlugin; +//# sourceMappingURL=index.js.map -/***/ 53068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 32649: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +var { + _optionalChain +} = __nccwpck_require__(25304); -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +Object.defineProperty(exports, "__esModule", ({ value: true })); -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(32767); +const nodeVersion = __nccwpck_require__(29421); +const http = __nccwpck_require__(715); + +const _httpIntegration = ((options = {}) => { + const { breadcrumbs, tracing, shouldCreateSpanForRequest } = options; + + const convertedOptions = { + breadcrumbs, + tracing: + tracing === false + ? false + : utils.dropUndefinedKeys({ + // If tracing is forced to `true`, we don't want to set `enableIfHasTracingEnabled` + enableIfHasTracingEnabled: tracing === true ? undefined : true, + shouldCreateSpanForRequest, + }), + }; -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + // eslint-disable-next-line deprecation/deprecation + return new Http(convertedOptions) ; +}) ; -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/** + * The http module integration instruments Node's internal http module. It creates breadcrumbs, spans for outgoing + * http requests, and attaches trace data when tracing is enabled via its `tracing` option. + * + * By default, this will always create breadcrumbs, and will create spans if tracing is enabled. + */ +const httpIntegration = core.defineIntegration(_httpIntegration); -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +/** + * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing + * http requests and attaches trace data when tracing is enabled via its `tracing` option. + * + * @deprecated Use `httpIntegration()` instead. + */ +class Http { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Http';} -var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -Scripts = __nccwpck_require__(4169); + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + __init() {this.name = Http.id;} -Group = function () { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser.load(this.limiterOptions, this.defaults, this); - this.Events = new Events(this); - this.instances = {}; - this.Bottleneck = __nccwpck_require__(83911); + /** + * @inheritDoc + */ + constructor(options = {}) {Http.prototype.__init.call(this); + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; + } - this._startAutoCleanup(); + /** + * @inheritDoc + */ + setupOnce( + _addGlobalEventProcessor, + // eslint-disable-next-line deprecation/deprecation + setupOnceGetCurrentHub, + ) { + // eslint-disable-next-line deprecation/deprecation + const clientOptions = _optionalChain([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - this.sharedConnection = this.connection != null; + // If `tracing` is not explicitly set, we default this based on whether or not tracing is enabled. + // But for compatibility, we only do that if `enableIfHasTracingEnabled` is set. + const shouldCreateSpans = _shouldCreateSpans(this._tracing, clientOptions); - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } - } + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !shouldCreateSpans) { + return; } - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); + // Do not auto-instrument for other instrumenter + if (clientOptions && clientOptions.instrumenter !== 'sentry') { + debugBuild.DEBUG_BUILD && utils.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); + return; } - deleteKey(key = "") { - var _this = this; + const shouldCreateSpanForRequest = _getShouldCreateSpanForRequest(shouldCreateSpans, this._tracing, clientOptions); - return _asyncToGenerator(function* () { - var deleted, instance; - instance = _this.instances[key]; + // eslint-disable-next-line deprecation/deprecation + const tracePropagationTargets = _optionalChain([clientOptions, 'optionalAccess', _6 => _6.tracePropagationTargets]) || _optionalChain([this, 'access', _7 => _7._tracing, 'optionalAccess', _8 => _8.tracePropagationTargets]); + + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpModule = __nccwpck_require__(58611); + const wrappedHttpHandlerMaker = _createWrappedRequestMethodFactory( + httpModule, + this._breadcrumbs, + shouldCreateSpanForRequest, + tracePropagationTargets, + ); + utils.fill(httpModule, 'get', wrappedHttpHandlerMaker); + utils.fill(httpModule, 'request', wrappedHttpHandlerMaker); + + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (nodeVersion.NODE_VERSION.major > 8) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpsModule = __nccwpck_require__(65692); + const wrappedHttpsHandlerMaker = _createWrappedRequestMethodFactory( + httpsModule, + this._breadcrumbs, + shouldCreateSpanForRequest, + tracePropagationTargets, + ); + utils.fill(httpsModule, 'get', wrappedHttpsHandlerMaker); + utils.fill(httpsModule, 'request', wrappedHttpsHandlerMaker); + } + } +}Http.__initStatic(); - if (_this.connection) { - deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); - } +// for ease of reading below - if (instance != null) { - delete _this.instances[key]; - yield instance.disconnect(); - } +/** + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) + * + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * + * @returns A function which accepts the exiting handler and returns a wrapped handler + */ +function _createWrappedRequestMethodFactory( + httpModule, + breadcrumbsEnabled, + shouldCreateSpanForRequest, + tracePropagationTargets, +) { + // We're caching results so we don't have to recompute regexp every time we create a request. + const createSpanUrlMap = new utils.LRUMap(100); + const headersUrlMap = new utils.LRUMap(100); - return instance != null || deleted > 0; - })(); + const shouldCreateSpan = (url) => { + if (shouldCreateSpanForRequest === undefined) { + return true; } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; + const cachedDecision = createSpanUrlMap.get(url); + if (cachedDecision !== undefined) { + return cachedDecision; + } - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } + const decision = shouldCreateSpanForRequest(url); + createSpanUrlMap.set(url, decision); + return decision; + }; - return results; + const shouldAttachTraceData = (url) => { + if (tracePropagationTargets === undefined) { + return true; } - keys() { - return Object.keys(this.instances); + const cachedDecision = headersUrlMap.get(url); + if (cachedDecision !== undefined) { + return cachedDecision; } - clusterKeys() { - var _this2 = this; - - return _asyncToGenerator(function* () { - var cursor, end, found, i, k, keys, len, next, start; + const decision = utils.stringMatchesSomePattern(url, tracePropagationTargets); + headersUrlMap.set(url, decision); + return decision; + }; - if (_this2.connection == null) { - return _this2.Promise.resolve(_this2.keys()); - } + /** + * Captures Breadcrumb based on provided request/response pair + */ + function addRequestBreadcrumb( + event, + requestSpanData, + req, + res, + ) { + // eslint-disable-next-line deprecation/deprecation + if (!core.getCurrentHub().getIntegration(Http)) { + return; + } - keys = []; - cursor = null; - start = `b_${_this2.id}-`.length; - end = "_settings".length; + core.addBreadcrumb( + { + category: 'http', + data: { + status_code: res && res.statusCode, + ...requestSpanData, + }, + type: 'http', + }, + { + event, + request: req, + response: res, + }, + ); + } - while (cursor !== 0) { - var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); + return function wrappedRequestMethodFactory(originalRequestMethod) { + return function wrappedMethod( ...args) { + const requestArgs = http.normalizeRequestArgs(httpModule, args); + const requestOptions = requestArgs[0]; + // eslint-disable-next-line deprecation/deprecation + const rawRequestUrl = http.extractRawUrl(requestOptions); + const requestUrl = http.extractUrl(requestOptions); + const client = core.getClient(); + + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method + if (core.isSentryRequestUrl(requestUrl, client)) { + return originalRequestMethod.apply(httpModule, requestArgs); + } + + const scope = core.getCurrentScope(); + const isolationScope = core.getIsolationScope(); + const parentSpan = core.getActiveSpan(); + + const data = getRequestSpanData(requestUrl, requestOptions); + + const requestSpan = shouldCreateSpan(rawRequestUrl) + ? // eslint-disable-next-line deprecation/deprecation + _optionalChain([parentSpan, 'optionalAccess', _9 => _9.startChild, 'call', _10 => _10({ + op: 'http.client', + origin: 'auto.http.node.http', + description: `${data['http.method']} ${data.url}`, + data, + })]) + : undefined; + + if (client && shouldAttachTraceData(rawRequestUrl)) { + const { traceId, spanId, sampled, dsc } = { + ...isolationScope.getPropagationContext(), + ...scope.getPropagationContext(), + }; - var _ref2 = _slicedToArray(_ref, 2); + const sentryTraceHeader = requestSpan + ? core.spanToTraceHeader(requestSpan) + : utils.generateSentryTraceHeader(traceId, spanId, sampled); - next = _ref2[0]; - found = _ref2[1]; - cursor = ~~next; + const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader( + dsc || + (requestSpan + ? core.getDynamicSamplingContextFromSpan(requestSpan) + : core.getDynamicSamplingContextFromClient(traceId, client, scope)), + ); - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); + addHeadersToRequestOptions(requestOptions, requestUrl, sentryTraceHeader, sentryBaggageHeader); + } else { + debugBuild.DEBUG_BUILD && + utils.logger.log( + `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, + ); + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalRequestMethod + .apply(httpModule, requestArgs) + .once('response', function ( res) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', data, req, res); } - } - - return keys; - })(); - } - - _startAutoCleanup() { - var _this3 = this; - - var base; - clearInterval(this.interval); - return typeof (base = this.interval = setInterval( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e, k, ref, results, time, v; - time = Date.now(); - ref = _this3.instances; - results = []; - - for (k in ref) { - v = ref[k]; - - try { - if (yield v._store.__groupCheck__(time)) { - results.push(_this3.deleteKey(k)); - } else { - results.push(void 0); + if (requestSpan) { + if (res.statusCode) { + core.setHttpStatus(requestSpan, res.statusCode); } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); + requestSpan.updateName( + http.cleanSpanDescription(core.spanToJSON(requestSpan).description || '', requestOptions, req) || '', + ); + requestSpan.end(); } - } - - return results; - }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; - } + }) + .once('error', function () { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; - updateSettings(options = {}) { - parser.overwrite(options, this.defaults, this); - parser.overwrite(options, options, this.limiterOptions); + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', data, req); + } + if (requestSpan) { + core.setHttpStatus(requestSpan, 500); + requestSpan.updateName( + http.cleanSpanDescription(core.spanToJSON(requestSpan).description || '', requestOptions, req) || '', + ); + requestSpan.end(); + } + }); + }; + }; +} - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +function addHeadersToRequestOptions( + requestOptions, + requestUrl, + sentryTraceHeader, + sentryBaggageHeader, +) { + // Don't overwrite sentry-trace and baggage header if it's already set. + const headers = requestOptions.headers || {}; + if (headers['sentry-trace']) { + return; + } - disconnect(flush = true) { - var ref; + debugBuild.DEBUG_BUILD && + utils.logger.log(`[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `); - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + requestOptions.headers = { + ...requestOptions.headers, + 'sentry-trace': sentryTraceHeader, + // Setting a header to `undefined` will crash in node so we only set the baggage header when it's defined + ...(sentryBaggageHeader && + sentryBaggageHeader.length > 0 && { baggage: normalizeBaggageHeader(requestOptions, sentryBaggageHeader) }), + }; +} +function getRequestSpanData(requestUrl, requestOptions) { + const method = requestOptions.method || 'GET'; + const data = { + url: requestUrl, + 'http.method': method, + }; + if (requestOptions.hash) { + // strip leading "#" + data['http.fragment'] = requestOptions.hash.substring(1); } + if (requestOptions.search) { + // strip leading "?" + data['http.query'] = requestOptions.search.substring(1); + } + return data; +} - ; - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; - return Group; -}.call(void 0); +function normalizeBaggageHeader( + requestOptions, + sentryBaggageHeader, +) { + if (!requestOptions.headers || !requestOptions.headers.baggage) { + return sentryBaggageHeader; + } else if (!sentryBaggageHeader) { + return requestOptions.headers.baggage ; + } else if (Array.isArray(requestOptions.headers.baggage)) { + return [...requestOptions.headers.baggage, sentryBaggageHeader]; + } + // Type-cast explanation: + // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity + // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. + return [requestOptions.headers.baggage, sentryBaggageHeader] ; +} + +/** Exported for tests only. */ +function _shouldCreateSpans( + tracingOptions, + clientOptions, +) { + return tracingOptions === undefined + ? false + : tracingOptions.enableIfHasTracingEnabled + ? core.hasTracingEnabled(clientOptions) + : true; +} + +/** Exported for tests only. */ +function _getShouldCreateSpanForRequest( + shouldCreateSpans, + tracingOptions, + clientOptions, +) { + const handler = shouldCreateSpans + ? // eslint-disable-next-line deprecation/deprecation + _optionalChain([tracingOptions, 'optionalAccess', _11 => _11.shouldCreateSpanForRequest]) || _optionalChain([clientOptions, 'optionalAccess', _12 => _12.shouldCreateSpanForRequest]) + : () => false; -module.exports = Group; + return handler; +} -/***/ }), +exports.Http = Http; +exports._getShouldCreateSpanForRequest = _getShouldCreateSpanForRequest; +exports._shouldCreateSpans = _shouldCreateSpans; +exports.httpIntegration = httpIntegration; +//# sourceMappingURL=http.js.map -/***/ 47710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 63293: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +Object.defineProperty(exports, "__esModule", ({ value: true })); -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +const console = __nccwpck_require__(66572); +const http = __nccwpck_require__(32649); +const onuncaughtexception = __nccwpck_require__(83790); +const onunhandledrejection = __nccwpck_require__(28798); +const modules = __nccwpck_require__(94288); +const contextlines = __nccwpck_require__(11367); +const context = __nccwpck_require__(54090); +const core = __nccwpck_require__(75062); +const index = __nccwpck_require__(8705); +const index$1 = __nccwpck_require__(32094); +const spotlight = __nccwpck_require__(16733); +const index$2 = __nccwpck_require__(19137); +const index$3 = __nccwpck_require__(48322); + +/* eslint-disable deprecation/deprecation */ + +exports.Console = console.Console; +exports.Http = http.Http; +exports.OnUncaughtException = onuncaughtexception.OnUncaughtException; +exports.OnUnhandledRejection = onunhandledrejection.OnUnhandledRejection; +exports.Modules = modules.Modules; +exports.ContextLines = contextlines.ContextLines; +exports.Context = context.Context; +exports.RequestData = core.RequestData; +exports.LocalVariables = index.LocalVariables; +exports.Undici = index$1.Undici; +exports.Spotlight = spotlight.Spotlight; +exports.Anr = index$2.Anr; +exports.Hapi = index$3.Hapi; +//# sourceMappingURL=index.js.map -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +/***/ }), -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/***/ 55480: +/***/ ((__unused_webpack_module, exports) => { -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +Object.defineProperty(exports, "__esModule", ({ value: true })); -var Events, IORedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); +/** + * Creates a rate limiter that will call the disable callback when the rate limit is reached and the enable callback + * when a timeout has occurred. + * @param maxPerSecond Maximum number of calls per second + * @param enable Callback to enable capture + * @param disable Callback to disable capture + * @returns A function to call to increment the rate limiter count + */ +function createRateLimiter( + maxPerSecond, + enable, + disable, +) { + let count = 0; + let retrySeconds = 5; + let disabledTimeout = 0; -IORedisConnection = function () { - class IORedisConnection { - constructor(options = {}) { - parser.load(options, this.defaults, this); + setInterval(() => { + if (disabledTimeout === 0) { + if (count > maxPerSecond) { + retrySeconds *= 2; + disable(retrySeconds); - if (this.Redis == null) { - this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option. + // Cap at one day + if (retrySeconds > 86400) { + retrySeconds = 86400; + } + disabledTimeout = retrySeconds; } + } else { + disabledTimeout -= 1; - if (this.Events == null) { - this.Events = new Events(this); + if (disabledTimeout === 0) { + enable(); } + } - this.terminated = false; + count = 0; + }, 1000).unref(); - if (this.clusterNodes != null) { - this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); - this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); - } else if (this.client != null && this.client.duplicate == null) { - this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options); - } else { - if (this.client == null) { - this.client = new this.Redis(this.clientOptions); - } + return () => { + count += 1; + }; +} - this.subscriber = this.client.duplicate(); - } +// Add types for the exception event data - this.limiters = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - this._loadScripts(); +/** Could this be an anonymous function? */ +function isAnonymous(name) { + return name !== undefined && (name.length === 0 || name === '?' || name === ''); +} - return { - client: this.client, - subscriber: this.subscriber - }; - }); - } +/** Do the function names appear to match? */ +function functionNamesMatch(a, b) { + return a === b || (isAnonymous(a) && isAnonymous(b)); +} - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); +/** Creates a unique hash from stack frames */ +function hashFrames(frames) { + if (frames === undefined) { + return; + } - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + // Only hash the 10 most recent frames (ie. the last 10) + return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, ''); +} - if (client.status === "ready") { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } +/** + * We use the stack parser to create a unique hash from the exception stack trace + * This is used to lookup vars when the exception passes through the event processor + */ +function hashFromStack(stackParser, stack) { + if (stack === undefined) { + return undefined; + } - _loadScripts() { - return Scripts.names.forEach(name => { - return this.client.defineCommand(name, { - lua: Scripts.payload(name) - }); - }); - } + return hashFrames(stackParser(stack, 1)); +} - __runCommand__(cmd) { - var _this = this; +exports.createRateLimiter = createRateLimiter; +exports.functionNamesMatch = functionNamesMatch; +exports.hashFrames = hashFrames; +exports.hashFromStack = hashFromStack; +exports.isAnonymous = isAnonymous; +//# sourceMappingURL=common.js.map - return _asyncToGenerator(function* () { - var _, deleted; - yield _this.ready; +/***/ }), - var _ref = yield _this.client.pipeline([cmd]).exec(); +/***/ 8705: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var _ref2 = _slicedToArray(_ref, 1); +Object.defineProperty(exports, "__esModule", ({ value: true })); - var _ref2$ = _slicedToArray(_ref2[0], 2); +const localVariablesSync = __nccwpck_require__(37328); - _ = _ref2$[0]; - deleted = _ref2$[1]; - return deleted; - })(); - } +/** + * Adds local variables to exception frames. + * + * @deprecated Use `localVariablesIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const LocalVariables = localVariablesSync.LocalVariablesSync; +// eslint-disable-next-line deprecation/deprecation - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - return this.subscriber.subscribe(channel, () => { - this.limiters[channel] = instance; - return resolve(); - }); - }); - })); - } +const localVariablesIntegration = localVariablesSync.localVariablesSyncIntegration; - __removeLimiter__(instance) { - var _this2 = this; +exports.LocalVariables = LocalVariables; +exports.localVariablesIntegration = localVariablesIntegration; +//# sourceMappingURL=index.js.map - return [instance.channel(), instance.channel_client()].forEach( - /*#__PURE__*/ - function () { - var _ref3 = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield _this2.subscriber.unsubscribe(channel); - } - return delete _this2.limiters[channel]; - }); +/***/ }), - return function (_x) { - return _ref3.apply(this, arguments); - }; - }()); - } +/***/ 37328: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [keys.length].concat(keys, args, cb); - } +var { + _optionalChain +} = __nccwpck_require__(25304); - __scriptFn__(name) { - return this.client[name].bind(this.client); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const nodeVersion = __nccwpck_require__(29421); +const common = __nccwpck_require__(55480); - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } +/* eslint-disable max-lines */ - this.limiters = {}; - this.terminated = true; +/** Creates a container for callbacks to be called sequentially */ +function createCallbackList(complete) { + // A collection of callbacks to be executed last to first + let callbacks = []; - if (flush) { - return this.Promise.all([this.client.quit(), this.subscriber.quit()]); - } else { - this.client.disconnect(); - this.subscriber.disconnect(); - return this.Promise.resolve(); - } + let completedCalled = false; + function checkedComplete(result) { + callbacks = []; + if (completedCalled) { + return; } - + completedCalled = true; + complete(result); } - ; - IORedisConnection.prototype.datastore = "ioredis"; - IORedisConnection.prototype.defaults = { - Redis: null, - clientOptions: {}, - clusterNodes: null, - client: null, - Promise: Promise, - Events: null - }; - return IORedisConnection; -}.call(void 0); - -module.exports = IORedisConnection; + // complete should be called last + callbacks.push(checkedComplete); -/***/ }), + function add(fn) { + callbacks.push(fn); + } -/***/ 25949: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function next(result) { + const popped = callbacks.pop() || checkedComplete; -"use strict"; + try { + popped(result); + } catch (_) { + // If there is an error, we still want to call the complete callback + checkedComplete(result); + } + } + return { add, next }; +} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/** + * Promise API is available as `Experimental` and in Node 19 only. + * + * Callback-based API is `Stable` since v14 and `Experimental` since v8. + * Because of that, we are creating our own `AsyncSession` class. + * + * https://nodejs.org/docs/latest-v19.x/api/inspector.html#promises-api + * https://nodejs.org/docs/latest-v14.x/api/inspector.html + */ +class AsyncSession { -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + /** Throws if inspector API is not available */ + constructor() { + /* + TODO: We really should get rid of this require statement below for a couple of reasons: + 1. It makes the integration unusable in the SvelteKit SDK, as it's not possible to use `require` + in SvelteKit server code (at least not by default). + 2. Throwing in a constructor is bad practice + + More context for a future attempt to fix this: + We already tried replacing it with import but didn't get it to work because of async problems. + We still called import in the constructor but assigned to a promise which we "awaited" in + `configureAndConnect`. However, this broke the Node integration tests as no local variables + were reported any more. We probably missed a place where we need to await the promise, too. + */ -var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); + // Node can be built without inspector support so this can throw + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { Session } = __nccwpck_require__(50264); + this._session = new Session(); + } - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } + /** @inheritdoc */ + configureAndConnect(onPause, captureAll) { + this._session.connect(); - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; + this._session.on('Debugger.paused', event => { + onPause(event, () => { + // After the pause work is complete, resume execution or the exception context memory is leaked + this._session.post('Debugger.resume'); + }); }); - this.retryCount = 0; - } - - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } + this._session.post('Debugger.enable'); + this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' }); } - _randomIndex() { - return Math.random().toString(36).slice(2); + setPauseOnExceptions(captureAll) { + this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' }); } - doDrop({ - error, - message = "This job has been dropped by Bottleneck" - } = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError(message)); + /** @inheritdoc */ + getLocalVariables(objectId, complete) { + this._getProperties(objectId, props => { + const { add, next } = createCallbackList(complete); + + for (const prop of props) { + if (_optionalChain([prop, 'optionalAccess', _2 => _2.value, 'optionalAccess', _3 => _3.objectId]) && _optionalChain([prop, 'optionalAccess', _4 => _4.value, 'access', _5 => _5.className]) === 'Array') { + const id = prop.value.objectId; + add(vars => this._unrollArray(id, prop.name, vars, next)); + } else if (_optionalChain([prop, 'optionalAccess', _6 => _6.value, 'optionalAccess', _7 => _7.objectId]) && _optionalChain([prop, 'optionalAccess', _8 => _8.value, 'optionalAccess', _9 => _9.className]) === 'Object') { + const id = prop.value.objectId; + add(vars => this._unrollObject(id, prop.name, vars, next)); + } else if (_optionalChain([prop, 'optionalAccess', _10 => _10.value, 'optionalAccess', _11 => _11.value]) != null || _optionalChain([prop, 'optionalAccess', _12 => _12.value, 'optionalAccess', _13 => _13.description]) != null) { + add(vars => this._unrollOther(prop, vars, next)); + } } - this.Events.trigger("dropped", { - args: this.args, - options: this.options, - task: this.task, - promise: this.promise - }); - return true; - } else { - return false; - } + next({}); + }); } - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - - if (!(status === expected || expected === "DONE" && status === null)) { - throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } + /** + * Gets all the PropertyDescriptors of an object + */ + _getProperties(objectId, next) { + this._session.post( + 'Runtime.getProperties', + { + objectId, + ownProperties: true, + }, + (err, params) => { + if (err) { + next([]); + } else { + next(params.result); + } + }, + ); } - doReceive() { - this._states.start(this.options.id); + /** + * Unrolls an array property + */ + _unrollArray(objectId, name, vars, next) { + this._getProperties(objectId, props => { + vars[name] = props + .filter(v => v.name !== 'length' && !isNaN(parseInt(v.name, 10))) + .sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10)) + .map(v => _optionalChain([v, 'optionalAccess', _14 => _14.value, 'optionalAccess', _15 => _15.value])); + + next(vars); + }); + } - return this.Events.trigger("received", { - args: this.args, - options: this.options + /** + * Unrolls an object property + */ + _unrollObject(objectId, name, vars, next) { + this._getProperties(objectId, props => { + vars[name] = props + .map(v => [v.name, _optionalChain([v, 'optionalAccess', _16 => _16.value, 'optionalAccess', _17 => _17.value])]) + .reduce((obj, [key, val]) => { + obj[key] = val; + return obj; + }, {} ); + + next(vars); }); } - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); + /** + * Unrolls other properties + */ + _unrollOther(prop, vars, next) { + if (_optionalChain([prop, 'optionalAccess', _18 => _18.value, 'optionalAccess', _19 => _19.value]) != null) { + vars[prop.name] = prop.value.value; + } else if (_optionalChain([prop, 'optionalAccess', _20 => _20.value, 'optionalAccess', _21 => _21.description]) != null && _optionalChain([prop, 'optionalAccess', _22 => _22.value, 'optionalAccess', _23 => _23.type]) !== 'function') { + vars[prop.name] = `<${prop.value.description}>`; + } - this._states.next(this.options.id); + next(vars); + } +} - return this.Events.trigger("queued", { - args: this.args, - options: this.options, - reachedHWM, - blocked - }); +/** + * When using Vercel pkg, the inspector module is not available. + * https://github.com/getsentry/sentry-javascript/issues/6769 + */ +function tryNewAsyncSession() { + try { + return new AsyncSession(); + } catch (e) { + return undefined; } +} - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); +const INTEGRATION_NAME = 'LocalVariables'; - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); +/** + * Adds local variables to exception frames + */ +const _localVariablesSyncIntegration = (( + options = {}, + session = tryNewAsyncSession(), +) => { + const cachedFrames = new utils.LRUMap(20); + let rateLimiter; + let shouldProcessEvent = false; + + function handlePaused( + stackParser, + { params: { reason, data, callFrames } }, + complete, + ) { + if (reason !== 'exception' && reason !== 'promiseRejection') { + complete(); + return; } - return this.Events.trigger("scheduled", { - args: this.args, - options: this.options + _optionalChain([rateLimiter, 'optionalCall', _24 => _24()]); + + // data.description contains the original error.stack + const exceptionHash = common.hashFromStack(stackParser, _optionalChain([data, 'optionalAccess', _25 => _25.description])); + + if (exceptionHash == undefined) { + complete(); + return; + } + + const { add, next } = createCallbackList(frames => { + cachedFrames.set(exceptionHash, frames); + complete(); }); - } - doExecute(chained, clearGlobalState, run, free) { - var _this = this; + // Because we're queuing up and making all these calls synchronously, we can potentially overflow the stack + // For this reason we only attempt to get local variables for the first 5 frames + for (let i = 0; i < Math.min(callFrames.length, 5); i++) { + const { scopeChain, functionName, this: obj } = callFrames[i]; - return _asyncToGenerator(function* () { - var error, eventInfo, passed; + const localScope = scopeChain.find(scope => scope.type === 'local'); - if (_this.retryCount === 0) { - _this._assertStatus("RUNNING"); + // obj.className is undefined in ESM modules + const fn = obj.className === 'global' || !obj.className ? functionName : `${obj.className}.${functionName}`; - _this._states.next(_this.options.id); + if (_optionalChain([localScope, 'optionalAccess', _26 => _26.object, 'access', _27 => _27.objectId]) === undefined) { + add(frames => { + frames[i] = { function: fn }; + next(frames); + }); } else { - _this._assertStatus("EXECUTING"); + const id = localScope.object.objectId; + add(frames => + _optionalChain([session, 'optionalAccess', _28 => _28.getLocalVariables, 'call', _29 => _29(id, vars => { + frames[i] = { function: fn, vars }; + next(frames); + })]), + ); } + } - eventInfo = { - args: _this.args, - options: _this.options, - retryCount: _this.retryCount - }; + next([]); + } - _this.Events.trigger("executing", eventInfo); + function addLocalVariablesToException(exception) { + const hash = common.hashFrames(_optionalChain([exception, 'optionalAccess', _30 => _30.stacktrace, 'optionalAccess', _31 => _31.frames])); - try { - passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); + if (hash === undefined) { + return; + } - if (clearGlobalState()) { - _this.doDone(eventInfo); + // Check if we have local variables for an exception that matches the hash + // remove is identical to get but also removes the entry from the cache + const cachedFrame = cachedFrames.remove(hash); - yield free(_this.options, eventInfo); + if (cachedFrame === undefined) { + return; + } - _this._assertStatus("DONE"); + // Filter out frames where the function name is `new Promise` since these are in the error.stack frames + // but do not appear in the debugger call frames + const frames = (_optionalChain([exception, 'access', _32 => _32.stacktrace, 'optionalAccess', _33 => _33.frames]) || []).filter(frame => frame.function !== 'new Promise'); - return _this._resolve(passed); - } - } catch (error1) { - error = error1; - return _this._onFailure(error, eventInfo, clearGlobalState, run, free); + for (let i = 0; i < frames.length; i++) { + // Sentry frames are in reverse order + const frameIndex = frames.length - i - 1; + + // Drop out if we run out of frames to match up + if (!frames[frameIndex] || !cachedFrame[i]) { + break; } - })(); - } - doExpire(clearGlobalState, run, free) { - var error, eventInfo; + if ( + // We need to have vars to add + cachedFrame[i].vars === undefined || + // We're not interested in frames that are not in_app because the vars are not relevant + frames[frameIndex].in_app === false || + // The function names need to match + !common.functionNamesMatch(frames[frameIndex].function, cachedFrame[i].function) + ) { + continue; + } - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); + frames[frameIndex].vars = cachedFrame[i].vars; } + } - this._assertStatus("EXECUTING"); + function addLocalVariablesToEvent(event) { + for (const exception of _optionalChain([event, 'optionalAccess', _34 => _34.exception, 'optionalAccess', _35 => _35.values]) || []) { + addLocalVariablesToException(exception); + } - eventInfo = { - args: this.args, - options: this.options, - retryCount: this.retryCount - }; - error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); + return event; } - _onFailure(error, eventInfo, clearGlobalState, run, free) { - var _this2 = this; + return { + name: INTEGRATION_NAME, + setupOnce() { + const client = core.getClient(); + const clientOptions = _optionalChain([client, 'optionalAccess', _36 => _36.getOptions, 'call', _37 => _37()]); + + if (session && _optionalChain([clientOptions, 'optionalAccess', _38 => _38.includeLocalVariables])) { + // Only setup this integration if the Node version is >= v18 + // https://github.com/getsentry/sentry-javascript/issues/7697 + const unsupportedNodeVersion = nodeVersion.NODE_VERSION.major < 18; + + if (unsupportedNodeVersion) { + utils.logger.log('The `LocalVariables` integration is only supported on Node >= v18.'); + return; + } - return _asyncToGenerator(function* () { - var retry, retryAfter; + const captureAll = options.captureAllExceptions !== false; - if (clearGlobalState()) { - retry = yield _this2.Events.trigger("failed", error, eventInfo); + session.configureAndConnect( + (ev, complete) => + handlePaused(clientOptions.stackParser, ev , complete), + captureAll, + ); - if (retry != null) { - retryAfter = ~~retry; + if (captureAll) { + const max = options.maxExceptionsPerSecond || 50; - _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); + rateLimiter = common.createRateLimiter( + max, + () => { + utils.logger.log('Local variables rate-limit lifted.'); + _optionalChain([session, 'optionalAccess', _39 => _39.setPauseOnExceptions, 'call', _40 => _40(true)]); + }, + seconds => { + utils.logger.log( + `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`, + ); + _optionalChain([session, 'optionalAccess', _41 => _41.setPauseOnExceptions, 'call', _42 => _42(false)]); + }, + ); + } - _this2.retryCount++; - return run(retryAfter); - } else { - _this2.doDone(eventInfo); + shouldProcessEvent = true; + } + }, + processEvent(event) { + if (shouldProcessEvent) { + return addLocalVariablesToEvent(event); + } - yield free(_this2.options, eventInfo); + return event; + }, + // These are entirely for testing + _getCachedFramesCount() { + return cachedFrames.size; + }, + _getFirstCachedFrame() { + return cachedFrames.values()[0]; + }, + }; +}) ; - _this2._assertStatus("DONE"); +const localVariablesSyncIntegration = core.defineIntegration(_localVariablesSyncIntegration); - return _this2._reject(error); - } - } - })(); - } +/** + * Adds local variables to exception frames. + * @deprecated Use `localVariablesSyncIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const LocalVariablesSync = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + localVariablesSyncIntegration, +) - doDone(eventInfo) { - this._assertStatus("EXECUTING"); +; - this._states.next(this.options.id); +// eslint-disable-next-line deprecation/deprecation - return this.Events.trigger("done", eventInfo); - } +exports.LocalVariablesSync = LocalVariablesSync; +exports.createCallbackList = createCallbackList; +exports.localVariablesSyncIntegration = localVariablesSyncIntegration; +//# sourceMappingURL=local-variables-sync.js.map -}; -module.exports = Job; /***/ }), -/***/ 38979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 94288: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +const fs = __nccwpck_require__(79896); +const path = __nccwpck_require__(16928); +const core = __nccwpck_require__(75062); -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +let moduleCache; -var BottleneckError, LocalDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; +const INTEGRATION_NAME = 'Modules'; - this._startHeartbeat(); +/** Extract information about paths */ +function getPaths() { + try { + return require.cache ? Object.keys(require.cache ) : []; + } catch (e) { + return []; } +} - _startHeartbeat() { - var base; +/** Extract information about package.json modules */ +function collectModules() - if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { - return typeof (base = this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); + { + const mainPaths = (require.main && require.main.paths) || []; + const paths = getPaths(); + const infos - if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + = {}; + const seen - this.instance._drainAll(this.computeCapacity()); - } + = {}; - if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - var _this$storeOptions = this.storeOptions; - amount = _this$storeOptions.reservoirIncreaseAmount; - maximum = _this$storeOptions.reservoirIncreaseMaximum; - reservoir = _this$storeOptions.reservoir; - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + paths.forEach(path$1 => { + let dir = path$1; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } + /** Traverse directories upward in the search of package.json file */ + const updir = () => { + const orig = dir; + dir = path.dirname(orig); - __publish__(message) { - var _this = this; + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } - return _asyncToGenerator(function* () { - yield _this.yieldLoop(); - return _this.instance.Events.trigger("message", message.toString()); - })(); - } + const pkgfile = path.join(orig, 'package.json'); + seen[orig] = true; - __disconnect__(flush) { - var _this2 = this; + if (!fs.existsSync(pkgfile)) { + return updir(); + } - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } + try { + const info = JSON.parse(fs.readFileSync(pkgfile, 'utf8')) - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); - } +; + infos[info.name] = info.version; + } catch (_oO) { + // no-empty + } + }; - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } + updir(); + }); - __updateSettings__(options) { - var _this3 = this; + return infos; +} - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); +/** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ +function _getModules() { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; +} - _this3._startHeartbeat(); +const _modulesIntegration = (() => { + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + processEvent(event) { + event.modules = { + ...event.modules, + ..._getModules(), + }; - _this3.instance._drainAll(_this3.computeCapacity()); + return event; + }, + }; +}) ; - return true; - })(); - } +const modulesIntegration = core.defineIntegration(_modulesIntegration); - __running__() { - var _this4 = this; +/** + * Add node modules / packages to the event. + * @deprecated Use `modulesIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Modules = core.convertIntegrationFnToClass(INTEGRATION_NAME, modulesIntegration) - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } +; - __queued__() { - var _this5 = this; +// eslint-disable-next-line deprecation/deprecation - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } +exports.Modules = Modules; +exports.modulesIntegration = modulesIntegration; +//# sourceMappingURL=modules.js.map - __done__() { - var _this6 = this; - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); - } +/***/ }), - __groupCheck__(time) { - var _this7 = this; +/***/ 83790: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions2 = this.storeOptions; - maxConcurrent = _this$storeOptions2.maxConcurrent; - reservoir = _this$storeOptions2.reservoir; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(32767); +const errorhandling = __nccwpck_require__(97676); - if (maxConcurrent != null && reservoir != null) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } +const INTEGRATION_NAME = 'OnUncaughtException'; - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; - } +const _onUncaughtExceptionIntegration = ((options = {}) => { + const _options = { + exitEvenIfOtherHandlersAreRegistered: true, + ...options, + }; - __incrementReservoir__(incr) { - var _this8 = this; + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + global.process.on('uncaughtException', makeErrorHandler(client, _options)); + }, + }; +}) ; - return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; +const onUncaughtExceptionIntegration = core.defineIntegration(_onUncaughtExceptionIntegration); - _this8.instance._drainAll(_this8.computeCapacity()); +/** + * Global Exception handler. + * @deprecated Use `onUncaughtExceptionIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const OnUncaughtException = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + onUncaughtExceptionIntegration, +) - return reservoir; - })(); - } +; - __currentReservoir__() { - var _this9 = this; +// eslint-disable-next-line deprecation/deprecation - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } +/** Exported only for tests */ +function makeErrorHandler(client, options) { + const timeout = 2000; + let caughtFirstError = false; + let caughtSecondError = false; + let calledFatalError = false; + let firstError; + + const clientOptions = client.getOptions(); + + return Object.assign( + (error) => { + let onFatalError = errorhandling.logAndExitProcess; + + if (options.onFatalError) { + onFatalError = options.onFatalError; + } else if (clientOptions.onFatalError) { + onFatalError = clientOptions.onFatalError ; + } + + // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not + // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust + // exit behaviour of the SDK accordingly: + // - If other listeners are attached, do not exit. + // - If the only listener attached is ours, exit. + const userProvidedListenersCount = ( + global.process.listeners('uncaughtException') + ).reduce((acc, listener) => { + if ( + // There are 3 listeners we ignore: + listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself + (listener.tag && listener.tag === 'sentry_tracingErrorCallback') || // the handler we register for tracing + (listener )._errorHandler // the handler we register in this integration + ) { + return acc; + } else { + return acc + 1; + } + }, 0); - isBlocked(now) { - return this._unblockTime >= now; - } + const processWouldExit = userProvidedListenersCount === 0; + const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } + if (!caughtFirstError) { + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; - __check__(weight) { - var _this10 = this; + if (core.getClient() === client) { + core.captureException(error, { + originalException: error, + captureContext: { + level: 'fatal', + }, + mechanism: { + handled: false, + type: 'onuncaughtexception', + }, + }); + } - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); - } + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } + } else { + if (shouldApplyFatalHandlingLogic) { + if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + debugBuild.DEBUG_BUILD && + utils.logger.warn( + 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', + ); + errorhandling.logAndExitProcess(error); + } else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(() => { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc + } + } + } + }, + { _errorHandler: true }, + ); +} - __register__(index, weight, expiration) { - var _this11 = this; +exports.OnUncaughtException = OnUncaughtException; +exports.makeErrorHandler = makeErrorHandler; +exports.onUncaughtExceptionIntegration = onUncaughtExceptionIntegration; +//# sourceMappingURL=onuncaughtexception.js.map - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; +/***/ }), - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; - } +/***/ 28798: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - wait = Math.max(_this11._nextRequest - now, 0); - _this11._nextRequest = now + wait + _this11.storeOptions.minTime; - return { - success: true, - wait, - reservoir: _this11.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - })(); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const errorhandling = __nccwpck_require__(97676); - __submit__(queueLength, weight) { - var _this12 = this; +const INTEGRATION_NAME = 'OnUnhandledRejection'; - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); +const _onUnhandledRejectionIntegration = ((options = {}) => { + const mode = options.mode || 'warn'; - if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); - } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, { mode })); + }, + }; +}) ; - now = Date.now(); - reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); - blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); +const onUnhandledRejectionIntegration = core.defineIntegration(_onUnhandledRejectionIntegration); - if (blocked) { - _this12._unblockTime = now + _this12.computePenalty(); - _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; +/** + * Global Promise Rejection handler. + * @deprecated Use `onUnhandledRejectionIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const OnUnhandledRejection = core.convertIntegrationFnToClass( + INTEGRATION_NAME, + onUnhandledRejectionIntegration, +) - _this12.instance._dropAllQueued(); - } +; - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); - } +// eslint-disable-next-line deprecation/deprecation - __free__(index, weight) { - var _this13 = this; +/** + * Send an exception with reason + * @param reason string + * @param promise promise + * + * Exported only for tests. + */ +function makeUnhandledPromiseHandler( + client, + options, +) { + return function sendUnhandledPromise(reason, promise) { + if (core.getClient() !== client) { + return; + } - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; + core.captureException(reason, { + originalException: promise, + captureContext: { + extra: { unhandledPromiseRejection: true }, + }, + mechanism: { + handled: false, + type: 'onunhandledrejection', + }, + }); - _this13.instance._drainAll(_this13.computeCapacity()); + handleRejection(reason, options); + }; +} - return { - running: _this13._running - }; - })(); +/** + * Handler for `mode` option + + */ +function handleRejection( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + reason, + options, +) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + const rejectionWarning = + 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + + /* eslint-disable no-console */ + if (options.mode === 'warn') { + utils.consoleSandbox(() => { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); + } else if (options.mode === 'strict') { + utils.consoleSandbox(() => { + console.warn(rejectionWarning); + }); + errorhandling.logAndExitProcess(reason); } + /* eslint-enable no-console */ +} + +exports.OnUnhandledRejection = OnUnhandledRejection; +exports.makeUnhandledPromiseHandler = makeUnhandledPromiseHandler; +exports.onUnhandledRejectionIntegration = onUnhandledRejectionIntegration; +//# sourceMappingURL=onunhandledrejection.js.map -}; -module.exports = LocalDatastore; /***/ }), -/***/ 65893: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 16733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const http = __nccwpck_require__(58611); +const url = __nccwpck_require__(87016); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); -var DLList, Events, Queues; -DLList = __nccwpck_require__(38579); -Events = __nccwpck_require__(107); -Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events(this); - this._length = 0; +const INTEGRATION_NAME = 'Spotlight'; - this._lists = function () { - var j, ref, results; - results = []; +const _spotlightIntegration = ((options = {}) => { + const _options = { + sidecarUrl: options.sidecarUrl || 'http://localhost:8969/stream', + }; - for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList(() => { - return this.incr(); - }, () => { - return this.decr(); - })); - } + return { + name: INTEGRATION_NAME, + // TODO v8: Remove this + setupOnce() {}, // eslint-disable-line @typescript-eslint/no-empty-function + setup(client) { + if (typeof process === 'object' && process.env && process.env.NODE_ENV !== 'development') { + utils.logger.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?"); + } + connectToSpotlight(client, _options); + }, + }; +}) ; - return results; - }.call(this); - } +const spotlightIntegration = core.defineIntegration(_spotlightIntegration); - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +/** + * Use this integration to send errors and transactions to Spotlight. + * + * Learn more about spotlight at https://spotlightjs.com + * + * Important: This integration only works with Node 18 or newer. + * + * @deprecated Use `spotlightIntegration()` instead. + */ +// eslint-disable-next-line deprecation/deprecation +const Spotlight = core.convertIntegrationFnToClass(INTEGRATION_NAME, spotlightIntegration) - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } +; + +// eslint-disable-next-line deprecation/deprecation + +function connectToSpotlight(client, options) { + const spotlightUrl = parseSidecarUrl(options.sidecarUrl); + if (!spotlightUrl) { + return; } - push(job) { - return this._lists[job.options.priority].push(job); + let failedRequests = 0; + + if (typeof client.on !== 'function') { + utils.logger.warn('[Spotlight] Cannot connect to spotlight due to missing method on SDK client (`client.on`)'); + return; } - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; + client.on('beforeEnvelope', (envelope) => { + if (failedRequests > 3) { + utils.logger.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests'); + return; } - } - shiftAll(fn) { - return this._lists.forEach(function (list) { - return list.forEachShift(fn); - }); - } + const serializedEnvelope = utils.serializeEnvelope(envelope); - getFirst(arr = this._lists) { - var j, len, list; + const request = getNativeHttpRequest(); + const req = request( + { + method: 'POST', + path: spotlightUrl.pathname, + hostname: spotlightUrl.hostname, + port: spotlightUrl.port, + headers: { + 'Content-Type': 'application/x-sentry-envelope', + }, + }, + res => { + res.on('data', () => { + // Drain socket + }); - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; + res.on('end', () => { + // Drain socket + }); + res.setEncoding('utf8'); + }, + ); - if (list.length > 0) { - return list; - } - } + req.on('error', () => { + failedRequests++; + utils.logger.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar'); + }); + req.write(serializedEnvelope); + req.end(); + }); +} - return []; +function parseSidecarUrl(url$1) { + try { + return new url.URL(`${url$1}`); + } catch (e) { + utils.logger.warn(`[Spotlight] Invalid sidecar URL: ${url$1}`); + return undefined; } +} - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); +/** + * We want to get an unpatched http request implementation to avoid capturing our own calls. + */ +function getNativeHttpRequest() { + const { request } = http; + if (isWrapped(request)) { + return request.__sentry_original__; } -}; -module.exports = Queues; + return request; +} -/***/ }), +function isWrapped(impl) { + return '__sentry_original__' in impl; +} -/***/ 29992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.Spotlight = Spotlight; +exports.getNativeHttpRequest = getNativeHttpRequest; +exports.spotlightIntegration = spotlightIntegration; +//# sourceMappingURL=spotlight.js.map -"use strict"; +/***/ }), -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/***/ 32094: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +var { + _optionalChain +} = __nccwpck_require__(25304); -var Events, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); +Object.defineProperty(exports, "__esModule", ({ value: true })); -RedisConnection = function () { - class RedisConnection { - constructor(options = {}) { - parser.load(options, this.defaults, this); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const nodeVersion = __nccwpck_require__(29421); - if (this.Redis == null) { - this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option. - } +exports.ChannelName = void 0;(function (ChannelName) { + // https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md#undicirequestcreate + const RequestCreate = 'undici:request:create'; ChannelName["RequestCreate"] = RequestCreate; + const RequestEnd = 'undici:request:headers'; ChannelName["RequestEnd"] = RequestEnd; + const RequestError = 'undici:request:error'; ChannelName["RequestError"] = RequestError; +})(exports.ChannelName || (exports.ChannelName = {})); - if (this.Events == null) { - this.Events = new Events(this); - } +// Please note that you cannot use `console.log` to debug the callbacks registered to the `diagnostics_channel` API. +// To debug, you can use `writeFileSync` to write to a file: +// https://nodejs.org/api/async_hooks.html#printing-in-asynchook-callbacks +// +// import { writeFileSync } from 'fs'; +// import { format } from 'util'; +// +// function debug(...args: any): void { +// // Use a function like this one when debugging inside an AsyncHook callback +// // @ts-expect-error any +// writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' }); +// } - this.terminated = false; +const _nativeNodeFetchintegration = ((options) => { + // eslint-disable-next-line deprecation/deprecation + return new Undici(options) ; +}) ; - if (this.client == null) { - this.client = this.Redis.createClient(this.clientOptions); - } +const nativeNodeFetchintegration = core.defineIntegration(_nativeNodeFetchintegration); - this.subscriber = this.client.duplicate(); - this.limiters = {}; - this.shas = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - return this._loadScripts(); - }).then(() => { - return { - client: this.client, - subscriber: this.subscriber - }; - }); - } +/** + * Instruments outgoing HTTP requests made with the `undici` package via + * Node's `diagnostics_channel` API. + * + * Supports Undici 4.7.0 or higher. + * + * Requires Node 16.17.0 or higher. + * + * @deprecated Use `nativeNodeFetchintegration()` instead. + */ +class Undici { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Undici';} - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); + /** + * @inheritDoc + */ + // eslint-disable-next-line deprecation/deprecation + __init() {this.name = Undici.id;} - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } + __init2() {this._createSpanUrlMap = new utils.LRUMap(100);} + __init3() {this._headersUrlMap = new utils.LRUMap(100);} - if (client.ready) { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } + constructor(_options = {}) {Undici.prototype.__init.call(this);Undici.prototype.__init2.call(this);Undici.prototype.__init3.call(this);Undici.prototype.__init4.call(this);Undici.prototype.__init5.call(this);Undici.prototype.__init6.call(this); + this._options = { + breadcrumbs: _options.breadcrumbs === undefined ? true : _options.breadcrumbs, + tracing: _options.tracing, + shouldCreateSpanForRequest: _options.shouldCreateSpanForRequest, + }; + } - _loadScript(name) { - return new this.Promise((resolve, reject) => { - var payload; - payload = Scripts.payload(name); - return this.client.multi([["script", "load", payload]]).exec((err, replies) => { - if (err != null) { - return reject(err); - } + /** + * @inheritDoc + */ + setupOnce(_addGlobalEventProcessor) { + // Requires Node 16+ to use the diagnostics_channel API. + if (nodeVersion.NODE_VERSION.major < 16) { + return; + } - this.shas[name] = replies[0]; - return resolve(replies[0]); - }); - }); + let ds; + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + ds = __nccwpck_require__(31637) ; + } catch (e) { + // no-op } - _loadScripts() { - return this.Promise.all(Scripts.names.map(k => { - return this._loadScript(k); - })); + if (!ds || !ds.subscribe) { + return; } - __runCommand__(cmd) { - var _this = this; + // https://github.com/nodejs/undici/blob/e6fc80f809d1217814c044f52ed40ef13f21e43c/docs/api/DiagnosticsChannel.md + ds.subscribe(exports.ChannelName.RequestCreate, this._onRequestCreate); + ds.subscribe(exports.ChannelName.RequestEnd, this._onRequestEnd); + ds.subscribe(exports.ChannelName.RequestError, this._onRequestError); + } - return _asyncToGenerator(function* () { - yield _this.ready; - return new _this.Promise((resolve, reject) => { - return _this.client.multi([cmd]).exec_atomic(function (err, replies) { - if (err != null) { - return reject(err); - } else { - return resolve(replies[0]); - } - }); - }); - })(); + /** Helper that wraps shouldCreateSpanForRequest option */ + _shouldCreateSpan(url) { + if (this._options.tracing === false || (this._options.tracing === undefined && !core.hasTracingEnabled())) { + return false; } - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - var handler; - - handler = chan => { - if (chan === channel) { - this.subscriber.removeListener("subscribe", handler); - this.limiters[channel] = instance; - return resolve(); - } - }; + if (this._options.shouldCreateSpanForRequest === undefined) { + return true; + } - this.subscriber.on("subscribe", handler); - return this.subscriber.subscribe(channel); - }); - })); + const cachedDecision = this._createSpanUrlMap.get(url); + if (cachedDecision !== undefined) { + return cachedDecision; } - __removeLimiter__(instance) { - var _this2 = this; + const decision = this._options.shouldCreateSpanForRequest(url); + this._createSpanUrlMap.set(url, decision); + return decision; + } - return this.Promise.all([instance.channel(), instance.channel_client()].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield new _this2.Promise((resolve, reject) => { - return _this2.subscriber.unsubscribe(channel, function (err, chan) { - if (err != null) { - return reject(err); - } + __init4() {this._onRequestCreate = (message) => { + // eslint-disable-next-line deprecation/deprecation + if (!_optionalChain([core.getClient, 'call', _10 => _10(), 'optionalAccess', _11 => _11.getIntegration, 'call', _12 => _12(Undici)])) { + return; + } - if (chan === channel) { - return resolve(); - } - }); - }); - } + const { request } = message ; - return delete _this2.limiters[channel]; - }); + const stringUrl = request.origin ? request.origin.toString() + request.path : request.path; - return function (_x) { - return _ref.apply(this, arguments); - }; - }())); + const client = core.getClient(); + if (!client) { + return; } - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [this.shas[name], keys.length].concat(keys, args, cb); + if (core.isSentryRequestUrl(stringUrl, client) || request.__sentry_span__ !== undefined) { + return; } - __scriptFn__(name) { - return this.client.evalsha.bind(this.client); - } + const clientOptions = client.getOptions(); + const scope = core.getCurrentScope(); + const isolationScope = core.getIsolationScope(); + const parentSpan = core.getActiveSpan(); - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); + const span = this._shouldCreateSpan(stringUrl) ? createRequestSpan(parentSpan, request, stringUrl) : undefined; + if (span) { + request.__sentry_span__ = span; + } - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); + const shouldAttachTraceData = (url) => { + if (clientOptions.tracePropagationTargets === undefined) { + return true; } - this.limiters = {}; - this.terminated = true; - this.client.end(flush); - this.subscriber.end(flush); - return this.Promise.resolve(); - } + const cachedDecision = this._headersUrlMap.get(url); + if (cachedDecision !== undefined) { + return cachedDecision; + } - } + const decision = utils.stringMatchesSomePattern(url, clientOptions.tracePropagationTargets); + this._headersUrlMap.set(url, decision); + return decision; + }; - ; - RedisConnection.prototype.datastore = "redis"; - RedisConnection.prototype.defaults = { - Redis: null, - clientOptions: {}, - client: null, - Promise: Promise, - Events: null - }; - return RedisConnection; -}.call(void 0); + if (shouldAttachTraceData(stringUrl)) { + const { traceId, spanId, sampled, dsc } = { + ...isolationScope.getPropagationContext(), + ...scope.getPropagationContext(), + }; -module.exports = RedisConnection; + const sentryTraceHeader = span ? core.spanToTraceHeader(span) : utils.generateSentryTraceHeader(traceId, spanId, sampled); -/***/ }), + const sentryBaggageHeader = utils.dynamicSamplingContextToSentryBaggageHeader( + dsc || + (span + ? core.getDynamicSamplingContextFromSpan(span) + : core.getDynamicSamplingContextFromClient(traceId, client, scope)), + ); -/***/ 4946: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + setHeadersOnRequest(request, sentryTraceHeader, sentryBaggageHeader); + } + };} -"use strict"; + __init5() {this._onRequestEnd = (message) => { + // eslint-disable-next-line deprecation/deprecation + if (!_optionalChain([core.getClient, 'call', _13 => _13(), 'optionalAccess', _14 => _14.getIntegration, 'call', _15 => _15(Undici)])) { + return; + } + const { request, response } = message ; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } + const stringUrl = request.origin ? request.origin.toString() + request.path : request.path; -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + if (core.isSentryRequestUrl(stringUrl, core.getClient())) { + return; + } -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + const span = request.__sentry_span__; + if (span) { + core.setHttpStatus(span, response.statusCode); + span.end(); + } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + if (this._options.breadcrumbs) { + core.addBreadcrumb( + { + category: 'http', + data: { + method: request.method, + status_code: response.statusCode, + url: stringUrl, + }, + type: 'http', + }, + { + event: 'response', + request, + response, + }, + ); + } + };} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + __init6() {this._onRequestError = (message) => { + // eslint-disable-next-line deprecation/deprecation + if (!_optionalChain([core.getClient, 'call', _16 => _16(), 'optionalAccess', _17 => _17.getIntegration, 'call', _18 => _18(Undici)])) { + return; + } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + const { request } = message ; -var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -RedisDatastore = class RedisDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.originalId = this.instance.id; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this.clients = {}; - this.capacityPriorityCounters = {}; - this.sharedConnection = this.connection != null; + const stringUrl = request.origin ? request.origin.toString() + request.path : request.path; - if (this.connection == null) { - this.connection = this.instance.datastore === "redis" ? new RedisConnection({ - Redis: this.Redis, - clientOptions: this.clientOptions, - Promise: this.Promise, - Events: this.instance.Events - }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ - Redis: this.Redis, - clientOptions: this.clientOptions, - clusterNodes: this.clusterNodes, - Promise: this.Promise, - Events: this.instance.Events - }) : void 0; + if (core.isSentryRequestUrl(stringUrl, core.getClient())) { + return; } - this.instance.connection = this.connection; - this.instance.datastore = this.connection.datastore; - this.ready = this.connection.ready.then(clients => { - this.clients = clients; - return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); - }).then(() => { - return this.connection.__addLimiter__(this.instance); - }).then(() => { - return this.runScript("register_client", [this.instance.queued()]); - }).then(() => { - var base; + const span = request.__sentry_span__; + if (span) { + span.setStatus('internal_error'); + span.end(); + } - if (typeof (base = this.heartbeat = setInterval(() => { - return this.runScript("heartbeat", []).catch(e => { - return this.instance.Events.trigger("error", e); - }); - }, this.heartbeatInterval)).unref === "function") { - base.unref(); - } + if (this._options.breadcrumbs) { + core.addBreadcrumb( + { + category: 'http', + data: { + method: request.method, + url: stringUrl, + }, + level: 'error', + type: 'http', + }, + { + event: 'error', + request, + }, + ); + } + };} +}Undici.__initStatic(); - return this.clients; - }); +function setHeadersOnRequest( + request, + sentryTrace, + sentryBaggageHeader, +) { + let hasSentryHeaders; + if (Array.isArray(request.headers)) { + hasSentryHeaders = request.headers.some(headerLine => headerLine === 'sentry-trace'); + } else { + const headerLines = request.headers.split('\r\n'); + hasSentryHeaders = headerLines.some(headerLine => headerLine.startsWith('sentry-trace:')); } - __publish__(message) { - var _this = this; + if (hasSentryHeaders) { + return; + } - return _asyncToGenerator(function* () { - var client; + request.addHeader('sentry-trace', sentryTrace); + if (sentryBaggageHeader) { + request.addHeader('baggage', sentryBaggageHeader); + } +} - var _ref = yield _this.ready; +function createRequestSpan( + activeSpan, + request, + stringUrl, +) { + const url = utils.parseUrl(stringUrl); - client = _ref.client; - return client.publish(_this.instance.channel(), `message:${message.toString()}`); - })(); + const method = request.method || 'GET'; + const data = { + 'http.method': method, + }; + if (url.search) { + data['http.query'] = url.search; + } + if (url.hash) { + data['http.fragment'] = url.hash; } + // eslint-disable-next-line deprecation/deprecation + return _optionalChain([activeSpan, 'optionalAccess', _19 => _19.startChild, 'call', _20 => _20({ + op: 'http.client', + origin: 'auto.http.node.undici', + description: `${method} ${utils.getSanitizedUrlString(url)}`, + data, + })]); +} - onMessage(channel, message) { - var _this2 = this; +exports.Undici = Undici; +exports.nativeNodeFetchintegration = nativeNodeFetchintegration; +//# sourceMappingURL=index.js.map - return _asyncToGenerator(function* () { - var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; - try { - pos = message.indexOf(":"); - var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; - type = _ref2[0]; - data = _ref2[1]; +/***/ }), - if (type === "capacity") { - return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); - } else if (type === "capacity-priority") { - var _data$split = data.split(":"); +/***/ 97676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var _data$split2 = _slicedToArray(_data$split, 3); +Object.defineProperty(exports, "__esModule", ({ value: true })); - rawCapacity = _data$split2[0]; - priorityClient = _data$split2[1]; - counter = _data$split2[2]; - capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const debugBuild = __nccwpck_require__(32767); - if (priorityClient === _this2.clientId) { - drained = yield _this2.instance._drainAll(capacity); - newCapacity = capacity != null ? capacity - (drained || 0) : ""; - return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); - } else if (priorityClient === "") { - clearTimeout(_this2.capacityPriorityCounters[counter]); - delete _this2.capacityPriorityCounters[counter]; - return _this2.instance._drainAll(capacity); - } else { - return _this2.capacityPriorityCounters[counter] = setTimeout( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e; +const DEFAULT_SHUTDOWN_TIMEOUT = 2000; - try { - delete _this2.capacityPriorityCounters[counter]; - yield _this2.runScript("blacklist_client", [priorityClient]); - return yield _this2.instance._drainAll(capacity); - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - }), 1000); - } - } else if (type === "message") { - return _this2.instance.Events.trigger("message", data); - } else if (type === "blocked") { - return yield _this2.instance._dropAllQueued(); - } - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - })(); - } +/** + * @hidden + */ +function logAndExitProcess(error) { + utils.consoleSandbox(() => { + // eslint-disable-next-line no-console + console.error(error); + }); - __disconnect__(flush) { - clearInterval(this.heartbeat); + const client = core.getClient(); - if (this.sharedConnection) { - return this.connection.__removeLimiter__(this.instance); - } else { - return this.connection.disconnect(flush); - } + if (client === undefined) { + debugBuild.DEBUG_BUILD && utils.logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); } - runScript(name, args) { - var _this3 = this; - - return _asyncToGenerator(function* () { - if (!(name === "init" || name === "register_client")) { - yield _this3.ready; + const options = client.getOptions(); + const timeout = + (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + client.close(timeout).then( + (result) => { + if (!result) { + debugBuild.DEBUG_BUILD && utils.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); } + global.process.exit(1); + }, + error => { + debugBuild.DEBUG_BUILD && utils.logger.error(error); + }, + ); +} - return new _this3.Promise((resolve, reject) => { - var all_args, arr; - all_args = [Date.now(), _this3.clientId].concat(args); +exports.logAndExitProcess = logAndExitProcess; +//# sourceMappingURL=errorhandling.js.map - _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); - arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { - if (err != null) { - return reject(err); - } +/***/ }), - return resolve(replies); - }); - return _this3.connection.__scriptFn__(name)(...arr); - }).catch(e => { - if (e.message === "SETTINGS_KEY_NOT_FOUND") { - if (name === "heartbeat") { - return _this3.Promise.resolve(); - } else { - return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { - return _this3.runScript(name, args); - }); - } - } else if (e.message === "UNKNOWN_CLIENT") { - return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { - return _this3.runScript(name, args); - }); - } else { - return _this3.Promise.reject(e); - } - }); - })(); - } +/***/ 715: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - prepareArray(arr) { - var i, len, results, x; - results = []; +var { + _optionalChain +} = __nccwpck_require__(25304); - for (i = 0, len = arr.length; i < len; i++) { - x = arr[i]; - results.push(x != null ? x.toString() : ""); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return results; - } +const url = __nccwpck_require__(87016); +const nodeVersion = __nccwpck_require__(29421); - prepareObject(obj) { - var arr, k, v; - arr = []; +/** + * Assembles a URL that's passed to the users to filter on. + * It can include raw (potentially PII containing) data, which we'll allow users to access to filter + * but won't include in spans or breadcrumbs. + * + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL + */ +// TODO (v8): This function should include auth, query and fragment (it's breaking, so we need to wait for v8) +function extractRawUrl(requestOptions) { + const { protocol, hostname, port } = parseRequestOptions(requestOptions); + const path = requestOptions.path ? requestOptions.path : '/'; + return `${protocol}//${hostname}${port}${path}`; +} - for (k in obj) { - v = obj[k]; - arr.push(k, v != null ? v.toString() : ""); - } +/** + * Assemble a URL to be used for breadcrumbs and spans. + * + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL + */ +function extractUrl(requestOptions) { + const { protocol, hostname, port } = parseRequestOptions(requestOptions); - return arr; - } + const path = requestOptions.pathname || '/'; - prepareInitSettings(clear) { - var args; - args = this.prepareObject(Object.assign({}, this.storeOptions, { - id: this.originalId, - version: this.instance.version, - groupTimeout: this.timeout, - clientTimeout: this.clientTimeout - })); - args.unshift(clear ? 1 : 0, this.instance.version); - return args; - } + // always filter authority, see https://develop.sentry.dev/sdk/data-handling/#structuring-data + const authority = requestOptions.auth ? redactAuthority(requestOptions.auth) : ''; - convertBool(b) { - return !!b; - } + return `${protocol}//${authority}${hostname}${port}${path}`; +} - __updateSettings__(options) { - var _this4 = this; +function redactAuthority(auth) { + const [user, password] = auth.split(':'); + return `${user ? '[Filtered]' : ''}:${password ? '[Filtered]' : ''}@`; +} - return _asyncToGenerator(function* () { - yield _this4.runScript("update_settings", _this4.prepareObject(options)); - return parser.overwrite(options, options, _this4.storeOptions); - })(); +/** + * Handle various edge cases in the span description (for spans representing http(s) requests). + * + * @param description current `description` property of the span representing the request + * @param requestOptions Configuration data for the request + * @param Request Request object + * + * @returns The cleaned description + */ +function cleanSpanDescription( + description, + requestOptions, + request, +) { + // nothing to clean + if (!description) { + return description; } - __running__() { - return this.runScript("running", []); - } + // eslint-disable-next-line prefer-const + let [method, requestUrl] = description.split(' '); - __queued__() { - return this.runScript("queued", []); + // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, + // we're likely dealing with an internal route and this doesn't apply) + if (requestOptions.host && !requestOptions.protocol) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = _optionalChain([(request ), 'optionalAccess', _ => _.agent, 'optionalAccess', _2 => _2.protocol]); // worst comes to worst, this is undefined and nothing changes + // This URL contains the filtered authority ([filtered]:[filtered]@example.com) but no fragment or query params + requestUrl = extractUrl(requestOptions); } - __done__() { - return this.runScript("done", []); + // internal routes can end up starting with a triple slash rather than a single one + if (_optionalChain([requestUrl, 'optionalAccess', _3 => _3.startsWith, 'call', _4 => _4('///')])) { + requestUrl = requestUrl.slice(2); } - __groupCheck__() { - var _this5 = this; + return `${method} ${requestUrl}`; +} - return _asyncToGenerator(function* () { - return _this5.convertBool((yield _this5.runScript("group_check", []))); - })(); - } +// the node types are missing a few properties which node's `urlToOptions` function spits out - __incrementReservoir__(incr) { - return this.runScript("increment_reservoir", [incr]); +/** + * Convert a URL object into a RequestOptions object. + * + * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the + * RequestOptions type above. + * + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + */ +function urlToOptions(url) { + const options = { + protocol: url.protocol, + hostname: + typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: `${url.pathname || ''}${url.search || ''}`, + href: url.href, + }; + if (url.port !== '') { + options.port = Number(url.port); } - - __currentReservoir__() { - return this.runScript("current_reservoir", []); + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; } + return options; +} - __check__(weight) { - var _this6 = this; +/** + * Normalize inputs to `http(s).request()` and `http(s).get()`. + * + * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: + * [ RequestOptions | string | URL ], + * [ RequestOptions | string | URL, RequestCallback ], + * [ string | URL, RequestOptions ], and + * [ string | URL, RequestOptions, RequestCallback ]. + * + * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is + * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact + * with the args in a standard way. + * + * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + */ +function normalizeRequestArgs( + httpModule, + requestArgs, +) { + let callback, requestOptions; - return _asyncToGenerator(function* () { - return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); - })(); + // pop off the callback, if there is one + if (typeof requestArgs[requestArgs.length - 1] === 'function') { + callback = requestArgs.pop() ; } - __register__(index, weight, expiration) { - var _this7 = this; + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url.URL(requestArgs[0])); + } else if (requestArgs[0] instanceof url.URL) { + requestOptions = urlToOptions(requestArgs[0]); + } else { + requestOptions = requestArgs[0]; - return _asyncToGenerator(function* () { - var reservoir, success, wait; + try { + const parsed = new url.URL( + requestOptions.path || '', + `${requestOptions.protocol || 'http:'}//${requestOptions.hostname}`, + ); + requestOptions = { + pathname: parsed.pathname, + search: parsed.search, + hash: parsed.hash, + ...requestOptions, + }; + } catch (e) { + // ignore + } + } - var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); + // if the options were given separately from the URL, fold them in + if (requestArgs.length === 2) { + requestOptions = { ...requestOptions, ...requestArgs[1] }; + } - var _ref5 = _slicedToArray(_ref4, 3); + // Figure out the protocol if it's currently missing + if (requestOptions.protocol === undefined) { + // Worst case we end up populating protocol with undefined, which it already is + /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - success = _ref5[0]; - wait = _ref5[1]; - reservoir = _ref5[2]; - return { - success: _this7.convertBool(success), - wait, - reservoir - }; - })(); + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, + // as it will always return `http`, even when using `https` module. + // + // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. + if (nodeVersion.NODE_VERSION.major > 8) { + requestOptions.protocol = + _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _5 => _5.globalAgent]) ), 'optionalAccess', _6 => _6.protocol]) || + _optionalChain([(requestOptions.agent ), 'optionalAccess', _7 => _7.protocol]) || + _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _8 => _8.protocol]); + } else { + requestOptions.protocol = + _optionalChain([(requestOptions.agent ), 'optionalAccess', _9 => _9.protocol]) || + _optionalChain([(requestOptions._defaultAgent ), 'optionalAccess', _10 => _10.protocol]) || + _optionalChain([(_optionalChain([httpModule, 'optionalAccess', _11 => _11.globalAgent]) ), 'optionalAccess', _12 => _12.protocol]); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ } - __submit__(queueLength, weight) { - var _this8 = this; + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } else { + return [requestOptions]; + } +} - return _asyncToGenerator(function* () { - var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; +function parseRequestOptions(requestOptions) - try { - var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); + { + const protocol = requestOptions.protocol || ''; + const hostname = requestOptions.hostname || requestOptions.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + // Also don't add port if the hostname already includes a port + const port = + !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\d+)$/.test(hostname) + ? '' + : `:${requestOptions.port}`; - var _ref7 = _slicedToArray(_ref6, 3); + return { protocol, hostname, port }; +} - reachedHWM = _ref7[0]; - blocked = _ref7[1]; - strategy = _ref7[2]; - return { - reachedHWM: _this8.convertBool(reachedHWM), - blocked: _this8.convertBool(blocked), - strategy - }; - } catch (error) { - e = error; +exports.cleanSpanDescription = cleanSpanDescription; +exports.extractRawUrl = extractRawUrl; +exports.extractUrl = extractUrl; +exports.normalizeRequestArgs = normalizeRequestArgs; +exports.urlToOptions = urlToOptions; +//# sourceMappingURL=http.js.map - if (e.message.indexOf("OVERWEIGHT") === 0) { - var _e$message$split = e.message.split(":"); - var _e$message$split2 = _slicedToArray(_e$message$split, 3); +/***/ }), - overweight = _e$message$split2[0]; - weight = _e$message$split2[1]; - maxConcurrent = _e$message$split2[2]; - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); - } else { - throw e; - } +/***/ 76137: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const path = __nccwpck_require__(16928); +const utils = __nccwpck_require__(25304); + +/** normalizes Windows paths */ +function normalizeWindowsPath(path) { + return path + .replace(/^[A-Z]:/, '') // remove Windows-style prefix + .replace(/\\/g, '/'); // replace all `\` instances with `/` +} + +/** Creates a function that gets the module name from a filename */ +function createGetModuleFromFilename( + basePath = process.argv[1] ? utils.dirname(process.argv[1]) : process.cwd(), + isWindows = path.sep === '\\', +) { + const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath; + + return (filename) => { + if (!filename) { + return; + } + + const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename; + + // eslint-disable-next-line prefer-const + let { dir, base: file, ext } = path.posix.parse(normalizedFilename); + + if (ext === '.js' || ext === '.mjs' || ext === '.cjs') { + file = file.slice(0, ext.length * -1); + } + + if (!dir) { + // No dirname whatsoever + dir = '.'; + } + + const n = dir.lastIndexOf('/node_modules'); + if (n > -1) { + return `${dir.slice(n + 14).replace(/\//g, '.')}:${file}`; + } + + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + if (dir.startsWith(normalizedBase)) { + let moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, '.'); + + if (moduleName) { + moduleName += ':'; } - })(); - } + moduleName += file; - __free__(index, weight) { - var _this9 = this; + return moduleName; + } - return _asyncToGenerator(function* () { - var running; - running = yield _this9.runScript("free", _this9.prepareArray([index])); - return { - running - }; - })(); - } + return file; + }; +} + +exports.createGetModuleFromFilename = createGetModuleFromFilename; +//# sourceMappingURL=module.js.map -}; -module.exports = RedisDatastore; /***/ }), -/***/ 4169: +/***/ 29421: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils = __nccwpck_require__(25304); -var headers, lua, templates; -lua = __nccwpck_require__(31936); -headers = { - refs: lua["refs.lua"], - validate_keys: lua["validate_keys.lua"], - validate_client: lua["validate_client.lua"], - refresh_expiration: lua["refresh_expiration.lua"], - process_tick: lua["process_tick.lua"], - conditions_check: lua["conditions_check.lua"], - get_time: lua["get_time.lua"] -}; +const NODE_VERSION = utils.parseSemver(process.versions.node) ; -exports.allKeys = function (id) { - return [ - /* - HASH - */ - `b_${id}_settings`, - /* - HASH - job index -> weight - */ - `b_${id}_job_weights`, - /* - ZSET - job index -> expiration - */ - `b_${id}_job_expirations`, - /* - HASH - job index -> client - */ - `b_${id}_job_clients`, - /* - ZSET - client -> sum running - */ - `b_${id}_client_running`, - /* - HASH - client -> num queued - */ - `b_${id}_client_num_queued`, - /* - ZSET - client -> last job registered - */ - `b_${id}_client_last_registered`, - /* - ZSET - client -> last seen - */ - `b_${id}_client_last_seen`]; -}; +exports.NODE_VERSION = NODE_VERSION; +//# sourceMappingURL=nodeVersion.js.map -templates = { - init: { - keys: exports.allKeys, - headers: ["process_tick"], - refresh_expiration: true, - code: lua["init.lua"] - }, - group_check: { - keys: exports.allKeys, - headers: [], - refresh_expiration: false, - code: lua["group_check.lua"] - }, - register_client: { - keys: exports.allKeys, - headers: ["validate_keys"], - refresh_expiration: false, - code: lua["register_client.lua"] - }, - blacklist_client: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["blacklist_client.lua"] - }, - heartbeat: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["heartbeat.lua"] - }, - update_settings: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["update_settings.lua"] - }, - running: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["running.lua"] - }, - queued: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["queued.lua"] - }, - done: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["done.lua"] - }, - check: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: false, - code: lua["check.lua"] - }, - submit: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["submit.lua"] - }, - register: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["register.lua"] - }, - free: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["free.lua"] - }, - current_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["current_reservoir.lua"] - }, - increment_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["increment_reservoir.lua"] - } -}; -exports.names = Object.keys(templates); -exports.keys = function (name, id) { - return templates[name].keys(id); -}; +/***/ }), -exports.payload = function (name) { - var template; - template = templates[name]; - return Array.prototype.concat(headers.refs, template.headers.map(function (h) { - return headers[h]; - }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); -}; +/***/ 28289: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +var { + _nullishCoalesce +} = __nccwpck_require__(25304); -/***/ 2527: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); -"use strict"; +const http = __nccwpck_require__(58611); +__nccwpck_require__(65692); + +/** +* This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7 +* With the following licence: +* +* (The MIT License) +* +* Copyright (c) 2013 Nathan Rajlich * +* +* 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 INTERNAL = Symbol('AgentBaseInternalState'); -var BottleneckError, States; -BottleneckError = __nccwpck_require__(93529); -States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function () { - return 0; - }); +class Agent extends http.Agent { + + // Set by `http.Agent` - missing from `@types/node` + + constructor(opts) { + super(opts); + this[INTERNAL] = {}; } - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access + if (typeof (options ).secureEndpoint === 'boolean') { + return options.secureEndpoint; + } - if (current != null && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } } + + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); } - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then(socket => { + if (socket instanceof http.Agent) { + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + return socket.addRequest(req, connectOpts); + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, cb); } - remove(id) { - var current; - current = this._jobs[id]; + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; + get defaultPort() { + return _nullishCoalesce(this[INTERNAL].defaultPort, () => ( (this.protocol === 'https:' ? 443 : 80))); + } + + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; } + } - return current != null; + get protocol() { + return _nullishCoalesce(this[INTERNAL].protocol, () => ( (this.isSecureEndpoint() ? 'https:' : 'http:'))); } - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } } +} - statusJobs(status) { - var k, pos, ref, results, v; +exports.Agent = Agent; +//# sourceMappingURL=base.js.map - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } +/***/ }), - ref = this._jobs; - results = []; +/***/ 13058: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (k in ref) { - v = ref[k]; +var { + _nullishCoalesce, + _optionalChain +} = __nccwpck_require__(25304); - if (v === pos) { - results.push(k); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return results; - } else { - return Object.keys(this._jobs); - } - } +const net = __nccwpck_require__(69278); +const tls = __nccwpck_require__(64756); +const url = __nccwpck_require__(87016); +const utils = __nccwpck_require__(25304); +const base = __nccwpck_require__(28289); +const parseProxyResponse = __nccwpck_require__(26954); - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); +function debug(...args) { + utils.logger.log('[https-proxy-agent]', ...args); +} + +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends base.Agent { + static __initStatic() {this.protocols = ['http', 'https']; } + + constructor(proxy, opts) { + super(opts); + this.options = {}; + this.proxy = typeof proxy === 'string' ? new url.URL(proxy) : proxy; + this.proxyHeaders = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _2 => _2.headers]), () => ( {})); + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; } -}; -module.exports = States; + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; -/***/ }), + if (!opts.host) { + throw new TypeError('No "host" provided'); + } -/***/ 56029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + const servername = this.connectOpts.servername || this.connectOpts.host; + socket = tls.connect({ + ...this.connectOpts, + servername: servername && net.isIP(servername) ? undefined : servername, + }); + } else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } -"use strict"; + const headers = + typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + headers.Host = `${host}:${opts.port}`; -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } -var DLList, Sync; -DLList = __nccwpck_require__(38579); -Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList(); - } + const proxyResponsePromise = parseProxyResponse.parseProxyResponse(socket); - isEmpty() { - return this._queue.length === 0; - } + socket.write(`${payload}\r\n`); - _tryToRun() { - var _this = this; + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not EventEmitter in Node types + this.emit('proxyConnect', connect, req); - return _asyncToGenerator(function* () { - var args, cb, error, reject, resolve, returned, task; + if (connect.statusCode === 200) { + req.once('socket', resume); - if (_this._running < 1 && _this._queue.length > 0) { - _this._running++; + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls.connect({ + ...omit(opts, 'host', 'path', 'port'), + socket, + servername: net.isIP(servername) ? undefined : servername, + }); + } - var _this$_queue$shift = _this._queue.shift(); + return socket; + } - task = _this$_queue$shift.task; - args = _this$_queue$shift.args; - resolve = _this$_queue$shift.resolve; - reject = _this$_queue$shift.reject; - cb = yield _asyncToGenerator(function* () { - try { - returned = yield task(...args); - return function () { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function () { - return reject(error); - }; - } - })(); - _this._running--; + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. - _this._tryToRun(); + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); - return cb(); - } - })(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + + return fakeSocket; } +}HttpsProxyAgent.__initStatic(); - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function (_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); +function resume(socket) { + socket.resume(); +} - this._queue.push({ - task, - args, - resolve, - reject - }); +function omit( + obj, + ...keys +) - this._tryToRun(); + { + const ret = {} - return promise; +; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } + return ret; +} -}; -module.exports = Sync; +exports.HttpsProxyAgent = HttpsProxyAgent; +//# sourceMappingURL=index.js.map -/***/ }), -/***/ 27356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ }), -"use strict"; +/***/ 26954: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); -module.exports = __nccwpck_require__(83911); +const utils = __nccwpck_require__(25304); -/***/ }), +function debug(...args) { + utils.logger.log('[https-proxy-agent:parse-proxy-response]', ...args); +} -/***/ 67823: -/***/ ((__unused_webpack_module, exports) => { +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; -"use strict"; + function read() { + const b = socket.read(); + if (b) ondata(b); + else socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } -exports.load = function (received, defaults, onto = {}) { - var k, ref, v; + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } - return onto; -}; + function ondata(b) { + buffers.push(b); + buffersLength += b.length; -exports.overwrite = function (received, defaults, onto = {}) { - var k, v; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); - for (k in received) { - v = received[k]; + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } - if (defaults[k] !== void 0) { - onto[k] = v; + const headerParts = buffered.slice(0, endOfHeaders).toString('ascii').split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); } - } - return onto; -}; + socket.on('error', onerror); + socket.on('end', onend); + + read(); + }); +} + +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + /***/ }), -/***/ 11174: -/***/ (function(module) { +/***/ 34161: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +const utils = __nccwpck_require__(25304); - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } +/** + * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. + */ - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; +/** + * Normalizes data from the request object, accounting for framework differences. + * + * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. + * + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. + * @returns An object containing normalized request data + */ +function extractRequestData(req, keys) { + return utils.extractRequestData(req, { include: keys }); +} - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; +/** + * Options deciding what parts of the request to use when enhancing an event + * + * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use + * `AddRequestDataToEventOptions` in `@sentry/utils` instead. + */ - var parser = { - load: load, - overwrite: overwrite - }; +/** + * Enriches passed event with request data. + * + * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. + * + * @param event Will be mutated and enriched with req data + * @param req Request object + * @param options object containing flags to enable functionality + * @hidden + */ +function parseRequest(event, req, options = {}) { + return utils.addRequestDataToEvent(event, req, { include: options }); +} - var DLList; +exports.extractRequestData = extractRequestData; +exports.parseRequest = parseRequest; +//# sourceMappingURL=requestDataDeprecated.js.map - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } +/***/ }), - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } +/***/ 89149: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - first() { - if (this._first != null) { - return this._first.value; - } - } +var { + _optionalChain +} = __nccwpck_require__(25304); - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const index$2 = __nccwpck_require__(15850); +const client = __nccwpck_require__(36458); +const console = __nccwpck_require__(66572); +const context = __nccwpck_require__(54090); +const contextlines = __nccwpck_require__(11367); +const http = __nccwpck_require__(32649); +const index$1 = __nccwpck_require__(8705); +const modules = __nccwpck_require__(94288); +const onuncaughtexception = __nccwpck_require__(83790); +const onunhandledrejection = __nccwpck_require__(28798); +const spotlight = __nccwpck_require__(16733); +const index = __nccwpck_require__(32094); +const module$1 = __nccwpck_require__(76137); +const http$1 = __nccwpck_require__(94098); - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } +/* eslint-disable max-lines */ - }; +/** @deprecated Use `getDefaultIntegrations(options)` instead. */ +const defaultIntegrations = [ + // Common + core.inboundFiltersIntegration(), + core.functionToStringIntegration(), + core.linkedErrorsIntegration(), + core.requestDataIntegration(), + // Native Wrappers + console.consoleIntegration(), + http.httpIntegration(), + index.nativeNodeFetchintegration(), + // Global Handlers + onuncaughtexception.onUncaughtExceptionIntegration(), + onunhandledrejection.onUnhandledRejectionIntegration(), + // Event Info + contextlines.contextLinesIntegration(), + index$1.localVariablesIntegration(), + context.nodeContextIntegration(), + modules.modulesIntegration(), +]; - var DLList_1 = DLList; +/** Get the default integrations for the Node SDK. */ +function getDefaultIntegrations(_options) { + const carrier = core.getMainCarrier(); - var Events; + const autoloadedIntegrations = _optionalChain([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } + return [ + // eslint-disable-next-line deprecation/deprecation + ...defaultIntegrations, + ...autoloadedIntegrations, + ]; +} - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } +/** + * The Sentry Node SDK Client. + * + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. + * + * @example + * ``` + * + * const { init } = require('@sentry/node'); + * + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` + * + * @example + * ``` + * + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` + * + * @see {@link NodeOptions} for documentation on configuration options. + */ +// eslint-disable-next-line complexity +function init(options = {}) { + index$2.setNodeAsyncContextStrategy(); - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + if (options.defaultIntegrations === undefined) { + options.defaultIntegrations = getDefaultIntegrations(); + } - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; + } - }; + const sentryTracesSampleRate = process.env.SENTRY_TRACES_SAMPLE_RATE; + if (options.tracesSampleRate === undefined && sentryTracesSampleRate) { + const tracesSampleRate = parseFloat(sentryTracesSampleRate); + if (isFinite(tracesSampleRate)) { + options.tracesSampleRate = tracesSampleRate; + } + } - var Events_1 = Events; + if (options.release === undefined) { + const detectedRelease = getSentryRelease(); + if (detectedRelease !== undefined) { + options.release = detectedRelease; + } else { + // If release is not provided, then we should disable autoSessionTracking + options.autoSessionTracking = false; + } + } - var DLList$1, Events$1, Queues; + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } - DLList$1 = DLList_1; + if (options.autoSessionTracking === undefined && options.dsn !== undefined) { + options.autoSessionTracking = true; + } - Events$1 = Events_1; + if (options.instrumenter === undefined) { + options.instrumenter = 'sentry'; + } - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } + // TODO(v7): Refactor this to reduce the logic above + const clientOptions = { + ...options, + stackParser: utils.stackParserFromStackParserOptions(options.stackParser || defaultStackParser), + integrations: core.getIntegrationsToSetup(options), + transport: options.transport || http$1.makeNodeTransport, + }; - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } + core.initAndBind(options.clientClass || client.NodeClient, clientOptions); - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + if (options.autoSessionTracking) { + startSessionTracking(); + } - push(job) { - return this._lists[job.options.priority].push(job); - } + updateScopeFromEnvVariables(); - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } + if (options.spotlight) { + const client = core.getClient(); + if (client && client.addIntegration) { + // force integrations to be setup even if no DSN was set + // If they have already been added before, they will be ignored anyhow + const integrations = client.getOptions().integrations; + for (const integration of integrations) { + client.addIntegration(integration); + } + client.addIntegration( + spotlight.spotlightIntegration({ sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined }), + ); + } + } +} - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } +/** + * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client + */ +function isAutoSessionTrackingEnabled(client) { + if (client === undefined) { + return false; + } + const clientOptions = client && client.getOptions(); + if (clientOptions && clientOptions.autoSessionTracking !== undefined) { + return clientOptions.autoSessionTracking; + } + return false; +} - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } +/** + * Returns a release dynamically from environment variables. + */ +function getSentryRelease(fallback) { + // Always read first as Sentry takes this as precedence + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; + } - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + // This supports the variable that sentry-webpack-plugin injects + if (utils.GLOBAL_OBJ.SENTRY_RELEASE && utils.GLOBAL_OBJ.SENTRY_RELEASE.id) { + return utils.GLOBAL_OBJ.SENTRY_RELEASE.id; + } - }; + return ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env.GITHUB_SHA || + // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env.COMMIT_REF || + // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env.VERCEL_GIT_COMMIT_SHA || + process.env.VERCEL_GITHUB_COMMIT_SHA || + process.env.VERCEL_GITLAB_COMMIT_SHA || + process.env.VERCEL_BITBUCKET_COMMIT_SHA || + // Zeit (now known as Vercel) + process.env.ZEIT_GITHUB_COMMIT_SHA || + process.env.ZEIT_GITLAB_COMMIT_SHA || + process.env.ZEIT_BITBUCKET_COMMIT_SHA || + // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables + process.env.CF_PAGES_COMMIT_SHA || + fallback + ); +} - var Queues_1 = Queues; +/** Node.js stack parser */ +const defaultStackParser = utils.createStackParser(utils.nodeStackLineParser(module$1.createGetModuleFromFilename())); - var BottleneckError; +/** + * Enable automatic Session Tracking for the node process. + */ +function startSessionTracking() { + core.startSession(); + // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because + // The 'beforeExit' event is not emitted for conditions causing explicit termination, + // such as calling process.exit() or uncaught exceptions. + // Ref: https://nodejs.org/api/process.html#process_event_beforeexit + process.on('beforeExit', () => { + const session = core.getIsolationScope().getSession(); + const terminalStates = ['exited', 'crashed']; + // Only call endSession, if the Session exists on Scope and SessionStatus is not a + // Terminal Status i.e. Exited or Crashed because + // "When a session is moved away from ok it must not be updated anymore." + // Ref: https://develop.sentry.dev/sdk/sessions/ + if (session && !terminalStates.includes(session.status)) { + core.endSession(); + } + }); +} - BottleneckError = class BottleneckError extends Error {}; +/** + * Update scope and propagation context based on environmental variables. + * + * See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md + * for more details. + */ +function updateScopeFromEnvVariables() { + const sentryUseEnvironment = (process.env.SENTRY_USE_ENVIRONMENT || '').toLowerCase(); + if (!['false', 'n', 'no', 'off', '0'].includes(sentryUseEnvironment)) { + const sentryTraceEnv = process.env.SENTRY_TRACE; + const baggageEnv = process.env.SENTRY_BAGGAGE; + const propagationContext = utils.propagationContextFromHeaders(sentryTraceEnv, baggageEnv); + core.getCurrentScope().setPropagationContext(propagationContext); + } +} - var BottleneckError_1 = BottleneckError; +exports.defaultIntegrations = defaultIntegrations; +exports.defaultStackParser = defaultStackParser; +exports.getDefaultIntegrations = getDefaultIntegrations; +exports.getSentryRelease = getSentryRelease; +exports.init = init; +exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled; +//# sourceMappingURL=sdk.js.map - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - NUM_PRIORITIES = 10; +/***/ }), - DEFAULT_PRIORITY = 5; +/***/ 19504: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parser$1 = parser; +Object.defineProperty(exports, "__esModule", ({ value: true })); - BottleneckError$1 = BottleneckError_1; +const tracing = __nccwpck_require__(41143); +const utils = __nccwpck_require__(25304); - Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } +/** + * Automatically detects and returns integrations that will work with your dependencies. + */ +function autoDiscoverNodePerformanceMonitoringIntegrations() { + const loadedIntegrations = tracing.lazyLoadedNodePerformanceMonitoringIntegrations + .map(tryLoad => { + try { + return tryLoad(); + } catch (_) { + return undefined; + } + }) + .filter(integration => !!integration) ; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } + if (loadedIntegrations.length === 0) { + utils.logger.warn('Performance monitoring integrations could not be automatically loaded.'); + } - _randomIndex() { - return Math.random().toString(36).slice(2); - } + // Only return integrations where their dependencies loaded successfully. + return loadedIntegrations.filter(integration => !!integration.loadDependency()); +} - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } +exports.autoDiscoverNodePerformanceMonitoringIntegrations = autoDiscoverNodePerformanceMonitoringIntegrations; +//# sourceMappingURL=index.js.map - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } +/***/ }), - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } +/***/ 52501: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } +const tracing = __nccwpck_require__(41143); - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } +exports.Apollo = tracing.Apollo; +exports.Express = tracing.Express; +exports.GraphQL = tracing.GraphQL; +exports.Mongo = tracing.Mongo; +exports.Mysql = tracing.Mysql; +exports.Postgres = tracing.Postgres; +exports.Prisma = tracing.Prisma; +//# sourceMappingURL=integrations.js.map - }; - var Job_1 = Job; +/***/ }), - var BottleneckError$2, LocalDatastore, parser$2; +/***/ 94098: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - parser$2 = parser; +var { + _nullishCoalesce +} = __nccwpck_require__(25304); - BottleneckError$2 = BottleneckError_1; +Object.defineProperty(exports, "__esModule", ({ value: true })); - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } +const http = __nccwpck_require__(58611); +const https = __nccwpck_require__(65692); +const stream = __nccwpck_require__(2203); +const url = __nccwpck_require__(87016); +const zlib = __nccwpck_require__(43106); +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); +const index = __nccwpck_require__(13058); - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } +// Estimated maximum size for reasonable standalone event +const GZIP_THRESHOLD = 1024 * 32; - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } +/** + * Gets a stream from a Uint8Array or string + * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 + */ +function streamFromBody(body) { + return new stream.Readable({ + read() { + this.push(body); + this.push(null); + }, + }); +} - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } +/** + * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. + */ +function makeNodeTransport(options) { + let urlSegments; - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } + try { + urlSegments = new url.URL(options.url); + } catch (e) { + utils.consoleSandbox(() => { + // eslint-disable-next-line no-console + console.warn( + '[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.', + ); + }); + return core.createTransport(options, () => Promise.resolve({})); + } - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } + const isHttps = urlSegments.protocol === 'https:'; - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } + // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` + // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` + const proxy = applyNoProxyOption( + urlSegments, + options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, + ); - async __running__() { - await this.yieldLoop(); - return this._running; - } + const nativeHttpModule = isHttps ? https : http; + const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } + // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node + // versions(>= 8) as they had memory leaks when using it: #2555 + const agent = proxy + ? (new index.HttpsProxyAgent(proxy) ) + : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); - async __done__() { - await this.yieldLoop(); - return this._done; - } + const requestExecutor = createRequestExecutor(options, _nullishCoalesce(options.httpModule, () => ( nativeHttpModule)), agent); + return core.createTransport(options, requestExecutor); +} - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } +/** + * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. + * + * @param transportUrl The URL the transport intends to send events to. + * @param proxy The client configured proxy. + * @returns A proxy the transport should use. + */ +function applyNoProxyOption(transportUrlSegments, proxy) { + const { no_proxy } = process.env; + + const urlIsExemptFromProxy = + no_proxy && + no_proxy + .split(',') + .some( + exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), + ); - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } + if (urlIsExemptFromProxy) { + return undefined; + } else { + return proxy; + } +} - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +/** + * Creates a RequestExecutor to be used with `createTransport`. + */ +function createRequestExecutor( + options, + httpModule, + agent, +) { + const { hostname, pathname, port, protocol, search } = new url.URL(options.url); + return function makeRequest(request) { + return new Promise((resolve, reject) => { + let body = streamFromBody(request.body); - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } + const headers = { ...options.headers }; - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } + if (request.body.length > GZIP_THRESHOLD) { + headers['content-encoding'] = 'gzip'; + body = body.pipe(zlib.createGzip()); + } - isBlocked(now) { - return this._unblockTime >= now; - } + const req = httpModule.request( + { + method: 'POST', + agent, + headers, + hostname, + path: `${pathname}${search}`, + port, + protocol, + ca: options.caCerts, + }, + res => { + res.on('data', () => { + // Drain socket + }); - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } + res.on('end', () => { + // Drain socket + }); - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } + res.setEncoding('utf8'); - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } + // "Key-value pairs of header names and values. Header names are lower-cased." + // https://nodejs.org/api/http.html#http_message_headers + const retryAfterHeader = _nullishCoalesce(res.headers['retry-after'], () => ( null)); + const rateLimitsHeader = _nullishCoalesce(res.headers['x-sentry-rate-limits'], () => ( null)); - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + resolve({ + statusCode: res.statusCode, + headers: { + 'retry-after': retryAfterHeader, + 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, + }, + }); + }, + ); - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } + req.on('error', reject); + body.pipe(req); + }); + }; +} - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } +exports.makeNodeTransport = makeNodeTransport; +//# sourceMappingURL=http.js.map - }; - var LocalDatastore_1 = LocalDatastore; +/***/ }), - var BottleneckError$3, States; +/***/ 98074: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - BottleneckError$3 = BottleneckError_1; +var { + _optionalChain +} = __nccwpck_require__(25304); - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } +const core = __nccwpck_require__(75062); +const utils = __nccwpck_require__(25304); - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } +/** + * Sentry tRPC middleware that names the handling transaction after the called procedure. + * + * Use the Sentry tRPC middleware in combination with the Sentry server integration, + * e.g. Express Request Handlers or Next.js SDK. + */ +function trpcMiddleware(options = {}) { + return function ({ path, type, next, rawInput }) { + const clientOptions = _optionalChain([core.getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3()]); + // eslint-disable-next-line deprecation/deprecation + const sentryTransaction = core.getCurrentScope().getTransaction(); - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } + if (sentryTransaction) { + sentryTransaction.updateName(`trpc/${path}`); + sentryTransaction.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route'); + sentryTransaction.op = 'rpc.server'; - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } + const trpcContext = { + procedure_type: type, + }; - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } + if (options.attachRpcInput !== undefined ? options.attachRpcInput : _optionalChain([clientOptions, 'optionalAccess', _4 => _4.sendDefaultPii])) { + trpcContext.input = utils.normalize(rawInput); + } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } + // TODO: Can we rewrite this to an attribute? Or set this on the scope? + // eslint-disable-next-line deprecation/deprecation + sentryTransaction.setContext('trpc', trpcContext); + } - }; + function captureIfError(nextResult) { + if (!nextResult.ok) { + core.captureException(nextResult.error, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); + } + } - var States_1 = States; + let maybePromiseResult; + try { + maybePromiseResult = next(); + } catch (e) { + core.captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); + throw e; + } - var DLList$2, Sync; + if (utils.isThenable(maybePromiseResult)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + Promise.resolve(maybePromiseResult).then( + nextResult => { + captureIfError(nextResult ); + }, + e => { + core.captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); + }, + ); + } else { + captureIfError(maybePromiseResult ); + } - DLList$2 = DLList_1; + // We return the original promise just to be safe. + return maybePromiseResult; + }; +} - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } +exports.trpcMiddleware = trpcMiddleware; +//# sourceMappingURL=trpc.js.map - isEmpty() { - return this._queue.length === 0; - } - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } +/***/ }), - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } +/***/ 67036: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var Sync_1 = Sync; +const fs = __nccwpck_require__(79896); +const path = __nccwpck_require__(16928); - var version = "2.19.5"; - var version$1 = { - version: version - }; +/** + * Recursively read the contents of a directory. + * + * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this + * directory. + * @returns Array holding all relative paths + * @deprecated This function will be removed in the next major version. + */ +function deepReadDirSync(targetDir) { + const targetDirAbsPath = path.resolve(targetDir); - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); + if (!fs.existsSync(targetDirAbsPath)) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); + } - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (!fs.statSync(targetDirAbsPath).isDirectory()) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); + } - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it + // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve + // the difference between `targetDirAbsPath` and `currentDirAbsPath`. + const deepReadCurrentDir = (currentDirAbsPath) => { + return fs.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { + const itemAbsPath = path.join(currentDirAbsPath, itemName); - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + if (fs.statSync(itemAbsPath).isDirectory()) { + return absPaths.concat(deepReadCurrentDir(itemAbsPath)); + } - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + absPaths.push(itemAbsPath); + return absPaths; + }, []); + }; - parser$3 = parser; + return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath)); +} - Events$2 = Events_1; +exports.deepReadDirSync = deepReadDirSync; +//# sourceMappingURL=utils.js.map - RedisConnection$1 = require$$2; - IORedisConnection$1 = require$$3; +/***/ }), - Scripts$1 = require$$4; +/***/ 36555: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +const is = __nccwpck_require__(36958); +const string = __nccwpck_require__(98439); - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } +/** + * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter. + */ +function applyAggregateErrorsToEvent( + exceptionFromErrorImplementation, + parser, + maxValueLimit = 250, + key, + limit, + event, + hint, +) { + if (!event.exception || !event.exception.values || !hint || !is.isInstanceOf(hint.originalException, Error)) { + return; + } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } + // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error + const originalException = + event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined; + + // We only create exception grouping if there is an exception in the event. + if (originalException) { + event.exception.values = truncateAggregateExceptions( + aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + hint.originalException , + key, + event.exception.values, + originalException, + 0, + ), + maxValueLimit, + ); + } +} - keys() { - return Object.keys(this.instances); - } +function aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + error, + key, + prevExceptions, + exception, + exceptionId, +) { + if (prevExceptions.length >= limit + 1) { + return prevExceptions; + } + + let newExceptions = [...prevExceptions]; + + // Recursively call this function in order to walk down a chain of errors + if (is.isInstanceOf(error[key], Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, error[key]); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + error[key], + key, + [newException, ...newExceptions], + newException, + newExceptionId, + ); + } - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } + // This will create exception grouping for AggregateErrors + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError + if (Array.isArray(error.errors)) { + error.errors.forEach((childError, i) => { + if (is.isInstanceOf(childError, Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, childError); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError( + exceptionFromErrorImplementation, + parser, + limit, + childError, + key, + [newException, ...newExceptions], + newException, + newExceptionId, + ); + } + }); + } - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } + return newExceptions; +} - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +function applyExceptionGroupFieldsForParentException(exception, exceptionId) { + // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default. + exception.mechanism = exception.mechanism || { type: 'generic', handled: true }; - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + exception.mechanism = { + ...exception.mechanism, + ...(exception.type === 'AggregateError' && { is_exception_group: true }), + exception_id: exceptionId, + }; +} - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; +function applyExceptionGroupFieldsForChildException( + exception, + source, + exceptionId, + parentId, +) { + // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default. + exception.mechanism = exception.mechanism || { type: 'generic', handled: true }; + + exception.mechanism = { + ...exception.mechanism, + type: 'chained', + source, + exception_id: exceptionId, + parent_id: parentId, + }; +} - return Group; +/** + * Truncate the message (exception.value) of all exceptions in the event. + * Because this event processor is ran after `applyClientOptions`, + * we need to truncate the message of the added exceptions here. + */ +function truncateAggregateExceptions(exceptions, maxValueLength) { + return exceptions.map(exception => { + if (exception.value) { + exception.value = string.truncate(exception.value, maxValueLength); + } + return exception; + }); +} - }).call(commonjsGlobal); +exports.applyAggregateErrorsToEvent = applyAggregateErrorsToEvent; +//# sourceMappingURL=aggregate-errors.js.map - var Group_1 = Group; - var Batcher, Events$3, parser$4; +/***/ }), - parser$4 = parser; +/***/ 42939: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Events$3 = Events_1; +Object.defineProperty(exports, "__esModule", ({ value: true })); - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } +const object = __nccwpck_require__(36941); +const nodeStackTrace = __nccwpck_require__(60851); - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +/** + * A node.js watchdog timer + * @param pollInterval The interval that we expect to get polled at + * @param anrThreshold The threshold for when we consider ANR + * @param callback The callback to call for ANR + * @returns An object with `poll` and `enabled` functions {@link WatchdogReturn} + */ +function watchdogTimer( + createTimer, + pollInterval, + anrThreshold, + callback, +) { + const timer = createTimer(); + let triggered = false; + let enabled = true; - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + setInterval(() => { + const diffMs = timer.getTimeMs(); - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } + if (triggered === false && diffMs > pollInterval + anrThreshold) { + triggered = true; + if (enabled) { + callback(); + } + } - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; + if (diffMs < pollInterval + anrThreshold) { + triggered = false; + } + }, 20); - return Batcher; + return { + poll: () => { + timer.reset(); + }, + enabled: (state) => { + enabled = state; + }, + }; +} - }).call(commonjsGlobal); +// types copied from inspector.d.ts - var Batcher_1 = Batcher; +/** + * Converts Debugger.CallFrame to Sentry StackFrame + */ +function callFrameToStackFrame( + frame, + url, + getModuleFromFilename, +) { + const filename = url ? url.replace(/^file:\/\//, '') : undefined; + + // CallFrame row/col are 0 based, whereas StackFrame are 1 based + const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : undefined; + const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : undefined; + + return object.dropUndefinedKeys({ + filename, + module: getModuleFromFilename(filename), + function: frame.functionName || '?', + colno, + lineno, + in_app: filename ? nodeStackTrace.filenameIsInApp(filename) : undefined, + }); +} - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +exports.callFrameToStackFrame = callFrameToStackFrame; +exports.watchdogTimer = watchdogTimer; +//# sourceMappingURL=anr.js.map - var require$$8 = getCjsExportFromNamespace(version$2); - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; +/***/ }), - NUM_PRIORITIES$1 = 10; +/***/ 41022: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - DEFAULT_PRIORITY$1 = 5; +Object.defineProperty(exports, "__esModule", ({ value: true })); - parser$5 = parser; +const debugBuild = __nccwpck_require__(61782); +const is = __nccwpck_require__(36958); +const logger = __nccwpck_require__(8758); - Queues$1 = Queues_1; +const BAGGAGE_HEADER_NAME = 'baggage'; - Job$1 = Job_1; +const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; - LocalDatastore$1 = LocalDatastore_1; +const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; - RedisDatastore$1 = require$$4$1; +/** + * Max length of a serialized baggage string + * + * https://www.w3.org/TR/baggage/#limits + */ +const MAX_BAGGAGE_STRING_LENGTH = 8192; - Events$4 = Events_1; +/** + * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values + * from it. + * + * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. + * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. + */ +function baggageHeaderToDynamicSamplingContext( + // Very liberal definition of what any incoming header might look like + baggageHeader, +) { + if (!is.isString(baggageHeader) && !Array.isArray(baggageHeader)) { + return undefined; + } - States$1 = States_1; + // Intermediary object to store baggage key value pairs of incoming baggage headers on. + // It is later used to read Sentry-DSC-values from. + let baggageObject = {}; - Sync$1 = Sync_1; + if (Array.isArray(baggageHeader)) { + // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it + baggageObject = baggageHeader.reduce((acc, curr) => { + const currBaggageObject = baggageHeaderToObject(curr); + for (const key of Object.keys(currBaggageObject)) { + acc[key] = currBaggageObject[key]; + } + return acc; + }, {}); + } else { + // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but + // this is how we choose to handle it) + if (!baggageHeader) { + return undefined; + } - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } + baggageObject = baggageHeaderToObject(baggageHeader); + } - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } + // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. + const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { + if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { + const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); + acc[nonPrefixedKey] = value; + } + return acc; + }, {}); - ready() { - return this._store.ready; - } + // Only return a dynamic sampling context object if there are keys in it. + // A keyless object means there were no sentry values on the header, which means that there is no DSC. + if (Object.keys(dynamicSamplingContext).length > 0) { + return dynamicSamplingContext ; + } else { + return undefined; + } +} - clients() { - return this._store.clients; - } +/** + * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". + * + * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility + * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is + * `undefined` the function will return `undefined`. + * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` + * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. + */ +function dynamicSamplingContextToSentryBaggageHeader( + // this also takes undefined for convenience and bundle size in other places + dynamicSamplingContext, +) { + if (!dynamicSamplingContext) { + return undefined; + } - channel() { - return `b_${this.id}`; - } + // Prefix all DSC keys with "sentry-" and put them into a new object + const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( + (acc, [dscKey, dscValue]) => { + if (dscValue) { + acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; + } + return acc; + }, + {}, + ); - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + return objectToBaggageHeader(sentryPrefixedDSC); +} - publish(message) { - return this._store.__publish__(message); - } +/** + * Will parse a baggage header, which is a simple key-value map, into a flat object. + * + * @param baggageHeader The baggage header to parse. + * @returns a flat object containing all the key-value pairs from `baggageHeader`. + */ +function baggageHeaderToObject(baggageHeader) { + return baggageHeader + .split(',') + .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) + .reduce((acc, [key, value]) => { + acc[key] = value; + return acc; + }, {}); +} - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } +/** + * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. + * + * @param object The object to turn into a baggage header. + * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header + * is not spec compliant. + */ +function objectToBaggageHeader(object) { + if (Object.keys(object).length === 0) { + // An empty baggage header is not spec compliant: We return undefined. + return undefined; + } - chain(_limiter) { - this._limiter = _limiter; - return this; - } + return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { + const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; + const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; + if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { + debugBuild.DEBUG_BUILD && + logger.logger.warn( + `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, + ); + return baggageHeader; + } else { + return newBaggageHeader; + } + }, ''); +} - queued(priority) { - return this._queues.queued(priority); - } +exports.BAGGAGE_HEADER_NAME = BAGGAGE_HEADER_NAME; +exports.MAX_BAGGAGE_STRING_LENGTH = MAX_BAGGAGE_STRING_LENGTH; +exports.SENTRY_BAGGAGE_KEY_PREFIX = SENTRY_BAGGAGE_KEY_PREFIX; +exports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = SENTRY_BAGGAGE_KEY_PREFIX_REGEX; +exports.baggageHeaderToDynamicSamplingContext = baggageHeaderToDynamicSamplingContext; +exports.dynamicSamplingContextToSentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader; +//# sourceMappingURL=baggage.js.map - clusterQueued() { - return this._store.__queued__(); - } - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +/***/ }), - running() { - return this._store.__running__(); - } +/***/ 83732: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - done() { - return this._store.__done__(); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - jobStatus(id) { - return this._states.jobStatus(id); - } +const is = __nccwpck_require__(36958); +const worldwide = __nccwpck_require__(35291); - jobs(status) { - return this._states.statusJobs(status); - } +// eslint-disable-next-line deprecation/deprecation +const WINDOW = worldwide.getGlobalObject(); - counts() { - return this._states.statusCounts(); - } +const DEFAULT_MAX_STRING_LENGTH = 80; - _randomIndex() { - return Math.random().toString(36).slice(2); - } +/** + * Given a child DOM element, returns a query-selector statement describing that + * and its ancestors + * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] + * @returns generated DOM path + */ +function htmlTreeAsString( + elem, + options = {}, +) { + if (!elem) { + return ''; + } - check(weight = 1) { - return this._store.__check__(weight); - } + // try/catch both: + // - accessing event.target (see getsentry/raven-js#838, #768) + // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly + // - can throw an exception in some circumstances. + try { + let currentElem = elem ; + const MAX_TRAVERSE_HEIGHT = 5; + const out = []; + let height = 0; + let len = 0; + const separator = ' > '; + const sepLength = separator.length; + let nextStr; + const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; + const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH; + + while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem, keyAttrs); + // bail out if + // - nextStr is the 'html' element + // - the length of the string that would be created exceeds maxStringLength + // (ignore this limit if we are on the first iteration) + if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) { + break; + } - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } + out.push(nextStr); - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } + len += nextStr.length; + currentElem = currentElem.parentNode; + } - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } + return out.reverse().join(separator); + } catch (_oO) { + return ''; + } +} - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } +/** + * Returns a simple, query-selector representation of a DOM element + * e.g. [HTMLElement] => input#foo.btn[name=baz] + * @returns generated DOM path + */ +function _htmlElementAsString(el, keyAttrs) { + const elem = el - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } +; - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } + const out = []; + let className; + let classes; + let key; + let attr; + let i; - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } + if (!elem || !elem.tagName) { + return ''; + } - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } + // @ts-expect-error WINDOW has HTMLElement + if (WINDOW.HTMLElement) { + // If using the component name annotation plugin, this value may be available on the DOM node + if (elem instanceof HTMLElement && elem.dataset && elem.dataset['sentryComponent']) { + return elem.dataset['sentryComponent']; + } + } - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } + out.push(elem.tagName.toLowerCase()); - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } + // Pairs of attribute keys defined in `serializeAttribute` and their values on element. + const keyAttrPairs = + keyAttrs && keyAttrs.length + ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) + : null; - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } + if (keyAttrPairs && keyAttrPairs.length) { + keyAttrPairs.forEach(keyAttrPair => { + out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); + }); + } else { + if (elem.id) { + out.push(`#${elem.id}`); + } - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } + // eslint-disable-next-line prefer-const + className = elem.className; + if (className && is.isString(className)) { + classes = className.split(/\s+/); + for (i = 0; i < classes.length; i++) { + out.push(`.${classes[i]}`); + } + } + } + const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt']; + for (i = 0; i < allowedAttrs.length; i++) { + key = allowedAttrs[i]; + attr = elem.getAttribute(key); + if (attr) { + out.push(`[${key}="${attr}"]`); + } + } + return out.join(''); +} - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } +/** + * A safe form of location.href + */ +function getLocationHref() { + try { + return WINDOW.document.location.href; + } catch (oO) { + return ''; + } +} - currentReservoir() { - return this._store.__currentReservoir__(); - } +/** + * Gets a DOM element by using document.querySelector. + * + * This wrapper will first check for the existance of the function before + * actually calling it so that we don't have to take care of this check, + * every time we want to access the DOM. + * + * Reason: DOM/querySelector is not available in all environments. + * + * We have to cast to any because utils can be consumed by a variety of environments, + * and we don't want to break TS users. If you know what element will be selected by + * `document.querySelector`, specify it as part of the generic call. For example, + * `const element = getDomElement('selector');` + * + * @param selector the selector string passed on to document.querySelector + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getDomElement(selector) { + if (WINDOW.document && WINDOW.document.querySelector) { + return WINDOW.document.querySelector(selector) ; + } + return null; +} - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +/** + * Given a DOM element, traverses up the tree until it finds the first ancestor node + * that has the `data-sentry-component` attribute. This attribute is added at build-time + * by projects that have the component name annotation plugin installed. + * + * @returns a string representation of the component for the provided DOM element, or `null` if not found + */ +function getComponentName(elem) { + // @ts-expect-error WINDOW has HTMLElement + if (!WINDOW.HTMLElement) { + return null; + } - } - Bottleneck.default = Bottleneck; + let currentElem = elem ; + const MAX_TRAVERSE_HEIGHT = 5; + for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) { + if (!currentElem) { + return null; + } - Bottleneck.Events = Events$4; + if (currentElem instanceof HTMLElement && currentElem.dataset['sentryComponent']) { + return currentElem.dataset['sentryComponent']; + } - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; + currentElem = currentElem.parentNode; + } - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; + return null; +} - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +exports.getComponentName = getComponentName; +exports.getDomElement = getDomElement; +exports.getLocationHref = getLocationHref; +exports.htmlTreeAsString = htmlTreeAsString; +//# sourceMappingURL=browser.js.map - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; +/***/ }), - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; +/***/ 77124: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; +Object.defineProperty(exports, "__esModule", ({ value: true })); - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; +const _nullishCoalesce = __nccwpck_require__(47378); - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; +// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; +/** + * Polyfill for the nullish coalescing operator (`??`), when used in situations where at least one of the values is the + * result of an async operation. + * + * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the + * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * + * @param lhs The value of the expression to the left of the `??` + * @param rhsFn A function returning the value of the expression to the right of the `??` + * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value + */ +async function _asyncNullishCoalesce(lhs, rhsFn) { + return _nullishCoalesce._nullishCoalesce(lhs, rhsFn); +} - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; +// Sucrase version: +// async function _asyncNullishCoalesce(lhs, rhsFn) { +// if (lhs != null) { +// return lhs; +// } else { +// return await rhsFn(); +// } +// } - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; +exports._asyncNullishCoalesce = _asyncNullishCoalesce; +//# sourceMappingURL=_asyncNullishCoalesce.js.map - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; - return Bottleneck; +/***/ }), - }).call(commonjsGlobal); +/***/ 52013: +/***/ ((__unused_webpack_module, exports) => { - var Bottleneck_1 = Bottleneck; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var lib = Bottleneck_1; +/** + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions, for situations in which at least one part of the expression is async. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See + * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * + * @param ops Array result of expression conversion + * @returns The value of the expression + */ +async function _asyncOptionalChain(ops) { + let lastAccessLHS = undefined; + let value = ops[0]; + let i = 1; + while (i < ops.length) { + const op = ops[i] ; + const fn = ops[i + 1] ; + i += 2; + // by checking for loose equality to `null`, we catch both `null` and `undefined` + if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { + // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it + return; + } + if (op === 'access' || op === 'optionalAccess') { + lastAccessLHS = value; + value = await fn(value); + } else if (op === 'call' || op === 'optionalCall') { + value = await fn((...args) => (value ).call(lastAccessLHS, ...args)); + lastAccessLHS = undefined; + } + } + return value; +} - return lib; +// Sucrase version: +// async function _asyncOptionalChain(ops) { +// let lastAccessLHS = undefined; +// let value = ops[0]; +// let i = 1; +// while (i < ops.length) { +// const op = ops[i]; +// const fn = ops[i + 1]; +// i += 2; +// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { +// return undefined; +// } +// if (op === 'access' || op === 'optionalAccess') { +// lastAccessLHS = value; +// value = await fn(value); +// } else if (op === 'call' || op === 'optionalCall') { +// value = await fn((...args) => value.call(lastAccessLHS, ...args)); +// lastAccessLHS = undefined; +// } +// } +// return value; +// } -}))); +exports._asyncOptionalChain = _asyncOptionalChain; +//# sourceMappingURL=_asyncOptionalChain.js.map /***/ }), -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 73718: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); +Object.defineProperty(exports, "__esModule", ({ value: true })); -module.exports = expandTop; +const _asyncOptionalChain = __nccwpck_require__(52013); -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'; +// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); +/** + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions, in cases where the value of the expression is to be deleted. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See + * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * + * @param ops Array result of expression conversion + * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable + * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which + * case `false`. + */ +async function _asyncOptionalChainDelete(ops) { + const result = (await _asyncOptionalChain._asyncOptionalChain(ops)) ; + // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case, + // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in + // which case we return whatever the `delete` returned, which will be a boolean. + return result == null ? true : (result ); } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} +// Sucrase version: +// async function asyncOptionalChainDelete(ops) { +// const result = await ASYNC_OPTIONAL_CHAIN_NAME(ops); +// return result == null ? true : result; +// } + +exports._asyncOptionalChainDelete = _asyncOptionalChainDelete; +//# sourceMappingURL=_asyncOptionalChainDelete.js.map + + +/***/ }), + +/***/ 47378: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f +// +// The MIT License (MIT) +// +// Copyright (c) 2012-2018 various contributors (see AUTHORS) +// +// 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. -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +/** + * Polyfill for the nullish coalescing operator (`??`). + * + * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the + * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * + * @param lhs The value of the expression to the left of the `??` + * @param rhsFn A function returning the value of the expression to the right of the `??` + * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value + */ +function _nullishCoalesce(lhs, rhsFn) { + // by checking for loose equality to `null`, we catch both `null` and `undefined` + return lhs != null ? lhs : rhsFn(); } +// Sucrase version: +// function _nullishCoalesce(lhs, rhsFn) { +// if (lhs != null) { +// return lhs; +// } else { +// return rhsFn(); +// } +// } -// 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 ['']; +exports._nullishCoalesce = _nullishCoalesce; +//# sourceMappingURL=_nullishCoalesce.js.map - var parts = []; - var m = balanced('{', '}', str); - if (!m) - return str.split(','); +/***/ }), + +/***/ 16151: +/***/ ((__unused_webpack_module, exports) => { - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +Object.defineProperty(exports, "__esModule", ({ value: true })); - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); +/** + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * + * @param ops Array result of expression conversion + * @returns The value of the expression + */ +function _optionalChain(ops) { + let lastAccessLHS = undefined; + let value = ops[0]; + let i = 1; + while (i < ops.length) { + const op = ops[i] ; + const fn = ops[i + 1] ; + i += 2; + // by checking for loose equality to `null`, we catch both `null` and `undefined` + if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { + // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it + return; + } + if (op === 'access' || op === 'optionalAccess') { + lastAccessLHS = value; + value = fn(value); + } else if (op === 'call' || op === 'optionalCall') { + value = fn((...args) => (value ).call(lastAccessLHS, ...args)); + lastAccessLHS = undefined; + } } + return value; +} - parts.push.apply(parts, p); +// Sucrase version +// function _optionalChain(ops) { +// let lastAccessLHS = undefined; +// let value = ops[0]; +// let i = 1; +// while (i < ops.length) { +// const op = ops[i]; +// const fn = ops[i + 1]; +// i += 2; +// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { +// return undefined; +// } +// if (op === 'access' || op === 'optionalAccess') { +// lastAccessLHS = value; +// value = fn(value); +// } else if (op === 'call' || op === 'optionalCall') { +// value = fn((...args) => value.call(lastAccessLHS, ...args)); +// lastAccessLHS = undefined; +// } +// } +// return value; +// } - return parts; -} +exports._optionalChain = _optionalChain; +//# sourceMappingURL=_optionalChain.js.map -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); -} +/***/ 78328: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function identity(e) { - return e; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +const _optionalChain = __nccwpck_require__(16151); -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; +// https://github.com/alangpierce/sucrase/tree/265887868966917f3b924ce38dfad01fbab1329f + +/** + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions, in cases where the value of the expression is to be deleted. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) See + * https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * + * @param ops Array result of expression conversion + * @returns The return value of the `delete` operator: `true`, unless the deletion target is an own, non-configurable + * property (one which can't be deleted or turned into an accessor, and whose enumerability can't be changed), in which + * case `false`. + */ +function _optionalChainDelete(ops) { + const result = _optionalChain._optionalChain(ops) ; + // If `result` is `null`, it means we didn't get to the end of the chain and so nothing was deleted (in which case, + // return `true` since that's what `delete` does when it no-ops). If it's non-null, we know the delete happened, in + // which case we return whatever the `delete` returned, which will be a boolean. + return result == null ? true : result; } -function expand(str, isTop) { - var expansions = []; +// Sucrase version: +// function _optionalChainDelete(ops) { +// const result = _optionalChain(ops); +// // by checking for loose equality to `null`, we catch both `null` and `undefined` +// return result == null ? true : result; +// } - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; +exports._optionalChainDelete = _optionalChainDelete; +//# sourceMappingURL=_optionalChainDelete.js.map - 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]; - } - 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; - }); - } - } - } +/***/ }), - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +/***/ 23758: +/***/ ((__unused_webpack_module, exports) => { - // 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) - : ['']; +Object.defineProperty(exports, "__esModule", ({ value: true })); - var N; +/** + * Creates a cache that evicts keys in fifo order + * @param size {Number} + */ +function makeFifoCache( + size, +) - 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); + { + // Maintain a fifo queue of keys, we cannot rely on Object.keys as the browser may not support it. + let evictionOrder = []; + let cache = {}; - N = []; + return { + add(key, value) { + while (evictionOrder.length >= size) { + // shift is O(n) but this is small size and only happens if we are + // exceeding the cache size so it should be fine. + const evictCandidate = evictionOrder.shift(); - 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; - } + if (evictCandidate !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete cache[evictCandidate]; } } - 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); - } - } + // in case we have a collision, delete the old key. + if (cache[key]) { + this.delete(key); + } + + evictionOrder.push(key); + cache[key] = value; + }, + clear() { + cache = {}; + evictionOrder = []; + }, + get(key) { + return cache[key]; + }, + size() { + return evictionOrder.length; + }, + // Delete cache key and return true if it existed, false otherwise. + delete(key) { + if (!cache[key]) { + return false; + } + + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete cache[key]; + + for (let i = 0; i < evictionOrder.length; i++) { + if (evictionOrder[i] === key) { + evictionOrder.splice(i, 1); + break; + } + } - return expansions; + return true; + }, + }; } +exports.makeFifoCache = makeFifoCache; +//# sourceMappingURL=cache.js.map /***/ }), -/***/ 72358: -/***/ ((module) => { +/***/ 46659: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = function btoa(str) { - return new Buffer(str).toString('base64') +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const envelope = __nccwpck_require__(20950); +const time = __nccwpck_require__(4907); + +/** + * Creates client report envelope + * @param discarded_events An array of discard events + * @param dsn A DSN that can be set on the header. Optional. + */ +function createClientReportEnvelope( + discarded_events, + dsn, + timestamp, +) { + const clientReportItem = [ + { type: 'client_report' }, + { + timestamp: timestamp || time.dateTimestampInSeconds(), + discarded_events, + }, + ]; + return envelope.createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); } +exports.createClientReportEnvelope = createClientReportEnvelope; +//# sourceMappingURL=clientreport.js.map + /***/ }), -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 51244: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -/*jshint node:true */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -var Buffer = (__nccwpck_require__(14300).Buffer); // browserify -var SlowBuffer = (__nccwpck_require__(14300).SlowBuffer); +/** + * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case. + * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js + * It had the following license: + * + * (The MIT License) + * + * Copyright (c) 2012-2014 Roman Shtylman + * Copyright (c) 2015 Douglas Christopher Wilson + * + * 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 = bufferEq; +/** + * Parses a cookie string + */ +function parseCookie(str) { + const obj = {}; + let index = 0; -function bufferEq(a, b) { + while (index < str.length) { + const eqIdx = str.indexOf('=', index); - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } + // no more cookie pairs + if (eqIdx === -1) { + break; + } - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } + let endIdx = str.indexOf(';', index); - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + // backtrack on prior semicolon + index = str.lastIndexOf(';', eqIdx - 1) + 1; + continue; + } -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; + const key = str.slice(index, eqIdx).trim(); -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; + // only assign once + if (undefined === obj[key]) { + let val = str.slice(eqIdx + 1, endIdx).trim(); + // quoted values + if (val.charCodeAt(0) === 0x22) { + val = val.slice(1, -1); + } -/***/ }), + try { + obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val; + } catch (e) { + obj[key] = val; + } + } -/***/ 86966: -/***/ ((module) => { + index = endIdx + 1; + } -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ + return obj; +} +exports.parseCookie = parseCookie; +//# sourceMappingURL=cookie.js.map -/** - * Module exports. - * @public - */ +/***/ }), -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; +/***/ 61782: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Module variables. - * @private + * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code. + * + * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking. */ +const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__); -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; +exports.DEBUG_BUILD = DEBUG_BUILD; +//# sourceMappingURL=debug-build.js.map -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; +/***/ }), -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; +/***/ 92269: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } +const debugBuild = __nccwpck_require__(61782); +const logger = __nccwpck_require__(8758); - if (typeof value === 'number') { - return format(value, options); - } +/** Regular expression used to parse a Dsn. */ +const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; - return null; +function isValidProtocol(protocol) { + return protocol === 'http' || protocol === 'https'; } /** - * Format the given value in bytes into a string. + * Renders the string representation of this Dsn. * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. + * By default, this will render the public representation without the password + * component. To get the deprecated private representation, set `withPassword` + * to true. * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] + * @param withPassword When set to true, the password will be included. + */ +function dsnToString(dsn, withPassword = false) { + const { host, path, pass, port, projectId, protocol, publicKey } = dsn; + return ( + `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + + `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` + ); +} + +/** + * Parses a Dsn from a given string. * - * @returns {string|null} - * @public + * @param str A Dsn as string + * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string */ +function dsnFromString(str) { + const match = DSN_REGEX.exec(str); -function format(value, options) { - if (!Number.isFinite(value)) { - return null; + if (!match) { + // This should be logged to the console + logger.consoleSandbox(() => { + // eslint-disable-next-line no-console + console.error(`Invalid Sentry Dsn: ${str}`); + }); + return undefined; } - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; + const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); + let path = ''; + let projectId = lastPath; - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; + const split = projectId.split('/'); + if (split.length > 1) { + path = split.slice(0, -1).join('/'); + projectId = split.pop() ; + } + + if (projectId) { + const projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; } } - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); + return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); +} - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); +function dsnFromComponents(components) { + return { + protocol: components.protocol, + publicKey: components.publicKey || '', + pass: components.pass || '', + host: components.host, + port: components.port || '', + path: components.path || '', + projectId: components.projectId, + }; +} + +function validateDsn(dsn) { + if (!debugBuild.DEBUG_BUILD) { + return true; } - if (thousandsSeparator) { - str = str.split('.').map(function (s, i) { - return i === 0 - ? s.replace(formatThousandsRegExp, thousandsSeparator) - : s - }).join('.'); - } - - return str + unitSeparator + unit; -} + const { port, projectId, protocol } = dsn; -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ + const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; + const hasMissingRequiredComponent = requiredComponents.find(component => { + if (!dsn[component]) { + logger.logger.error(`Invalid Sentry Dsn: ${component} missing`); + return true; + } + return false; + }); -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; + if (hasMissingRequiredComponent) { + return false; } - if (typeof val !== 'string') { - return null; + if (!projectId.match(/^\d+$/)) { + logger.logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); + return false; } - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); + if (!isValidProtocol(protocol)) { + logger.logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); + return false; } - if (isNaN(floatValue)) { - return null; + if (port && isNaN(parseInt(port, 10))) { + logger.logger.error(`Invalid Sentry Dsn: Invalid port ${port}`); + return false; } - return Math.floor(map[unit] * floatValue); + return true; +} + +/** + * Creates a valid Sentry Dsn object, identifying a Sentry instance and project. + * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source + */ +function makeDsn(from) { + const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); + if (!components || !validateDsn(components)) { + return undefined; + } + return components; } +exports.dsnFromString = dsnFromString; +exports.dsnToString = dsnToString; +exports.makeDsn = makeDsn; +//# sourceMappingURL=dsn.js.map + /***/ }), -/***/ 27972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 60995: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); -const os = __nccwpck_require__(22037); +/* + * This module exists for optimizations in the build process through rollup and terser. We define some global + * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these + * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will + * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to + * `logger` and preventing node-related code from appearing in browser bundles. + * + * Attention: + * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by + * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack) + * having issues tree-shaking these constants across package boundaries. + * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want + * users to be able to shake away expressions that it guards. + */ -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); +/** + * Figures out if we're building a browser bundle. + * + * @returns true if this is a browser bundle build. + */ +function isBrowserBundle() { + return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; +} -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); +/** + * Get source of SDK. + */ +function getSDKSource() { + // @ts-expect-error "npm" is injected by rollup during build process + return "npm"; +} - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } +exports.getSDKSource = getSDKSource; +exports.isBrowserBundle = isBrowserBundle; +//# sourceMappingURL=env.js.map - const match = pathMatches[1]; - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } +/***/ }), - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } +/***/ 20950: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return line; - }) - .join('\n'); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const dsn = __nccwpck_require__(92269); +const normalize = __nccwpck_require__(6811); +const object = __nccwpck_require__(36941); -/***/ }), +/** + * Creates an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. + */ +function createEnvelope(headers, items = []) { + return [headers, items] ; +} -/***/ 48481: -/***/ ((module) => { +/** + * Add an item to an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. + */ +function addItemToEnvelope(envelope, newItem) { + const [headers, items] = envelope; + return [headers, [...items, newItem]] ; +} -/* - * Copyright 2001-2010 Georges Menie (www.menie.org) - * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) - * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) - * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the University of California, Berkeley nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. +/** + * Convenience function to loop through the items and item types of an envelope. + * (This function was mostly created because working with envelope types is painful at the moment) * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * If the callback returns true, the rest of the items will be skipped. */ +function forEachEnvelopeItem( + envelope, + callback, +) { + const envelopeItems = envelope[1]; -/* CRC16 implementation according to CCITT standards. - * - * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the - * following parameters: - * - * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" - * Width : 16 bit - * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) - * Initialization : 0000 - * Reflect Input byte : False - * Reflect Output CRC : False - * Xor constant to output CRC : 0000 - * Output for "123456789" : 31C3 + for (const envelopeItem of envelopeItems) { + const envelopeItemType = envelopeItem[0].type; + const result = callback(envelopeItem, envelopeItemType); + + if (result) { + return true; + } + } + + return false; +} + +/** + * Returns true if the envelope contains any of the given envelope item types */ +function envelopeContainsItemType(envelope, types) { + return forEachEnvelopeItem(envelope, (_, type) => types.includes(type)); +} -var lookup = [ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -]; +/** + * Encode a string to UTF8. + */ +function encodeUTF8(input, textEncoder) { + const utf8 = textEncoder || new TextEncoder(); + return utf8.encode(input); +} /** - * Convert a string to a UTF8 array - faster than via buffer - * @param str - * @returns {Array} + * Serializes an envelope. */ -var toUTF8Array = function toUTF8Array(str) { - var char; - var i = 0; - var p = 0; - var utf8 = []; - var len = str.length; +function serializeEnvelope(envelope, textEncoder) { + const [envHeaders, items] = envelope; - for (; i < len; i++) { - char = str.charCodeAt(i); - if (char < 128) { - utf8[p++] = char; - } else if (char < 2048) { - utf8[p++] = (char >> 6) | 192; - utf8[p++] = (char & 63) | 128; - } else if ( - ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && - ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { - char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); - utf8[p++] = (char >> 18) | 240; - utf8[p++] = ((char >> 12) & 63) | 128; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; + // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data + let parts = JSON.stringify(envHeaders); + + function append(next) { + if (typeof parts === 'string') { + parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; } else { - utf8[p++] = (char >> 12) | 224; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; + parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); } } - return utf8; -}; + for (const item of items) { + const [itemHeaders, payload] = item; -/** - * Convert a string into a redis slot hash. - * @param str - * @returns {number} - */ -var generate = module.exports = function generate(str) { - var char; - var i = 0; - var start = -1; - var result = 0; - var resultHash = 0; - var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; - var len = utf8.length; + append(`\n${JSON.stringify(itemHeaders)}\n`); - while (i < len) { - char = utf8[i++]; - if (start === -1) { - if (char === 0x7B) { - start = i; + if (typeof payload === 'string' || payload instanceof Uint8Array) { + append(payload); + } else { + let stringifiedPayload; + try { + stringifiedPayload = JSON.stringify(payload); + } catch (e) { + // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still + // fails, we try again after normalizing it again with infinite normalization depth. This of course has a + // performance impact but in this case a performance hit is better than throwing. + stringifiedPayload = JSON.stringify(normalize.normalize(payload)); } - } else if (char !== 0x7D) { - resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); - } else if (i - 1 !== start) { - return resultHash & 0x3FFF; + append(stringifiedPayload); } + } - result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + return typeof parts === 'string' ? parts : concatBuffers(parts); +} + +function concatBuffers(buffers) { + const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); + + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const buffer of buffers) { + merged.set(buffer, offset); + offset += buffer.length; } - return result & 0x3FFF; -}; + return merged; +} /** - * Convert an array of multiple strings into a redis slot hash. - * Returns -1 if one of the keys is not for the same slot as the others - * @param keys - * @returns {number} + * Parses an envelope */ -module.exports.generateMulti = function generateMulti(keys) { - var i = 1; - var len = keys.length; - var base = generate(keys[0]); +function parseEnvelope( + env, + textEncoder, + textDecoder, +) { + let buffer = typeof env === 'string' ? textEncoder.encode(env) : env; - while (i < len) { - if (generate(keys[i++]) !== base) return -1; + function readBinary(length) { + const bin = buffer.subarray(0, length); + // Replace the buffer with the remaining data excluding trailing newline + buffer = buffer.subarray(length + 1); + return bin; } - return base; -}; + function readJson() { + let i = buffer.indexOf(0xa); + // If we couldn't find a newline, we must have found the end of the buffer + if (i < 0) { + i = buffer.length; + } + return JSON.parse(textDecoder.decode(readBinary(i))) ; + } -/***/ }), + const envelopeHeader = readJson(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const items = []; -/***/ 61904: -/***/ ((module, exports, __nccwpck_require__) => { + while (buffer.length) { + const itemHeader = readJson(); + const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined; + + items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]); + } + + return [envelopeHeader, items]; +} /** - * Module dependencies. + * Creates attachment envelope items */ +function createAttachmentEnvelopeItem( + attachment, + textEncoder, +) { + const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; -const EventEmitter = (__nccwpck_require__(82361).EventEmitter); -const spawn = (__nccwpck_require__(32081).spawn); -const path = __nccwpck_require__(71017); -const fs = __nccwpck_require__(57147); + return [ + object.dropUndefinedKeys({ + type: 'attachment', + length: buffer.length, + filename: attachment.filename, + content_type: attachment.contentType, + attachment_type: attachment.attachmentType, + }), + buffer, + ]; +} -// @ts-check +const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { + session: 'session', + sessions: 'session', + attachment: 'attachment', + transaction: 'transaction', + event: 'error', + client_report: 'internal', + user_report: 'default', + profile: 'profile', + replay_event: 'replay', + replay_recording: 'replay', + check_in: 'monitor', + feedback: 'feedback', + span: 'span', + statsd: 'metric_bucket', +}; -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} description - * @api public - */ +/** + * Maps the type of an envelope item to a data category. + */ +function envelopeItemTypeToDataCategory(type) { + return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; +} - constructor(flags, description) { - this.flags = flags; - this.required = flags.includes('<'); // A value must be supplied when the option is specified. - this.optional = flags.includes('['); // A value is optional when the option is specified. - // variadic test ignores et al which might be used to describe custom splitting of single argument - this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. - this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. - const optionFlags = _parseOptionFlags(flags); - this.short = optionFlags.shortFlag; - this.long = optionFlags.longFlag; - this.negate = false; - if (this.long) { - this.negate = this.long.startsWith('--no-'); - } - this.description = description || ''; - this.defaultValue = undefined; +/** Extracts the minimal SDK info from the metadata or an events */ +function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { + if (!metadataOrEvent || !metadataOrEvent.sdk) { + return; } + const { name, version } = metadataOrEvent.sdk; + return { name, version }; +} - /** - * Return option name. - * - * @return {string} - * @api private - */ - - name() { - if (this.long) { - return this.long.replace(/^--/, ''); - } - return this.short.replace(/^-/, ''); +/** + * Creates event envelope headers, based on event, sdk info and tunnel + * Note: This function was extracted from the core package to make it available in Replay + */ +function createEventEnvelopeHeaders( + event, + sdkInfo, + tunnel, + dsn$1, +) { + const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; + return { + event_id: event.event_id , + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && dsn$1 && { dsn: dsn.dsnToString(dsn$1) }), + ...(dynamicSamplingContext && { + trace: object.dropUndefinedKeys({ ...dynamicSamplingContext }), + }), }; +} - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - * @api private - */ - - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - }; +exports.addItemToEnvelope = addItemToEnvelope; +exports.createAttachmentEnvelopeItem = createAttachmentEnvelopeItem; +exports.createEnvelope = createEnvelope; +exports.createEventEnvelopeHeaders = createEventEnvelopeHeaders; +exports.envelopeContainsItemType = envelopeContainsItemType; +exports.envelopeItemTypeToDataCategory = envelopeItemTypeToDataCategory; +exports.forEachEnvelopeItem = forEachEnvelopeItem; +exports.getSdkMetadataForEnvelopeHeader = getSdkMetadataForEnvelopeHeader; +exports.parseEnvelope = parseEnvelope; +exports.serializeEnvelope = serializeEnvelope; +//# sourceMappingURL=envelope.js.map - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @api private - */ - is(arg) { - return this.short === arg || this.long === arg; - }; -} +/***/ }), -/** - * CommanderError class - * @class - */ -class CommanderError extends Error { - /** - * Constructs the CommanderError class - * @param {number} exitCode suggested exit code which could be used with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @constructor - */ - constructor(exitCode, code, message) { - super(message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.code = code; - this.exitCode = exitCode; - this.nestedError = undefined; - } -} +/***/ 60202: +/***/ ((__unused_webpack_module, exports) => { -class Command extends EventEmitter { - /** - * Initialize a new `Command`. - * - * @param {string} [name] - * @api public - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); - constructor(name) { - super(); - this.commands = []; - this.options = []; - this.parent = null; - this._allowUnknownOption = false; - this._args = []; - this.rawArgs = null; - this._scriptPath = null; - this._name = name || ''; - this._optionValues = {}; - this._storeOptionsAsProperties = true; // backwards compatible by default - this._storeOptionsAsPropertiesCalled = false; - this._passCommandToAction = true; // backwards compatible by default - this._actionResults = []; - this._actionHandler = null; - this._executableHandler = false; - this._executableFile = null; // custom name for executable - this._defaultCommandName = null; - this._exitCallback = null; - this._aliases = []; - this._combineFlagAndOptionalValue = true; +/** An error emitted by Sentry SDKs and related utilities. */ +class SentryError extends Error { + /** Display name of this error instance. */ - this._hidden = false; - this._hasHelpOption = true; - this._helpFlags = '-h, --help'; - this._helpDescription = 'display help for command'; - this._helpShortFlag = '-h'; - this._helpLongFlag = '--help'; - this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false - this._helpCommandName = 'help'; - this._helpCommandnameAndArgs = 'help [command]'; - this._helpCommandDescription = 'display help for command'; + constructor( message, logLevel = 'warn') { + super(message);this.message = message; + this.name = new.target.prototype.constructor.name; + // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line + // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes + // instances of `SentryError` fail `obj instanceof SentryError` checks. + Object.setPrototypeOf(this, new.target.prototype); + this.logLevel = logLevel; } +} - /** - * Define a command. - * - * There are two styles of command: pay attention to where to put the description. - * - * Examples: - * - * // Command implemented using action handler (description is supplied separately to `.command`) - * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * - * // Command implemented using separate executable file (description is second parameter to `.command`) - * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); - * - * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) - * @param {Object} [execOpts] - configuration options (for executable) - * @return {Command} returns new command for action handler, or `this` for executable command - * @api public - */ +exports.SentryError = SentryError; +//# sourceMappingURL=error.js.map - command(nameAndArgs, actionOptsOrExecDesc, execOpts) { - let desc = actionOptsOrExecDesc; - let opts = execOpts; - if (typeof desc === 'object' && desc !== null) { - opts = desc; - desc = null; - } - opts = opts || {}; - const args = nameAndArgs.split(/ +/); - const cmd = this.createCommand(args.shift()); - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; - } - if (opts.isDefault) this._defaultCommandName = cmd._name; +/***/ }), - cmd._hidden = !!(opts.noHelp || opts.hidden); - cmd._hasHelpOption = this._hasHelpOption; - cmd._helpFlags = this._helpFlags; - cmd._helpDescription = this._helpDescription; - cmd._helpShortFlag = this._helpShortFlag; - cmd._helpLongFlag = this._helpLongFlag; - cmd._helpCommandName = this._helpCommandName; - cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; - cmd._helpCommandDescription = this._helpCommandDescription; - cmd._exitCallback = this._exitCallback; - cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; - cmd._passCommandToAction = this._passCommandToAction; - cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; +/***/ 38753: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - this.commands.push(cmd); - cmd._parseExpectedArgs(args); - cmd.parent = this; +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (desc) return this; - return cmd; - }; +const is = __nccwpck_require__(36958); +const misc = __nccwpck_require__(88642); +const normalize = __nccwpck_require__(6811); +const object = __nccwpck_require__(36941); - /** - * Factory routine to create a new unattached command. - * - * See .command() for creating an attached subcommand, which uses this routine to - * create the command. You can override createCommand to customise subcommands. - * - * @param {string} [name] - * @return {Command} new command - * @api public - */ +/** + * Extracts stack frames from the error.stack string + */ +function parseStackFrames(stackParser, error) { + return stackParser(error.stack || '', 1); +} - createCommand(name) { - return new Command(name); +/** + * Extracts stack frames from the error and builds a Sentry Exception + */ +function exceptionFromError(stackParser, error) { + const exception = { + type: error.name || error.constructor.name, + value: error.message, }; - /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. - * - * @param {Command} cmd - new subcommand - * @param {Object} [opts] - configuration options - * @return {Command} `this` command for chaining - * @api public - */ + const frames = parseStackFrames(stackParser, error); + if (frames.length) { + exception.stacktrace = { frames }; + } - addCommand(cmd, opts) { - if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); + return exception; +} - // To keep things simple, block automatic name generation for deeply nested executables. - // Fail fast and detect when adding rather than later when parsing. - function checkExplicitNames(commandArray) { - commandArray.forEach((cmd) => { - if (cmd._executableHandler && !cmd._executableFile) { - throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); - } - checkExplicitNames(cmd.commands); - }); +function getMessageForObject(exception) { + if ('name' in exception && typeof exception.name === 'string') { + let message = `'${exception.name}' captured as exception`; + + if ('message' in exception && typeof exception.message === 'string') { + message += ` with message '${exception.message}'`; } - checkExplicitNames(cmd.commands); - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation + return message; + } else if ('message' in exception && typeof exception.message === 'string') { + return exception.message; + } else { + // This will allow us to group events based on top-level keys + // which is much better than creating new group when any key/value change + return `Object captured as exception with keys: ${object.extractExceptionKeysForMessage( + exception , + )}`; + } +} - this.commands.push(cmd); - cmd.parent = this; - return this; +/** + * Builds and Event from a Exception + * + * TODO(v8): Remove getHub fallback + * @hidden + */ +function eventFromUnknownInput( + // eslint-disable-next-line deprecation/deprecation + getHubOrClient, + stackParser, + exception, + hint, +) { + const client = + typeof getHubOrClient === 'function' + ? // eslint-disable-next-line deprecation/deprecation + getHubOrClient().getClient() + : getHubOrClient; + + let ex = exception; + const providedMechanism = + hint && hint.data && (hint.data ).mechanism; + const mechanism = providedMechanism || { + handled: true, + type: 'generic', }; - /** - * Define argument syntax for the command. - * - * @api public - */ - - arguments(desc) { - return this._parseExpectedArgs(desc.split(/ +/)); - }; + let extras; - /** - * Override default decision whether to add implicit help command. - * - * addHelpCommand() // force on - * addHelpCommand(false); // force off - * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details - * - * @return {Command} `this` command for chaining - * @api public - */ + if (!is.isError(exception)) { + if (is.isPlainObject(exception)) { + const normalizeDepth = client && client.getOptions().normalizeDepth; + extras = { ['__serialized__']: normalize.normalizeToSize(exception , normalizeDepth) }; - addHelpCommand(enableOrNameAndArgs, description) { - if (enableOrNameAndArgs === false) { - this._hasImplicitHelpCommand = false; + const message = getMessageForObject(exception); + ex = (hint && hint.syntheticException) || new Error(message); + (ex ).message = message; } else { - this._hasImplicitHelpCommand = true; - if (typeof enableOrNameAndArgs === 'string') { - this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; - this._helpCommandnameAndArgs = enableOrNameAndArgs; - } - this._helpCommandDescription = description || this._helpCommandDescription; + // This handles when someone does: `throw "something awesome";` + // We use synthesized Error here so we can extract a (rough) stack trace. + ex = (hint && hint.syntheticException) || new Error(exception ); + (ex ).message = exception ; } - return this; + mechanism.synthetic = true; + } + + const event = { + exception: { + values: [exceptionFromError(stackParser, ex )], + }, }; - /** - * @return {boolean} - * @api private - */ + if (extras) { + event.extra = extras; + } - _lazyHasImplicitHelpCommand() { - if (this._hasImplicitHelpCommand === undefined) { - this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); - } - return this._hasImplicitHelpCommand; + misc.addExceptionTypeValue(event, undefined, undefined); + misc.addExceptionMechanism(event, mechanism); + + return { + ...event, + event_id: hint && hint.event_id, }; +} - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} `this` command for chaining - * @api private - */ +/** + * Builds and Event from a Message + * @hidden + */ +function eventFromMessage( + stackParser, + message, + // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + attachStacktrace, +) { + const event = { + event_id: hint && hint.event_id, + level, + }; - _parseExpectedArgs(args) { - if (!args.length) return; - args.forEach((arg) => { - const argDetails = { - required: false, - name: '', - variadic: false + if (attachStacktrace && hint && hint.syntheticException) { + const frames = parseStackFrames(stackParser, hint.syntheticException); + if (frames.length) { + event.exception = { + values: [ + { + value: message, + stacktrace: { frames }, + }, + ], }; + } + } - switch (arg[0]) { - case '<': - argDetails.required = true; - argDetails.name = arg.slice(1, -1); - break; - case '[': - argDetails.name = arg.slice(1, -1); - break; - } + if (is.isParameterizedString(message)) { + const { __sentry_template_string__, __sentry_template_values__ } = message; - if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { - argDetails.variadic = true; - argDetails.name = argDetails.name.slice(0, -3); - } - if (argDetails.name) { - this._args.push(argDetails); - } - }); - this._args.forEach((arg, i) => { - if (arg.variadic && i < this._args.length - 1) { - throw new Error(`only the last argument can be variadic '${arg.name}'`); - } - }); - return this; - }; + event.logentry = { + message: __sentry_template_string__, + params: __sentry_template_values__, + }; + return event; + } - /** - * Register callback to use as replacement for calling process.exit. - * - * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing - * @return {Command} `this` command for chaining - * @api public - */ + event.message = message; + return event; +} - exitOverride(fn) { - if (fn) { - this._exitCallback = fn; - } else { - this._exitCallback = (err) => { - if (err.code !== 'commander.executeSubCommandAsync') { - throw err; - } else { - // Async callback from spawn events, not useful to throw. - } - }; - } - return this; - }; +exports.eventFromMessage = eventFromMessage; +exports.eventFromUnknownInput = eventFromUnknownInput; +exports.exceptionFromError = exceptionFromError; +exports.parseStackFrames = parseStackFrames; +//# sourceMappingURL=eventbuilder.js.map - /** - * Call process.exit, and _exitCallback if defined. - * - * @param {number} exitCode exit code for using with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @return never - * @api private - */ - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. - } - process.exit(exitCode); - }; +/***/ }), - /** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} `this` command for chaining - * @api public - */ +/***/ 25304: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - action(fn) { - const listener = (args) => { - // The .action callback takes an extra parameter which is the command or options. - const expectedArgsCount = this._args.length; - const actionArgs = args.slice(0, expectedArgsCount); - if (this._passCommandToAction) { - actionArgs[expectedArgsCount] = this; - } else { - actionArgs[expectedArgsCount] = this.opts(); - } - // Add the extra arguments so available too. - if (args.length > expectedArgsCount) { - actionArgs.push(args.slice(expectedArgsCount)); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - const actionResult = fn.apply(this, actionArgs); - // Remember result in case it is async. Assume parseAsync getting called on root. - let rootCommand = this; - while (rootCommand.parent) { - rootCommand = rootCommand.parent; - } - rootCommand._actionResults.push(actionResult); - }; - this._actionHandler = listener; - return this; - }; +const aggregateErrors = __nccwpck_require__(36555); +const browser = __nccwpck_require__(83732); +const dsn = __nccwpck_require__(92269); +const error = __nccwpck_require__(60202); +const worldwide = __nccwpck_require__(35291); +const index = __nccwpck_require__(49352); +const is = __nccwpck_require__(36958); +const isBrowser = __nccwpck_require__(45268); +const logger = __nccwpck_require__(8758); +const memo = __nccwpck_require__(71200); +const misc = __nccwpck_require__(88642); +const node = __nccwpck_require__(6534); +const normalize = __nccwpck_require__(6811); +const object = __nccwpck_require__(36941); +const path = __nccwpck_require__(36753); +const promisebuffer = __nccwpck_require__(3067); +const requestdata = __nccwpck_require__(57269); +const severity = __nccwpck_require__(44781); +const stacktrace = __nccwpck_require__(92243); +const string = __nccwpck_require__(98439); +const supports = __nccwpck_require__(58746); +const syncpromise = __nccwpck_require__(23600); +const time = __nccwpck_require__(4907); +const tracing = __nccwpck_require__(77354); +const env = __nccwpck_require__(60995); +const envelope = __nccwpck_require__(20950); +const clientreport = __nccwpck_require__(46659); +const ratelimit = __nccwpck_require__(25773); +const baggage = __nccwpck_require__(41022); +const url = __nccwpck_require__(40825); +const userIntegrations = __nccwpck_require__(79110); +const cache = __nccwpck_require__(23758); +const eventbuilder = __nccwpck_require__(38753); +const anr = __nccwpck_require__(42939); +const lru = __nccwpck_require__(82317); +const _asyncNullishCoalesce = __nccwpck_require__(77124); +const _asyncOptionalChain = __nccwpck_require__(52013); +const _asyncOptionalChainDelete = __nccwpck_require__(73718); +const _nullishCoalesce = __nccwpck_require__(47378); +const _optionalChain = __nccwpck_require__(16151); +const _optionalChainDelete = __nccwpck_require__(78328); +const console = __nccwpck_require__(14805); +const dom = __nccwpck_require__(47880); +const xhr = __nccwpck_require__(82878); +const fetch = __nccwpck_require__(35760); +const history = __nccwpck_require__(8828); +const globalError = __nccwpck_require__(77879); +const globalUnhandledRejection = __nccwpck_require__(22535); +const _handlers = __nccwpck_require__(17404); +const nodeStackTrace = __nccwpck_require__(60851); +const escapeStringForRegex = __nccwpck_require__(78075); +const supportsHistory = __nccwpck_require__(42159); + + + +exports.applyAggregateErrorsToEvent = aggregateErrors.applyAggregateErrorsToEvent; +exports.getComponentName = browser.getComponentName; +exports.getDomElement = browser.getDomElement; +exports.getLocationHref = browser.getLocationHref; +exports.htmlTreeAsString = browser.htmlTreeAsString; +exports.dsnFromString = dsn.dsnFromString; +exports.dsnToString = dsn.dsnToString; +exports.makeDsn = dsn.makeDsn; +exports.SentryError = error.SentryError; +exports.GLOBAL_OBJ = worldwide.GLOBAL_OBJ; +exports.getGlobalObject = worldwide.getGlobalObject; +exports.getGlobalSingleton = worldwide.getGlobalSingleton; +exports.addInstrumentationHandler = index.addInstrumentationHandler; +exports.isDOMError = is.isDOMError; +exports.isDOMException = is.isDOMException; +exports.isElement = is.isElement; +exports.isError = is.isError; +exports.isErrorEvent = is.isErrorEvent; +exports.isEvent = is.isEvent; +exports.isInstanceOf = is.isInstanceOf; +exports.isNaN = is.isNaN; +exports.isParameterizedString = is.isParameterizedString; +exports.isPlainObject = is.isPlainObject; +exports.isPrimitive = is.isPrimitive; +exports.isRegExp = is.isRegExp; +exports.isString = is.isString; +exports.isSyntheticEvent = is.isSyntheticEvent; +exports.isThenable = is.isThenable; +exports.isVueViewModel = is.isVueViewModel; +exports.isBrowser = isBrowser.isBrowser; +exports.CONSOLE_LEVELS = logger.CONSOLE_LEVELS; +exports.consoleSandbox = logger.consoleSandbox; +exports.logger = logger.logger; +exports.originalConsoleMethods = logger.originalConsoleMethods; +exports.memoBuilder = memo.memoBuilder; +exports.addContextToFrame = misc.addContextToFrame; +exports.addExceptionMechanism = misc.addExceptionMechanism; +exports.addExceptionTypeValue = misc.addExceptionTypeValue; +exports.arrayify = misc.arrayify; +exports.checkOrSetAlreadyCaught = misc.checkOrSetAlreadyCaught; +exports.getEventDescription = misc.getEventDescription; +exports.parseSemver = misc.parseSemver; +exports.uuid4 = misc.uuid4; +exports.dynamicRequire = node.dynamicRequire; +exports.isNodeEnv = node.isNodeEnv; +exports.loadModule = node.loadModule; +exports.normalize = normalize.normalize; +exports.normalizeToSize = normalize.normalizeToSize; +exports.normalizeUrlToBase = normalize.normalizeUrlToBase; +exports.walk = normalize.walk; +exports.addNonEnumerableProperty = object.addNonEnumerableProperty; +exports.convertToPlainObject = object.convertToPlainObject; +exports.dropUndefinedKeys = object.dropUndefinedKeys; +exports.extractExceptionKeysForMessage = object.extractExceptionKeysForMessage; +exports.fill = object.fill; +exports.getOriginalFunction = object.getOriginalFunction; +exports.markFunctionWrapped = object.markFunctionWrapped; +exports.objectify = object.objectify; +exports.urlEncode = object.urlEncode; +exports.basename = path.basename; +exports.dirname = path.dirname; +exports.isAbsolute = path.isAbsolute; +exports.join = path.join; +exports.normalizePath = path.normalizePath; +exports.relative = path.relative; +exports.resolve = path.resolve; +exports.makePromiseBuffer = promisebuffer.makePromiseBuffer; +exports.DEFAULT_USER_INCLUDES = requestdata.DEFAULT_USER_INCLUDES; +exports.addRequestDataToEvent = requestdata.addRequestDataToEvent; +exports.addRequestDataToTransaction = requestdata.addRequestDataToTransaction; +exports.extractPathForTransaction = requestdata.extractPathForTransaction; +exports.extractRequestData = requestdata.extractRequestData; +exports.winterCGHeadersToDict = requestdata.winterCGHeadersToDict; +exports.winterCGRequestToRequestData = requestdata.winterCGRequestToRequestData; +exports.severityFromString = severity.severityFromString; +exports.severityLevelFromString = severity.severityLevelFromString; +exports.validSeverityLevels = severity.validSeverityLevels; +exports.createStackParser = stacktrace.createStackParser; +exports.getFunctionName = stacktrace.getFunctionName; +exports.nodeStackLineParser = stacktrace.nodeStackLineParser; +exports.stackParserFromStackParserOptions = stacktrace.stackParserFromStackParserOptions; +exports.stripSentryFramesAndReverse = stacktrace.stripSentryFramesAndReverse; +exports.isMatchingPattern = string.isMatchingPattern; +exports.safeJoin = string.safeJoin; +exports.snipLine = string.snipLine; +exports.stringMatchesSomePattern = string.stringMatchesSomePattern; +exports.truncate = string.truncate; +exports.isNativeFetch = supports.isNativeFetch; +exports.supportsDOMError = supports.supportsDOMError; +exports.supportsDOMException = supports.supportsDOMException; +exports.supportsErrorEvent = supports.supportsErrorEvent; +exports.supportsFetch = supports.supportsFetch; +exports.supportsNativeFetch = supports.supportsNativeFetch; +exports.supportsReferrerPolicy = supports.supportsReferrerPolicy; +exports.supportsReportingObserver = supports.supportsReportingObserver; +exports.SyncPromise = syncpromise.SyncPromise; +exports.rejectedSyncPromise = syncpromise.rejectedSyncPromise; +exports.resolvedSyncPromise = syncpromise.resolvedSyncPromise; +Object.defineProperty(exports, "_browserPerformanceTimeOriginMode", ({ + enumerable: true, + get: () => time._browserPerformanceTimeOriginMode +})); +exports.browserPerformanceTimeOrigin = time.browserPerformanceTimeOrigin; +exports.dateTimestampInSeconds = time.dateTimestampInSeconds; +exports.timestampInSeconds = time.timestampInSeconds; +exports.timestampWithMs = time.timestampWithMs; +exports.TRACEPARENT_REGEXP = tracing.TRACEPARENT_REGEXP; +exports.extractTraceparentData = tracing.extractTraceparentData; +exports.generateSentryTraceHeader = tracing.generateSentryTraceHeader; +exports.propagationContextFromHeaders = tracing.propagationContextFromHeaders; +exports.tracingContextFromHeaders = tracing.tracingContextFromHeaders; +exports.getSDKSource = env.getSDKSource; +exports.isBrowserBundle = env.isBrowserBundle; +exports.addItemToEnvelope = envelope.addItemToEnvelope; +exports.createAttachmentEnvelopeItem = envelope.createAttachmentEnvelopeItem; +exports.createEnvelope = envelope.createEnvelope; +exports.createEventEnvelopeHeaders = envelope.createEventEnvelopeHeaders; +exports.envelopeContainsItemType = envelope.envelopeContainsItemType; +exports.envelopeItemTypeToDataCategory = envelope.envelopeItemTypeToDataCategory; +exports.forEachEnvelopeItem = envelope.forEachEnvelopeItem; +exports.getSdkMetadataForEnvelopeHeader = envelope.getSdkMetadataForEnvelopeHeader; +exports.parseEnvelope = envelope.parseEnvelope; +exports.serializeEnvelope = envelope.serializeEnvelope; +exports.createClientReportEnvelope = clientreport.createClientReportEnvelope; +exports.DEFAULT_RETRY_AFTER = ratelimit.DEFAULT_RETRY_AFTER; +exports.disabledUntil = ratelimit.disabledUntil; +exports.isRateLimited = ratelimit.isRateLimited; +exports.parseRetryAfterHeader = ratelimit.parseRetryAfterHeader; +exports.updateRateLimits = ratelimit.updateRateLimits; +exports.BAGGAGE_HEADER_NAME = baggage.BAGGAGE_HEADER_NAME; +exports.MAX_BAGGAGE_STRING_LENGTH = baggage.MAX_BAGGAGE_STRING_LENGTH; +exports.SENTRY_BAGGAGE_KEY_PREFIX = baggage.SENTRY_BAGGAGE_KEY_PREFIX; +exports.SENTRY_BAGGAGE_KEY_PREFIX_REGEX = baggage.SENTRY_BAGGAGE_KEY_PREFIX_REGEX; +exports.baggageHeaderToDynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext; +exports.dynamicSamplingContextToSentryBaggageHeader = baggage.dynamicSamplingContextToSentryBaggageHeader; +exports.getNumberOfUrlSegments = url.getNumberOfUrlSegments; +exports.getSanitizedUrlString = url.getSanitizedUrlString; +exports.parseUrl = url.parseUrl; +exports.stripUrlQueryAndFragment = url.stripUrlQueryAndFragment; +exports.addOrUpdateIntegration = userIntegrations.addOrUpdateIntegration; +exports.makeFifoCache = cache.makeFifoCache; +exports.eventFromMessage = eventbuilder.eventFromMessage; +exports.eventFromUnknownInput = eventbuilder.eventFromUnknownInput; +exports.exceptionFromError = eventbuilder.exceptionFromError; +exports.parseStackFrames = eventbuilder.parseStackFrames; +exports.callFrameToStackFrame = anr.callFrameToStackFrame; +exports.watchdogTimer = anr.watchdogTimer; +exports.LRUMap = lru.LRUMap; +exports._asyncNullishCoalesce = _asyncNullishCoalesce._asyncNullishCoalesce; +exports._asyncOptionalChain = _asyncOptionalChain._asyncOptionalChain; +exports._asyncOptionalChainDelete = _asyncOptionalChainDelete._asyncOptionalChainDelete; +exports._nullishCoalesce = _nullishCoalesce._nullishCoalesce; +exports._optionalChain = _optionalChain._optionalChain; +exports._optionalChainDelete = _optionalChainDelete._optionalChainDelete; +exports.addConsoleInstrumentationHandler = console.addConsoleInstrumentationHandler; +exports.addClickKeypressInstrumentationHandler = dom.addClickKeypressInstrumentationHandler; +exports.SENTRY_XHR_DATA_KEY = xhr.SENTRY_XHR_DATA_KEY; +exports.addXhrInstrumentationHandler = xhr.addXhrInstrumentationHandler; +exports.addFetchInstrumentationHandler = fetch.addFetchInstrumentationHandler; +exports.addHistoryInstrumentationHandler = history.addHistoryInstrumentationHandler; +exports.addGlobalErrorInstrumentationHandler = globalError.addGlobalErrorInstrumentationHandler; +exports.addGlobalUnhandledRejectionInstrumentationHandler = globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler; +exports.resetInstrumentationHandlers = _handlers.resetInstrumentationHandlers; +exports.filenameIsInApp = nodeStackTrace.filenameIsInApp; +exports.escapeStringForRegex = escapeStringForRegex.escapeStringForRegex; +exports.supportsHistory = supportsHistory.supportsHistory; +//# sourceMappingURL=index.js.map - /** - * Internal routine to check whether there is a clash storing option value with a Command property. - * - * @param {Option} option - * @api private - */ - _checkForOptionNameClash(option) { - if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { - // Storing options safely, or user has been explicit and up to them. - return; - } - // User may override help, and hard to tell if worth warning. - if (option.name() === 'help') { - return; - } +/***/ }), - const commandProperty = this._getOptionValue(option.attributeName()); - if (commandProperty === undefined) { - // no clash - return; - } +/***/ 17404: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let foundClash = true; - if (option.negate) { - // It is ok if define foo before --no-foo. - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - foundClash = !this._findOption(positiveLongFlag); - } else if (option.long) { - const negativeLongFlag = option.long.replace(/^--/, '--no-'); - foundClash = !this._findOption(negativeLongFlag); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (foundClash) { - throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command -- call storeOptionsAsProperties(false) to store option values safely, -- or call storeOptionsAsProperties(true) to suppress this check, -- or change option name +const debugBuild = __nccwpck_require__(61782); +const logger = __nccwpck_require__(8758); +const stacktrace = __nccwpck_require__(92243); -Read more on https://git.io/JJc0W`); - } - }; +// We keep the handlers globally +const handlers = {}; +const instrumented = {}; - /** - * Internal implementation shared by .option() and .requiredOption() - * - * @param {Object} config - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api private - */ +/** Add a handler function. */ +function addHandler(type, handler) { + handlers[type] = handlers[type] || []; + (handlers[type] ).push(handler); +} - _optionEx(config, flags, description, fn, defaultValue) { - const option = new Option(flags, description); - const oname = option.name(); - const name = option.attributeName(); - option.mandatory = !!config.mandatory; +/** + * Reset all instrumentation handlers. + * This can be used by tests to ensure we have a clean slate of instrumentation handlers. + */ +function resetInstrumentationHandlers() { + Object.keys(handlers).forEach(key => { + handlers[key ] = undefined; + }); +} - this._checkForOptionNameClash(option); +/** Maybe run an instrumentation function, unless it was already called. */ +function maybeInstrument(type, instrumentFn) { + if (!instrumented[type]) { + instrumentFn(); + instrumented[type] = true; + } +} - // default as 3rd arg - if (typeof fn !== 'function') { - if (fn instanceof RegExp) { - // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. - // No longer documented in README, but still present for backwards compatibility. - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - } else { - defaultValue = fn; - fn = null; - } - } +/** Trigger handlers for a given instrumentation type. */ +function triggerHandlers(type, data) { + const typeHandlers = type && handlers[type]; + if (!typeHandlers) { + return; + } - // preassign default value for --no-*, [optional], , or plain flag if boolean value - if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { - // when --no-foo we make sure default is true, unless a --foo option is already defined - if (option.negate) { - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; - } - // preassign only if we have a default - if (defaultValue !== undefined) { - this._setOptionValue(name, defaultValue); - option.defaultValue = defaultValue; - } + for (const handler of typeHandlers) { + try { + handler(data); + } catch (e) { + debugBuild.DEBUG_BUILD && + logger.logger.error( + `Error while triggering instrumentation handler.\nType: ${type}\nName: ${stacktrace.getFunctionName(handler)}\nError:`, + e, + ); } + } +} - // register the option - this.options.push(option); +exports.addHandler = addHandler; +exports.maybeInstrument = maybeInstrument; +exports.resetInstrumentationHandlers = resetInstrumentationHandlers; +exports.triggerHandlers = triggerHandlers; +//# sourceMappingURL=_handlers.js.map - // when it's passed assign the value - // and conditionally invoke the callback - this.on('option:' + oname, (val) => { - const oldValue = this._getOptionValue(name); - // custom processing - if (val !== null && fn) { - val = fn(val, oldValue === undefined ? defaultValue : oldValue); - } else if (val !== null && option.variadic) { - if (oldValue === defaultValue || !Array.isArray(oldValue)) { - val = [val]; - } else { - val = oldValue.concat(val); - } - } +/***/ }), - // unassigned or boolean value - if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { - // if no value, negate false, and we have a default, then use it! - if (val == null) { - this._setOptionValue(name, option.negate - ? false - : defaultValue || true); - } else { - this._setOptionValue(name, val); - } - } else if (val !== null) { - // reassign - this._setOptionValue(name, option.negate ? false : val); - } - }); +/***/ 14805: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this; - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to undefined - * program.option('-p, --pepper', 'add pepper'); - * - * program.pepper - * // => undefined - * - * --pepper - * program.pepper - * // => true - * - * // simple boolean defaulting to true (unless non-negated option is also defined) - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api public - */ +const logger = __nccwpck_require__(8758); +const object = __nccwpck_require__(36941); +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - option(flags, description, fn, defaultValue) { - return this._optionEx({}, flags, description, fn, defaultValue); - }; +/** + * Add an instrumentation handler for when a console.xxx method is called. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addConsoleInstrumentationHandler(handler) { + const type = 'console'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentConsole); +} - /** - * Add a required option which must have a value after parsing. This usually means - * the option must be specified on the command line. (Otherwise the same as .option().) - * - * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. - * - * @param {string} flags - * @param {string} description - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - * @api public - */ +function instrumentConsole() { + if (!('console' in worldwide.GLOBAL_OBJ)) { + return; + } - requiredOption(flags, description, fn, defaultValue) { - return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); - }; + logger.CONSOLE_LEVELS.forEach(function (level) { + if (!(level in worldwide.GLOBAL_OBJ.console)) { + return; + } - /** - * Alter parsing of short flags with optional values. - * - * Examples: - * - * // for `.option('-f,--flag [value]'): - * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour - * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` - * - * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. - * @api public - */ - combineFlagAndOptionalValue(arg) { - this._combineFlagAndOptionalValue = (arg === undefined) || arg; - return this; - }; + object.fill(worldwide.GLOBAL_OBJ.console, level, function (originalConsoleMethod) { + logger.originalConsoleMethods[level] = originalConsoleMethod; - /** - * Allow unknown options on the command line. - * - * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown - * for unknown options. - * @api public - */ - allowUnknownOption(arg) { - this._allowUnknownOption = (arg === undefined) || arg; - return this; - }; + return function (...args) { + const handlerData = { args, level }; + _handlers.triggerHandlers('console', handlerData); - /** - * Whether to store option values as properties on command object, - * or store separately (specify false). In both cases the option values can be accessed using .opts(). - * - * @param {boolean} value - * @return {Command} `this` command for chaining - * @api public - */ + const log = logger.originalConsoleMethods[level]; + log && log.apply(worldwide.GLOBAL_OBJ.console, args); + }; + }); + }); +} - storeOptionsAsProperties(value) { - this._storeOptionsAsPropertiesCalled = true; - this._storeOptionsAsProperties = (value === undefined) || value; - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); - } - return this; - }; +exports.addConsoleInstrumentationHandler = addConsoleInstrumentationHandler; +//# sourceMappingURL=console.js.map - /** - * Whether to pass command to action handler, - * or just the options (specify false). - * - * @param {boolean} value - * @return {Command} `this` command for chaining - * @api public - */ - passCommandToAction(value) { - this._passCommandToAction = (value === undefined) || value; - return this; - }; +/***/ }), - /** - * Store option value - * - * @param {string} key - * @param {Object} value - * @api private - */ +/***/ 47880: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _setOptionValue(key, value) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * Retrieve option value - * - * @param {string} key - * @return {Object} value - * @api private - */ +const misc = __nccwpck_require__(88642); +const object = __nccwpck_require__(36941); +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - _getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; - } - return this._optionValues[key]; - }; +const WINDOW = worldwide.GLOBAL_OBJ ; +const DEBOUNCE_DURATION = 1000; - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * The default expectation is that the arguments are from node and have the application as argv[0] - * and the script being run in argv[1], with user parameters after that. - * - * Examples: - * - * program.parse(process.argv); - * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions - * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - optional, defaults to process.argv - * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron - * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' - * @return {Command} `this` command for chaining - * @api public - */ +let debounceTimerID; +let lastCapturedEventType; +let lastCapturedEventTargetId; - parse(argv, parseOptions) { - if (argv !== undefined && !Array.isArray(argv)) { - throw new Error('first parameter to parse must be array or undefined'); - } - parseOptions = parseOptions || {}; +/** + * Add an instrumentation handler for when a click or a keypress happens. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addClickKeypressInstrumentationHandler(handler) { + const type = 'dom'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentDOM); +} - // Default to using process.argv - if (argv === undefined) { - argv = process.argv; - // @ts-ignore - if (process.versions && process.versions.electron) { - parseOptions.from = 'electron'; - } - } - this.rawArgs = argv.slice(); +/** Exported for tests only. */ +function instrumentDOM() { + if (!WINDOW.document) { + return; + } - // make it a little easier for callers by supporting various argv conventions - let userArgs; - switch (parseOptions.from) { - case undefined: - case 'node': - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - break; - case 'electron': - // @ts-ignore - if (process.defaultApp) { - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - } else { - userArgs = argv.slice(1); - } - break; - case 'user': - userArgs = argv.slice(0); - break; - default: - throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); - } - if (!this._scriptPath && process.mainModule) { - this._scriptPath = process.mainModule.filename; + // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom + // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before + // we instrument `addEventListener` so that we don't end up attaching this handler twice. + const triggerDOMHandler = _handlers.triggerHandlers.bind(null, 'dom'); + const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); + WINDOW.document.addEventListener('click', globalDOMEventHandler, false); + WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false); + + // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled + // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That + // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler + // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still + // guaranteed to fire at least once.) + ['EventTarget', 'Node'].forEach((target) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const proto = (WINDOW )[target] && (WINDOW )[target].prototype; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { + return; } - // Guess name, used in usage in help. - this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); + object.fill(proto, 'addEventListener', function (originalAddEventListener) { + return function ( - // Let's go! - this._parseCommand([], userArgs); + type, + listener, + options, + ) { + if (type === 'click' || type == 'keypress') { + try { + const el = this ; + const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); + const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 }); + + if (!handlerForType.handler) { + const handler = makeDOMEventHandler(triggerDOMHandler); + handlerForType.handler = handler; + originalAddEventListener.call(this, type, handler, options); + } - return this; - }; + handlerForType.refCount++; + } catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. - * - * The default expectation is that the arguments are from node and have the application as argv[0] - * and the script being run in argv[1], with user parameters after that. - * - * Examples: - * - * program.parseAsync(process.argv); - * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions - * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - * @param {Object} [parseOptions] - * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' - * @return {Promise} - * @api public - */ + return originalAddEventListener.call(this, type, listener, options); + }; + }); - parseAsync(argv, parseOptions) { - this.parse(argv, parseOptions); - return Promise.all(this._actionResults).then(() => this); - }; + object.fill( + proto, + 'removeEventListener', + function (originalRemoveEventListener) { + return function ( - /** - * Execute a sub-command executable. - * - * @api private - */ + type, + listener, + options, + ) { + if (type === 'click' || type == 'keypress') { + try { + const el = this ; + const handlers = el.__sentry_instrumentation_handlers__ || {}; + const handlerForType = handlers[type]; + + if (handlerForType) { + handlerForType.refCount--; + // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. + if (handlerForType.refCount <= 0) { + originalRemoveEventListener.call(this, type, handlerForType.handler, options); + handlerForType.handler = undefined; + delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete + } - _executeSubCommand(subcommand, args) { - args = args.slice(); - let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. - const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; + // If there are no longer any custom handlers of any type on this element, cleanup everything. + if (Object.keys(handlers).length === 0) { + delete el.__sentry_instrumentation_handlers__; + } + } + } catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); + return originalRemoveEventListener.call(this, type, listener, options); + }; + }, + ); + }); +} - // Want the entry script as the reference for command name and directory for searching for other files. - let scriptPath = this._scriptPath; - // Fallback in case not set, due to how Command created or called. - if (!scriptPath && process.mainModule) { - scriptPath = process.mainModule.filename; - } +/** + * Check whether the event is similar to the last captured one. For example, two click events on the same button. + */ +function isSimilarToLastCapturedEvent(event) { + // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. + if (event.type !== lastCapturedEventType) { + return false; + } - let baseDir; - try { - const resolvedLink = fs.realpathSync(scriptPath); - baseDir = path.dirname(resolvedLink); - } catch (e) { - baseDir = '.'; // dummy, probably not going to find executable! + try { + // If both events have the same type, it's still possible that actions were performed on different targets. + // e.g. 2 clicks on different buttons. + if (!event.target || (event.target )._sentryId !== lastCapturedEventTargetId) { + return false; } + } catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + } - // name of the subcommand, like `pm-install` - let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; - if (subcommand._executableFile) { - bin = subcommand._executableFile; - } + // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ + // to which an event listener was attached), we treat them as the same action, as we want to capture + // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. + return true; +} - const localBin = path.join(baseDir, bin); - if (fs.existsSync(localBin)) { - // prefer local `./` to bin in the $PATH - bin = localBin; - } else { - // Look for source files. - sourceExt.forEach((ext) => { - if (fs.existsSync(`${localBin}${ext}`)) { - bin = `${localBin}${ext}`; - } - }); - } - launchWithNode = sourceExt.includes(path.extname(bin)); +/** + * Decide whether an event should be captured. + * @param event event to be captured + */ +function shouldSkipDOMEvent(eventType, target) { + // We are only interested in filtering `keypress` events for now. + if (eventType !== 'keypress') { + return false; + } - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); + if (!target || !target.tagName) { + return true; + } - proc = spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = spawn(bin, args, { stdio: 'inherit' }); - } - } else { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = spawn(process.execPath, args, { stdio: 'inherit' }); + // Only consider keypress events on actual input elements. This will disregard keypresses targeting body + // e.g.tabbing through elements, hotkeys, etc. + if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { + return false; + } + + return true; +} + +/** + * Wraps addEventListener to capture UI breadcrumbs + */ +function makeDOMEventHandler( + handler, + globalListener = false, +) { + return (event) => { + // It's possible this handler might trigger multiple times for the same + // event (e.g. event propagation through node ancestors). + // Ignore if we've already captured that event. + if (!event || event['_sentryCaptured']) { + return; } - const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; - signals.forEach((signal) => { - // @ts-ignore - process.on(signal, () => { - if (proc.killed === false && proc.exitCode === null) { - proc.kill(signal); - } - }); - }); + const target = getEventTarget(event); - // By default terminate process when spawned process terminates. - // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! - const exitCallback = this._exitCallback; - if (!exitCallback) { - proc.on('close', process.exit.bind(process)); - } else { - proc.on('close', () => { - exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); - }); + // We always want to skip _some_ events. + if (shouldSkipDOMEvent(event.type, target)) { + return; } - proc.on('error', (err) => { - // @ts-ignore - if (err.code === 'ENOENT') { - const executableMissing = `'${bin}' does not exist - - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - - if the default executable name is not suitable, use the executableFile option to supply a custom name`; - throw new Error(executableMissing); - // @ts-ignore - } else if (err.code === 'EACCES') { - throw new Error(`'${bin}' not executable`); - } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } - }); - // Store the reference to the child process - this.runningCommand = proc; - }; + // Mark event as "seen" + object.addNonEnumerableProperty(event, '_sentryCaptured', true); - /** - * @api private - */ - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this._helpAndError(); + if (target && !target._sentryId) { + // Add UUID to event target so we can identify if + object.addNonEnumerableProperty(target, '_sentryId', misc.uuid4()); + } - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - subCommand._parseCommand(operands, unknown); + const name = event.type === 'keypress' ? 'input' : event.type; + + // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons. + // If there is a last captured event, see if the new event is different enough to treat it as a unique one. + // If that's the case, emit the previous event and store locally the newly-captured DOM event. + if (!isSimilarToLastCapturedEvent(event)) { + const handlerData = { event, name, global: globalListener }; + handler(handlerData); + lastCapturedEventType = event.type; + lastCapturedEventTargetId = target ? target._sentryId : undefined; } + + // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. + clearTimeout(debounceTimerID); + debounceTimerID = WINDOW.setTimeout(() => { + lastCapturedEventTargetId = undefined; + lastCapturedEventType = undefined; + }, DEBOUNCE_DURATION); }; +} - /** - * Process arguments in context of this command. - * - * @api private - */ +function getEventTarget(event) { + try { + return event.target ; + } catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + return null; + } +} - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); +exports.addClickKeypressInstrumentationHandler = addClickKeypressInstrumentationHandler; +exports.instrumentDOM = instrumentDOM; +//# sourceMappingURL=dom.js.map - if (operands && this._findCommand(operands[0])) { - this._dispatchSubcommand(operands[0], operands.slice(1), unknown); - } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { - if (operands.length === 1) { - this.help(); - } else { - this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); - } - } else if (this._defaultCommandName) { - outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command - this._dispatchSubcommand(this._defaultCommandName, operands, unknown); - } else { - if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { - // probably missing subcommand and no handler, user needs help - this._helpAndError(); - } - outputHelpIfRequested(this, parsed.unknown); - this._checkForMissingMandatoryOptions(); - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } +/***/ }), - if (this._actionHandler) { - const args = this.args.slice(); - this._args.forEach((arg, i) => { - if (arg.required && args[i] == null) { - this.missingArgument(arg.name); - } else if (arg.variadic) { - args[i] = args.splice(i); - } - }); +/***/ 35760: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this._actionHandler(args); - this.emit('command:' + this.name(), operands, unknown); - } else if (operands.length) { - if (this._findCommand('*')) { - this._dispatchSubcommand('*', operands, unknown); - } else if (this.listenerCount('command:*')) { - this.emit('command:*', operands, unknown); - } else if (this.commands.length) { - this.unknownCommand(); - } - } else if (this.commands.length) { - // This command has subcommands and nothing hooked up at this level, so display help. - this._helpAndError(); - } else { - // fall through for caller to handle after calling .parse() - } - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * Find matching command. - * - * @api private - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); - }; +const object = __nccwpck_require__(36941); +const supports = __nccwpck_require__(58746); +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @api private - */ +/** + * Add an instrumentation handler for when a fetch request happens. + * The handler function is called once when the request starts and once when it ends, + * which can be identified by checking if it has an `endTimestamp`. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addFetchInstrumentationHandler(handler) { + const type = 'fetch'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentFetch); +} - _findOption(arg) { - return this.options.find(option => option.is(arg)); - }; +function instrumentFetch() { + if (!supports.supportsNativeFetch()) { + return; + } - /** - * Display an error message if a mandatory option does not have a value. - * Lazy calling after checking for help flags from leaf subcommand. - * - * @api private - */ + object.fill(worldwide.GLOBAL_OBJ, 'fetch', function (originalFetch) { + return function (...args) { + const { method, url } = parseFetchArgs(args); - _checkForMissingMandatoryOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - for (let cmd = this; cmd; cmd = cmd.parent) { - cmd.options.forEach((anOption) => { - if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { - cmd.missingMandatoryOptionValue(anOption); - } + const handlerData = { + args, + fetchData: { + method, + url, + }, + startTimestamp: Date.now(), + }; + + _handlers.triggerHandlers('fetch', { + ...handlerData, }); - } - }; - /** - * Parse options from `argv` removing known options, - * and return argv split into operands and unknown arguments. - * - * Examples: - * - * argv => operands, unknown - * --known kkk op => [op], [] - * op --known kkk => [op], [] - * sub --unknown uuu op => [sub], [--unknown uuu op] - * sub -- --unknown uuu op => [sub --unknown uuu op], [] - * - * @param {String[]} argv - * @return {{operands: String[], unknown: String[]}} - * @api public - */ + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalFetch.apply(worldwide.GLOBAL_OBJ, args).then( + (response) => { + const finishedHandlerData = { + ...handlerData, + endTimestamp: Date.now(), + response, + }; - parseOptions(argv) { - const operands = []; // operands, not options or values - const unknown = []; // first unknown option and remaining unknown args - let dest = operands; - const args = argv.slice(); + _handlers.triggerHandlers('fetch', finishedHandlerData); + return response; + }, + (error) => { + const erroredHandlerData = { + ...handlerData, + endTimestamp: Date.now(), + error, + }; - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; - } + _handlers.triggerHandlers('fetch', erroredHandlerData); + // NOTE: If you are a Sentry user, and you are seeing this stack frame, + // it means the sentry.javascript SDK caught an error invoking your application code. + // This is expected behavior and NOT indicative of a bug with sentry.javascript. + throw error; + }, + ); + }; + }); +} - // parse options - let activeVariadicOption = null; - while (args.length) { - const arg = args.shift(); +function hasProp(obj, prop) { + return !!obj && typeof obj === 'object' && !!(obj )[prop]; +} - // literal - if (arg === '--') { - if (dest === unknown) dest.push(arg); - dest.push(...args); - break; - } +function getUrlFromResource(resource) { + if (typeof resource === 'string') { + return resource; + } - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; + if (!resource) { + return ''; + } - if (maybeOption(arg)) { - const option = this._findOption(arg); - // recognised option, call listener to assign value with possible custom processing - if (option) { - if (option.required) { - const value = args.shift(); - if (value === undefined) this.optionMissingArgument(option); - this.emit(`option:${option.name()}`, value); - } else if (option.optional) { - let value = null; - // historical behaviour is optional value is following arg unless an option - if (args.length > 0 && !maybeOption(args[0])) { - value = args.shift(); - } - this.emit(`option:${option.name()}`, value); - } else { // boolean flag - this.emit(`option:${option.name()}`); - } - activeVariadicOption = option.variadic ? option : null; - continue; - } - } + if (hasProp(resource, 'url')) { + return resource.url; + } - // Look for combo options following single dash, eat first one if known. - if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { - const option = this._findOption(`-${arg[1]}`); - if (option) { - if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { - // option with value following in same argument - this.emit(`option:${option.name()}`, arg.slice(2)); - } else { - // boolean option, emit and put back remainder of arg for further processing - this.emit(`option:${option.name()}`); - args.unshift(`-${arg.slice(2)}`); - } - continue; - } - } + if (resource.toString) { + return resource.toString(); + } - // Look for known long flag with value, like --foo=bar - if (/^--[^=]+=/.test(arg)) { - const index = arg.indexOf('='); - const option = this._findOption(arg.slice(0, index)); - if (option && (option.required || option.optional)) { - this.emit(`option:${option.name()}`, arg.slice(index + 1)); - continue; - } - } + return ''; +} - // looks like an option but unknown, unknowns from here - if (arg.length > 1 && arg[0] === '-') { - dest = unknown; - } +/** + * Parses the fetch arguments to find the used Http method and the url of the request. + * Exported for tests only. + */ +function parseFetchArgs(fetchArgs) { + if (fetchArgs.length === 0) { + return { method: 'GET', url: '' }; + } - // add arg - dest.push(arg); - } + if (fetchArgs.length === 2) { + const [url, options] = fetchArgs ; - return { operands, unknown }; + return { + url: getUrlFromResource(url), + method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET', + }; + } + + const arg = fetchArgs[0]; + return { + url: getUrlFromResource(arg ), + method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET', }; +} - /** - * Return an object containing options as key-value pairs - * - * @return {Object} - * @api public - */ - opts() { - if (this._storeOptionsAsProperties) { - // Preserve original behaviour so backwards compatible when still using properties - const result = {}; - const len = this.options.length; +exports.addFetchInstrumentationHandler = addFetchInstrumentationHandler; +exports.parseFetchArgs = parseFetchArgs; +//# sourceMappingURL=fetch.js.map - for (let i = 0; i < len; i++) { - const key = this.options[i].attributeName(); - result[key] = key === this._versionOptionName ? this._version : this[key]; - } - return result; - } - return this._optionValues; - }; +/***/ }), - /** - * Argument `name` is missing. - * - * @param {string} name - * @api private - */ +/***/ 77879: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - console.error(message); - this._exit(1, 'commander.missingArgument', message); - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {Option} option - * @param {string} [flag] - * @api private - */ +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - optionMissingArgument(option, flag) { - let message; - if (flag) { - message = `error: option '${option.flags}' argument missing, got '${flag}'`; - } else { - message = `error: option '${option.flags}' argument missing`; - } - console.error(message); - this._exit(1, 'commander.optionMissingArgument', message); - }; +let _oldOnErrorHandler = null; - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @api private - */ +/** + * Add an instrumentation handler for when an error is captured by the global error handler. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addGlobalErrorInstrumentationHandler(handler) { + const type = 'error'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentError); +} - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - console.error(message); - this._exit(1, 'commander.missingMandatoryOptionValue', message); - }; +function instrumentError() { + _oldOnErrorHandler = worldwide.GLOBAL_OBJ.onerror; - /** - * Unknown option `flag`. - * - * @param {string} flag - * @api private - */ + worldwide.GLOBAL_OBJ.onerror = function ( + msg, + url, + line, + column, + error, + ) { + const handlerData = { + column, + error, + line, + msg, + url, + }; + _handlers.triggerHandlers('error', handlerData); - unknownOption(flag) { - if (this._allowUnknownOption) return; - const message = `error: unknown option '${flag}'`; - console.error(message); - this._exit(1, 'commander.unknownOption', message); + if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) { + // eslint-disable-next-line prefer-rest-params + return _oldOnErrorHandler.apply(this, arguments); + } + + return false; }; - /** - * Unknown command. - * - * @api private - */ + worldwide.GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; +} - unknownCommand() { - const partCommands = [this.name()]; - for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { - partCommands.unshift(parentCmd.name()); - } - const fullCommand = partCommands.join(' '); - const message = `error: unknown command '${this.args[0]}'.` + - (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); - console.error(message); - this._exit(1, 'commander.unknownCommand', message); - }; +exports.addGlobalErrorInstrumentationHandler = addGlobalErrorInstrumentationHandler; +//# sourceMappingURL=globalError.js.map - /** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * You can optionally supply the flags and description to override the defaults. - * - * @param {string} str - * @param {string} [flags] - * @param {string} [description] - * @return {this | string} `this` command for chaining, or version string if no arguments - * @api public - */ - version(str, flags, description) { - if (str === undefined) return this._version; - this._version = str; - flags = flags || '-V, --version'; - description = description || 'output the version number'; - const versionOption = new Option(flags, description); - this._versionOptionName = versionOption.attributeName(); - this.options.push(versionOption); - this.on('option:' + versionOption.name(), () => { - process.stdout.write(str + '\n'); - this._exit(0, 'commander.version', str); - }); - return this; - }; +/***/ }), - /** - * Set the description to `str`. - * - * @param {string} str - * @param {Object} [argsDescription] - * @return {string|Command} - * @api public - */ +/***/ 22535: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) return this._description; - this._description = str; - this._argsDescription = argsDescription; - return this; - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * Set an alias for the command. - * - * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. - * - * @param {string} [alias] - * @return {string|Command} - * @api public - */ +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility +let _oldOnUnhandledRejectionHandler = null; - let command = this; - if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { - // assume adding alias for last added executable subcommand, rather than this - command = this.commands[this.commands.length - 1]; - } +/** + * Add an instrumentation handler for when an unhandled promise rejection is captured. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addGlobalUnhandledRejectionInstrumentationHandler( + handler, +) { + const type = 'unhandledrejection'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentUnhandledRejection); +} - if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); +function instrumentUnhandledRejection() { + _oldOnUnhandledRejectionHandler = worldwide.GLOBAL_OBJ.onunhandledrejection; - command._aliases.push(alias); - return this; + worldwide.GLOBAL_OBJ.onunhandledrejection = function (e) { + const handlerData = e; + _handlers.triggerHandlers('unhandledrejection', handlerData); + + if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) { + // eslint-disable-next-line prefer-rest-params + return _oldOnUnhandledRejectionHandler.apply(this, arguments); + } + + return true; }; - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {string[]|Command} - * @api public - */ + worldwide.GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; +} - aliases(aliases) { - // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). - if (aliases === undefined) return this._aliases; +exports.addGlobalUnhandledRejectionInstrumentationHandler = addGlobalUnhandledRejectionInstrumentationHandler; +//# sourceMappingURL=globalUnhandledRejection.js.map - aliases.forEach((alias) => this.alias(alias)); - return this; - }; - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ +/***/ }), - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; +/***/ 8828: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const args = this._args.map((arg) => { - return humanReadableArgName(arg); - }); - return [].concat( - (this.options.length || this._hasHelpOption ? '[options]' : []), - (this.commands.length ? '[command]' : []), - (this._args.length ? args : []) - ).join(' '); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - this._usage = str; - return this; - }; +const object = __nccwpck_require__(36941); +__nccwpck_require__(61782); +__nccwpck_require__(8758); +const worldwide = __nccwpck_require__(35291); +const supportsHistory = __nccwpck_require__(42159); +const _handlers = __nccwpck_require__(17404); - /** - * Get or set the name of the command - * - * @param {string} [str] - * @return {String|Command} - * @api public - */ +const WINDOW = worldwide.GLOBAL_OBJ ; - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - }; +let lastHref; - /** - * Return prepared commands. - * - * @return {Array} - * @api private - */ +/** + * Add an instrumentation handler for when a fetch request happens. + * The handler function is called once when the request starts and once when it ends, + * which can be identified by checking if it has an `endTimestamp`. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addHistoryInstrumentationHandler(handler) { + const type = 'history'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentHistory); +} - prepareCommands() { - const commandDetails = this.commands.filter((cmd) => { - return !cmd._hidden; - }).map((cmd) => { - const args = cmd._args.map((arg) => { - return humanReadableArgName(arg); - }).join(' '); - - return [ - cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + - (args ? ' ' + args : ''), - cmd._description - ]; - }); +function instrumentHistory() { + if (!supportsHistory.supportsHistory()) { + return; + } - if (this._lazyHasImplicitHelpCommand()) { - commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); + const oldOnPopState = WINDOW.onpopstate; + WINDOW.onpopstate = function ( ...args) { + const to = WINDOW.location.href; + // keep track of the current URL state, as we always receive only the updated state + const from = lastHref; + lastHref = to; + const handlerData = { from, to }; + _handlers.triggerHandlers('history', handlerData); + if (oldOnPopState) { + // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. + // https://github.com/getsentry/sentry-javascript/issues/3344 + // https://github.com/bugsnag/bugsnag-js/issues/469 + try { + return oldOnPopState.apply(this, args); + } catch (_oO) { + // no-empty + } } - return commandDetails; }; - /** - * Return the largest command length. - * - * @return {number} - * @api private - */ + function historyReplacementFunction(originalHistoryFunction) { + return function ( ...args) { + const url = args.length > 2 ? args[2] : undefined; + if (url) { + // coerce to string (this is what pushState does) + const from = lastHref; + const to = String(url); + // keep track of the current URL state, as we always receive only the updated state + lastHref = to; + const handlerData = { from, to }; + _handlers.triggerHandlers('history', handlerData); + } + return originalHistoryFunction.apply(this, args); + }; + } - largestCommandLength() { - const commands = this.prepareCommands(); - return commands.reduce((max, command) => { - return Math.max(max, command[0].length); - }, 0); - }; + object.fill(WINDOW.history, 'pushState', historyReplacementFunction); + object.fill(WINDOW.history, 'replaceState', historyReplacementFunction); +} - /** - * Return the largest option length. - * - * @return {number} - * @api private - */ +exports.addHistoryInstrumentationHandler = addHistoryInstrumentationHandler; +//# sourceMappingURL=history.js.map - largestOptionLength() { - const options = [].slice.call(this.options); - options.push({ - flags: this._helpFlags - }); - return options.reduce((max, option) => { - return Math.max(max, option.flags.length); - }, 0); - }; +/***/ }), - /** - * Return the largest arg length. - * - * @return {number} - * @api private - */ +/***/ 49352: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - largestArgLength() { - return this._args.reduce((max, arg) => { - return Math.max(max, arg.name.length); - }, 0); - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - /** - * Return the pad width. - * - * @return {number} - * @api private - */ +const debugBuild = __nccwpck_require__(61782); +const logger = __nccwpck_require__(8758); +const console = __nccwpck_require__(14805); +const dom = __nccwpck_require__(47880); +const fetch = __nccwpck_require__(35760); +const globalError = __nccwpck_require__(77879); +const globalUnhandledRejection = __nccwpck_require__(22535); +const history = __nccwpck_require__(8828); +const xhr = __nccwpck_require__(82878); - padWidth() { - let width = this.largestOptionLength(); - if (this._argsDescription && this._args.length) { - if (this.largestArgLength() > width) { - width = this.largestArgLength(); - } - } +// TODO(v8): Consider moving this file (or at least parts of it) into the browser package. The registered handlers are mostly non-generic and we risk leaking runtime specific code into generic packages. - if (this.commands && this.commands.length) { - if (this.largestCommandLength() > width) { - width = this.largestCommandLength(); - } - } +/** + * Add handler that will be called when given type of instrumentation triggers. + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + * @deprecated Use the proper function per instrumentation type instead! + */ +function addInstrumentationHandler(type, callback) { + switch (type) { + case 'console': + return console.addConsoleInstrumentationHandler(callback); + case 'dom': + return dom.addClickKeypressInstrumentationHandler(callback); + case 'xhr': + return xhr.addXhrInstrumentationHandler(callback); + case 'fetch': + return fetch.addFetchInstrumentationHandler(callback); + case 'history': + return history.addHistoryInstrumentationHandler(callback); + case 'error': + return globalError.addGlobalErrorInstrumentationHandler(callback); + case 'unhandledrejection': + return globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler(callback); + default: + debugBuild.DEBUG_BUILD && logger.logger.warn('unknown instrumentation type:', type); + } +} - return width; - }; +exports.addConsoleInstrumentationHandler = console.addConsoleInstrumentationHandler; +exports.addClickKeypressInstrumentationHandler = dom.addClickKeypressInstrumentationHandler; +exports.addFetchInstrumentationHandler = fetch.addFetchInstrumentationHandler; +exports.addGlobalErrorInstrumentationHandler = globalError.addGlobalErrorInstrumentationHandler; +exports.addGlobalUnhandledRejectionInstrumentationHandler = globalUnhandledRejection.addGlobalUnhandledRejectionInstrumentationHandler; +exports.addHistoryInstrumentationHandler = history.addHistoryInstrumentationHandler; +exports.SENTRY_XHR_DATA_KEY = xhr.SENTRY_XHR_DATA_KEY; +exports.addXhrInstrumentationHandler = xhr.addXhrInstrumentationHandler; +exports.addInstrumentationHandler = addInstrumentationHandler; +//# sourceMappingURL=index.js.map - /** - * Return help for options. - * - * @return {string} - * @api private - */ - optionHelp() { - const width = this.padWidth(); - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 4; - function padOptionDetails(flags, description) { - return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); - }; +/***/ }), - // Explicit options (including version) - const help = this.options.map((option) => { - const fullDesc = option.description + - ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); - return padOptionDetails(option.flags, fullDesc); - }); +/***/ 82878: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Implicit help - const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); - const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); - if (showShortHelpFlag || showLongHelpFlag) { - let helpFlags = this._helpFlags; - if (!showShortHelpFlag) { - helpFlags = this._helpLongFlag; - } else if (!showLongHelpFlag) { - helpFlags = this._helpShortFlag; - } - help.push(padOptionDetails(helpFlags, this._helpDescription)); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return help.join('\n'); - }; +const is = __nccwpck_require__(36958); +const object = __nccwpck_require__(36941); +const worldwide = __nccwpck_require__(35291); +const _handlers = __nccwpck_require__(17404); - /** - * Return command help documentation. - * - * @return {string} - * @api private - */ +const WINDOW = worldwide.GLOBAL_OBJ ; - commandHelp() { - if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; +const SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__'; - const commands = this.prepareCommands(); - const width = this.padWidth(); +/** + * Add an instrumentation handler for when an XHR request happens. + * The handler function is called once when the request starts and once when it ends, + * which can be identified by checking if it has an `endTimestamp`. + * + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden + */ +function addXhrInstrumentationHandler(handler) { + const type = 'xhr'; + _handlers.addHandler(type, handler); + _handlers.maybeInstrument(type, instrumentXHR); +} - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 4; +/** Exported only for tests. */ +function instrumentXHR() { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (!(WINDOW ).XMLHttpRequest) { + return; + } - return [ - 'Commands:', - commands.map((cmd) => { - const desc = cmd[1] ? ' ' + cmd[1] : ''; - return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); - }).join('\n').replace(/^/gm, ' '), - '' - ].join('\n'); - }; + const xhrproto = XMLHttpRequest.prototype; - /** - * Return program help documentation. - * - * @return {string} - * @api public - */ + object.fill(xhrproto, 'open', function (originalOpen) { + return function ( ...args) { + const startTimestamp = Date.now(); - helpInformation() { - let desc = []; - if (this._description) { - desc = [ - this._description, - '' - ]; - - const argsDescription = this._argsDescription; - if (argsDescription && this._args.length) { - const width = this.padWidth(); - const columns = process.stdout.columns || 80; - const descriptionWidth = columns - width - 5; - desc.push('Arguments:'); - this._args.forEach((arg) => { - desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); - }); - desc.push(''); + // open() should always be called with two or more arguments + // But to be on the safe side, we actually validate this and bail out if we don't have a method & url + const method = is.isString(args[0]) ? args[0].toUpperCase() : undefined; + const url = parseUrl(args[1]); + + if (!method || !url) { + return originalOpen.apply(this, args); } - } - let cmdName = this._name; - if (this._aliases[0]) { - cmdName = cmdName + '|' + this._aliases[0]; - } - let parentCmdNames = ''; - for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { - parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; - } - const usage = [ - 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), - '' - ]; + this[SENTRY_XHR_DATA_KEY] = { + method, + url, + request_headers: {}, + }; - let cmds = []; - const commandHelp = this.commandHelp(); - if (commandHelp) cmds = [commandHelp]; + // if Sentry key appears in URL, don't capture it as a request + if (method === 'POST' && url.match(/sentry_key/)) { + this.__sentry_own_request__ = true; + } - let options = []; - if (this._hasHelpOption || this.options.length > 0) { - options = [ - 'Options:', - '' + this.optionHelp().replace(/^/gm, ' '), - '' - ]; - } + const onreadystatechangeHandler = () => { + // For whatever reason, this is not the same instance here as from the outer method + const xhrInfo = this[SENTRY_XHR_DATA_KEY]; - return usage - .concat(desc) - .concat(options) - .concat(cmds) - .join('\n'); - }; + if (!xhrInfo) { + return; + } - /** - * Output help information for this command. - * - * When listener(s) are available for the helpLongFlag - * those callbacks are invoked. - * - * @api public - */ + if (this.readyState === 4) { + try { + // touching statusCode in some platforms throws + // an exception + xhrInfo.status_code = this.status; + } catch (e) { + /* do nothing */ + } - outputHelp(cb) { - if (!cb) { - cb = (passthru) => { - return passthru; + const handlerData = { + args: [method, url], + endTimestamp: Date.now(), + startTimestamp, + xhr: this, + }; + _handlers.triggerHandlers('xhr', handlerData); + } }; - } - const cbOutput = cb(this.helpInformation()); - if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { - throw new Error('outputHelp callback must return a string or a Buffer'); - } - process.stdout.write(cbOutput); - this.emit(this._helpLongFlag); - }; - /** - * You can pass in flags and a description to override the help - * flags and help description for your command. Pass in false to - * disable the built-in help option. - * - * @param {string | boolean} [flags] - * @param {string} [description] - * @return {Command} `this` command for chaining - * @api public - */ + if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') { + object.fill(this, 'onreadystatechange', function (original) { + return function ( ...readyStateArgs) { + onreadystatechangeHandler(); + return original.apply(this, readyStateArgs); + }; + }); + } else { + this.addEventListener('readystatechange', onreadystatechangeHandler); + } - helpOption(flags, description) { - if (typeof flags === 'boolean') { - this._hasHelpOption = flags; - return this; - } - this._helpFlags = flags || this._helpFlags; - this._helpDescription = description || this._helpDescription; + // Intercepting `setRequestHeader` to access the request headers of XHR instance. + // This will only work for user/library defined headers, not for the default/browser-assigned headers. + // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`. + object.fill(this, 'setRequestHeader', function (original) { + return function ( ...setRequestHeaderArgs) { + const [header, value] = setRequestHeaderArgs; - const helpFlags = _parseOptionFlags(this._helpFlags); - this._helpShortFlag = helpFlags.shortFlag; - this._helpLongFlag = helpFlags.longFlag; + const xhrInfo = this[SENTRY_XHR_DATA_KEY]; - return this; - }; + if (xhrInfo && is.isString(header) && is.isString(value)) { + xhrInfo.request_headers[header.toLowerCase()] = value; + } - /** - * Output help information and exit. - * - * @param {Function} [cb] - * @api public - */ + return original.apply(this, setRequestHeaderArgs); + }; + }); - help(cb) { - this.outputHelp(cb); - // exitCode: preserving original behaviour which was calling process.exit() - // message: do not have all displayed text available so only passing placeholder. - this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); - }; + return originalOpen.apply(this, args); + }; + }); - /** - * Output help information and exit. Display for error situations. - * - * @api private - */ + object.fill(xhrproto, 'send', function (originalSend) { + return function ( ...args) { + const sentryXhrData = this[SENTRY_XHR_DATA_KEY]; - _helpAndError() { - this.outputHelp(); - // message: do not have all displayed text available so only passing placeholder. - this._exit(1, 'commander.help', '(outputHelp)'); - }; -}; + if (!sentryXhrData) { + return originalSend.apply(this, args); + } -/** - * Expose the root command. - */ + if (args[0] !== undefined) { + sentryXhrData.body = args[0]; + } -exports = module.exports = new Command(); -exports.program = exports; // More explicit access to global command. + const handlerData = { + args: [sentryXhrData.method, sentryXhrData.url], + startTimestamp: Date.now(), + xhr: this, + }; + _handlers.triggerHandlers('xhr', handlerData); -/** - * Expose classes - */ + return originalSend.apply(this, args); + }; + }); +} -exports.Command = Command; -exports.Option = Option; -exports.CommanderError = CommanderError; +function parseUrl(url) { + if (is.isString(url)) { + return url; + } -/** - * Camel-case the given `flag` - * - * @param {string} flag - * @return {string} - * @api private - */ + try { + // url can be a string or URL + // but since URL is not available in IE11, we do not check for it, + // but simply assume it is an URL and return `toString()` from it (which returns the full URL) + // If that fails, we just return undefined + return (url ).toString(); + } catch (e2) {} // eslint-disable-line no-empty -function camelcase(flag) { - return flag.split('-').reduce((str, word) => { - return str + word[0].toUpperCase() + word.slice(1); - }); + return undefined; } -/** - * Pad `str` to `width`. - * - * @param {string} str - * @param {number} width - * @return {string} - * @api private - */ +exports.SENTRY_XHR_DATA_KEY = SENTRY_XHR_DATA_KEY; +exports.addXhrInstrumentationHandler = addXhrInstrumentationHandler; +exports.instrumentXHR = instrumentXHR; +//# sourceMappingURL=xhr.js.map -function pad(str, width) { - const len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} + +/***/ }), + +/***/ 36958: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +// eslint-disable-next-line @typescript-eslint/unbound-method +const objectToString = Object.prototype.toString; /** - * Wraps the given string with line breaks at the specified width while breaking - * words and indenting every but the first line on the left. + * Checks whether given value's type is one of a few Error or Error-like + * {@link isError}. * - * @param {string} str - * @param {number} width - * @param {number} indent - * @return {string} - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ -function wrap(str, width, indent) { - const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); - const lines = str.match(regex) || []; - return lines.map((line, i) => { - if (line.slice(-1) === '\n') { - line = line.slice(0, line.length - 1); - } - return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); - }).join('\n'); +function isError(wat) { + switch (objectToString.call(wat)) { + case '[object Error]': + case '[object Exception]': + case '[object DOMException]': + return true; + default: + return isInstanceOf(wat, Error); + } } - /** - * Optionally wrap the given str to a max width of width characters per line - * while indenting with indent spaces. Do not wrap if insufficient width or - * string is manually formatted. + * Checks whether given value is an instance of the given built-in class. * - * @param {string} str - * @param {number} width - * @param {number} indent - * @return {string} - * @api private + * @param wat The value to be checked + * @param className + * @returns A boolean representing the result. */ -function optionalWrap(str, width, indent) { - // Detect manually wrapped and indented strings by searching for line breaks - // followed by multiple spaces/tabs. - if (str.match(/[\n]\s+/)) return str; - // Do not wrap to narrow columns (or can end up with a word per line). - const minWidth = 40; - if (width < minWidth) return str; - - return wrap(str, width, indent); +function isBuiltin(wat, className) { + return objectToString.call(wat) === `[object ${className}]`; } /** - * Output help information if help flags specified + * Checks whether given value's type is ErrorEvent + * {@link isErrorEvent}. * - * @param {Command} cmd - command to output help for - * @param {Array} args - array of options to search for help flags - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function outputHelpIfRequested(cmd, args) { - const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); - if (helpOption) { - cmd.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); - } +function isErrorEvent(wat) { + return isBuiltin(wat, 'ErrorEvent'); } /** - * Takes an argument and returns its human readable equivalent for help usage. + * Checks whether given value's type is DOMError + * {@link isDOMError}. * - * @param {Object} arg - * @return {string} - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function humanReadableArgName(arg) { - const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - - return arg.required - ? '<' + nameOutput + '>' - : '[' + nameOutput + ']'; +function isDOMError(wat) { + return isBuiltin(wat, 'DOMError'); } /** - * Parse the short and long flag out of something like '-m,--mixed ' + * Checks whether given value's type is DOMException + * {@link isDOMException}. * - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function _parseOptionFlags(flags) { - let shortFlag; - let longFlag; - // Use original very loose parsing to maintain backwards compatibility for now, - // which allowed for example unintended `-sw, --short-word` [sic]. - const flagParts = flags.split(/[ |,]+/); - if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); - longFlag = flagParts.shift(); - // Add support for lone short flag without significantly changing parsing! - if (!shortFlag && /^-[^-]$/.test(longFlag)) { - shortFlag = longFlag; - longFlag = undefined; - } - return { shortFlag, longFlag }; +function isDOMException(wat) { + return isBuiltin(wat, 'DOMException'); } /** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * Checks whether given value's type is a string + * {@link isString}. * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function incrementNodeInspectorPort(args) { - // Testing for these options: - // --inspect[=[host:]port] - // --inspect-brk[=[host:]port] - // --inspect-port=[host:]port - return args.map((arg) => { - if (!arg.startsWith('--inspect')) { - return arg; - } - let debugOption; - let debugHost = '127.0.0.1'; - let debugPort = '9229'; - let match; - if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { - // e.g. --inspect - debugOption = match[1]; - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { - debugOption = match[1]; - if (/^\d+$/.test(match[3])) { - // e.g. --inspect=1234 - debugPort = match[3]; - } else { - // e.g. --inspect=localhost - debugHost = match[3]; - } - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { - // e.g. --inspect=localhost:1234 - debugOption = match[1]; - debugHost = match[3]; - debugPort = match[4]; - } - - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; - } - return arg; - }); +function isString(wat) { + return isBuiltin(wat, 'String'); } - -/***/ }), - -/***/ 86891: -/***/ ((module) => { - -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; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - - -/***/ }), - -/***/ 53921: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - - - /** - * Module exports. - * @public + * Checks whether given string is parameterized + * {@link isParameterizedString}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -module.exports = contentDisposition -module.exports.parse = parse +function isParameterizedString(wat) { + return ( + typeof wat === 'object' && + wat !== null && + '__sentry_template_string__' in wat && + '__sentry_template_values__' in wat + ); +} /** - * Module dependencies. - * @private + * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) + * {@link isPrimitive}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var basename = (__nccwpck_require__(71017).basename) -var Buffer = (__nccwpck_require__(21867).Buffer) +function isPrimitive(wat) { + return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function'); +} /** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private + * Checks whether given value's type is an object literal, or a class instance. + * {@link isPlainObject}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex +function isPlainObject(wat) { + return isBuiltin(wat, 'Object'); +} /** - * RegExp to match percent encoding escape. - * @private + * Checks whether given value's type is an Event instance + * {@link isEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g +function isEvent(wat) { + return typeof Event !== 'undefined' && isInstanceOf(wat, Event); +} /** - * RegExp to match non-latin1 characters. - * @private + * Checks whether given value's type is an Element instance + * {@link isElement}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g +function isElement(wat) { + return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +} /** - * RegExp to match quoted-pair in RFC 2616 + * Checks whether given value's type is an regexp + * {@link isRegExp}. * - * quoted-pair = "\" CHAR - * CHAR = - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex +function isRegExp(wat) { + return isBuiltin(wat, 'RegExp'); +} /** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private + * Checks whether given value has a then function. + * @param wat A value to be checked. */ - -var QUOTE_REGEXP = /([\\"])/g +function isThenable(wat) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return Boolean(wat && wat.then && typeof wat.then === 'function'); +} /** - * RegExp for various RFC 2616 grammar + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +} /** - * RegExp for various RFC 5987 grammar + * Checks whether given value is NaN + * {@link isNaN}. * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ +function isNaN(wat) { + return typeof wat === 'number' && wat !== wat; +} /** - * RegExp for various RFC 6266 grammar + * Checks whether given value's type is an instance of provided constructor. + * {@link isInstanceOf}. * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private + * @param wat A value to be checked. + * @param base A constructor to be used in a check. + * @returns A boolean representing the result. */ - -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } catch (_e) { + return false; + } +} /** - * Create an attachment Content-Disposition header. + * Checks whether given value's type is a Vue ViewModel. * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public + * @param wat A value to be checked. + * @returns A boolean representing the result. */ +function isVueViewModel(wat) { + // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property. + return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue)); +} -function contentDisposition (filename, options) { - var opts = options || {} +exports.isDOMError = isDOMError; +exports.isDOMException = isDOMException; +exports.isElement = isElement; +exports.isError = isError; +exports.isErrorEvent = isErrorEvent; +exports.isEvent = isEvent; +exports.isInstanceOf = isInstanceOf; +exports.isNaN = isNaN; +exports.isParameterizedString = isParameterizedString; +exports.isPlainObject = isPlainObject; +exports.isPrimitive = isPrimitive; +exports.isRegExp = isRegExp; +exports.isString = isString; +exports.isSyntheticEvent = isSyntheticEvent; +exports.isThenable = isThenable; +exports.isVueViewModel = isVueViewModel; +//# sourceMappingURL=is.js.map - // get type - var type = opts.type || 'attachment' - // get parameters - var params = createparams(filename, opts.fallback) +/***/ }), - // format into string - return format(new ContentDisposition(type, params)) -} +/***/ 45268: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const node = __nccwpck_require__(6534); +const worldwide = __nccwpck_require__(35291); /** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private + * Returns true if we are in the browser. */ +function isBrowser() { + // eslint-disable-next-line no-restricted-globals + return typeof window !== 'undefined' && (!node.isNodeEnv() || isElectronNodeRenderer()); +} -function createparams (filename, fallback) { - if (filename === undefined) { - return - } +// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them +function isElectronNodeRenderer() { + return ( + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + (worldwide.GLOBAL_OBJ ).process !== undefined && ((worldwide.GLOBAL_OBJ ).process ).type === 'renderer' + ); +} - var params = {} +exports.isBrowser = isBrowser; +//# sourceMappingURL=isBrowser.js.map - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } +/***/ }), - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } +/***/ 8758: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - // restrict to file base name - var name = basename(filename) +const debugBuild = __nccwpck_require__(61782); +const worldwide = __nccwpck_require__(35291); - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) +/** Prefix for logging strings */ +const PREFIX = 'Sentry Logger '; - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name +const CONSOLE_LEVELS = [ + 'debug', + 'info', + 'warn', + 'error', + 'log', + 'assert', + 'trace', +] ; - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } +/** This may be mutated by the console instrumentation. */ +const originalConsoleMethods - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } + = {}; - return params -} +/** JSDoc */ /** - * Format object to Content-Disposition header. + * Temporarily disable sentry console instrumentations. * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private + * @param callback The function to run against the original `console` messages + * @returns The results of the callback */ - -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') +function consoleSandbox(callback) { + if (!('console' in worldwide.GLOBAL_OBJ)) { + return callback(); } - // start with normalized type - var string = String(type).toLowerCase() - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + const console = worldwide.GLOBAL_OBJ.console ; + const wrappedFuncs = {}; - for (var i = 0; i < params.length; i++) { - param = params[i] + const wrappedLevels = Object.keys(originalConsoleMethods) ; - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + // Restore all wrapped console methods + wrappedLevels.forEach(level => { + const originalConsoleMethod = originalConsoleMethods[level] ; + wrappedFuncs[level] = console[level] ; + console[level] = originalConsoleMethod; + }); - string += '; ' + param + '=' + val - } + try { + return callback(); + } finally { + // Revert restoration to wrapped state + wrappedLevels.forEach(level => { + console[level] = wrappedFuncs[level] ; + }); } - - return string } -/** - * Decode a RFC 5987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ - -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) - - if (!match) { - throw new TypeError('invalid extended field value') - } - - var charset = match[1].toLowerCase() - var encoded = match[2] - var value - - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) +function makeLogger() { + let enabled = false; + const logger = { + enable: () => { + enabled = true; + }, + disable: () => { + enabled = false; + }, + isEnabled: () => enabled, + }; - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') + if (debugBuild.DEBUG_BUILD) { + CONSOLE_LEVELS.forEach(name => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + logger[name] = (...args) => { + if (enabled) { + consoleSandbox(() => { + worldwide.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); + }); + } + }; + }); + } else { + CONSOLE_LEVELS.forEach(name => { + logger[name] = () => undefined; + }); } - return value -} - -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ - -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') + return logger ; } -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ - -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } - - var match = DISPOSITION_TYPE_REGEXP.exec(string) - - if (!match) { - throw new TypeError('invalid type format') - } +const logger = makeLogger(); - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() +exports.CONSOLE_LEVELS = CONSOLE_LEVELS; +exports.consoleSandbox = consoleSandbox; +exports.logger = logger; +exports.originalConsoleMethods = originalConsoleMethods; +//# sourceMappingURL=logger.js.map - var key - var names = [] - var params = {} - var value - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index +/***/ }), - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } +/***/ 82317: +/***/ ((__unused_webpack_module, exports) => { - index += match[0].length - key = match[1].toLowerCase() - value = match[2] +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } +/** A simple Least Recently Used map */ +class LRUMap { - names.push(key) + constructor( _maxSize) {this._maxSize = _maxSize; + this._cache = new Map(); + } - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) + /** Get the current size of the cache */ + get size() { + return this._cache.size; + } - // overwrite existing value - params[key] = value - continue + /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */ + get(key) { + const value = this._cache.get(key); + if (value === undefined) { + return undefined; } + // Remove and re-insert to update the order + this._cache.delete(key); + this._cache.set(key, value); + return value; + } - if (typeof params[key] === 'string') { - continue + /** Insert an entry and evict an older entry if we've reached maxSize */ + set(key, value) { + if (this._cache.size >= this._maxSize) { + // keys() returns an iterator in insertion order so keys().next() gives us the oldest key + this._cache.delete(this._cache.keys().next().value); } + this._cache.set(key, value); + } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') + /** Remove an entry and return the entry if it was in the cache */ + remove(key) { + const value = this._cache.get(key); + if (value) { + this._cache.delete(key); } + return value; + } - params[key] = value + /** Clear all entries */ + clear() { + this._cache.clear(); } - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') + /** Get all the keys */ + keys() { + return Array.from(this._cache.keys()); } - return new ContentDisposition(type, params) + /** Get all the values */ + values() { + const values = []; + this._cache.forEach(value => values.push(value)); + return values; + } } -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ +exports.LRUMap = LRUMap; +//# sourceMappingURL=lru.js.map -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + +/***/ }), + +/***/ 71200: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-explicit-any */ /** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private + * Helper to decycle json objects */ +function memoBuilder() { + const hasWeakSet = typeof WeakSet === 'function'; + const inner = hasWeakSet ? new WeakSet() : []; + function memoize(obj) { + if (hasWeakSet) { + if (inner.has(obj)) { + return true; + } + inner.add(obj); + return false; + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < inner.length; i++) { + const value = inner[i]; + if (value === obj) { + return true; + } + } + inner.push(obj); + return false; + } -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() + function unmemoize(obj) { + if (hasWeakSet) { + inner.delete(obj); + } else { + for (let i = 0; i < inner.length; i++) { + if (inner[i] === obj) { + inner.splice(i, 1); + break; + } + } + } + } + return [memoize, unmemoize]; } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ +exports.memoBuilder = memoBuilder; +//# sourceMappingURL=memo.js.map -function qstring (val) { - var str = String(val) - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} +/***/ }), + +/***/ 88642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const object = __nccwpck_require__(36941); +const string = __nccwpck_require__(98439); +const worldwide = __nccwpck_require__(35291); /** - * Encode a Unicode string for HTTP (RFC 5987). + * UUID4 generator * - * @param {string} val - * @return {string} - * @private + * @returns string Generated UUID4. */ +function uuid4() { + const gbl = worldwide.GLOBAL_OBJ ; + const crypto = gbl.crypto || gbl.msCrypto; -function ustring (val) { - var str = String(val) + let getRandomByte = () => Math.random() * 16; + try { + if (crypto && crypto.randomUUID) { + return crypto.randomUUID().replace(/-/g, ''); + } + if (crypto && crypto.getRandomValues) { + getRandomByte = () => { + // crypto.getRandomValues might return undefined instead of the typed array + // in old Chromium versions (e.g. 23.0.1235.0 (151422)) + // However, `typedArray` is still filled in-place. + // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray + const typedArray = new Uint8Array(1); + crypto.getRandomValues(typedArray); + return typedArray[0]; + }; + } + } catch (_) { + // some runtimes can crash invoking crypto + // https://github.com/getsentry/sentry-javascript/issues/8935 + } - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 + // Concatenating the following numbers as strings results in '10000000100040008000100000000000' + return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => + // eslint-disable-next-line no-bitwise + ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), + ); +} - return 'UTF-8\'\'' + encoded +function getFirstException(event) { + return event.exception && event.exception.values ? event.exception.values[0] : undefined; } /** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor + * Extracts either message or type+value from an event that can be used for user-facing logs + * @returns event's description */ +function getEventDescription(event) { + const { message, event_id: eventId } = event; + if (message) { + return message; + } -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters + const firstException = getFirstException(event); + if (firstException) { + if (firstException.type && firstException.value) { + return `${firstException.type}: ${firstException.value}`; + } + return firstException.type || firstException.value || eventId || ''; + } + return eventId || ''; } - -/***/ }), - -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed +/** + * Adds exception values, type and value to an synthetic Exception. + * @param event The event to modify. + * @param value Value of the exception. + * @param type Type of the exception. + * @hidden */ - - +function addExceptionTypeValue(event, value, type) { + const exception = (event.exception = event.exception || {}); + const values = (exception.values = exception.values || []); + const firstException = (values[0] = values[0] || {}); + if (!firstException.value) { + firstException.value = value || ''; + } + if (!firstException.type) { + firstException.type = type || 'Error'; + } +} /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * @param event The event to modify. + * @param newMechanism Mechanism data to add to the event. + * @hidden */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ +function addExceptionMechanism(event, newMechanism) { + const firstException = getFirstException(event); + if (!firstException) { + return; + } + + const defaultMechanism = { type: 'generic', handled: true }; + const currentMechanism = firstException.mechanism; + firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; + + if (newMechanism && 'data' in newMechanism) { + const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; + firstException.mechanism.data = mergedData; + } +} + +// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +const SEMVER_REGEXP = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF + * Represents Semantic Versioning object */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g /** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + * Parses input into a SemVer interface + * @param input string representation of a semver version */ -var QUOTE_REGEXP = /([\\"])/g +function parseSemver(input) { + const match = input.match(SEMVER_REGEXP) || []; + const major = parseInt(match[1], 10); + const minor = parseInt(match[2], 10); + const patch = parseInt(match[3], 10); + return { + buildmetadata: match[5], + major: isNaN(major) ? undefined : major, + minor: isNaN(minor) ? undefined : minor, + patch: isNaN(patch) ? undefined : patch, + prerelease: match[4], + }; +} /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 + * This function adds context (pre/post/line) lines to the provided frame * - * media-type = type "/" subtype - * type = token - * subtype = token + * @param lines string[] containing all lines + * @param frame StackFrame that will be mutated + * @param linesOfContext number of context lines we want to add pre/post */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ +function addContextToFrame(lines, frame, linesOfContext = 5) { + // When there is no line number in the frame, attaching context is nonsensical and will even break grouping + if (frame.lineno === undefined) { + return; + } -/** - * Module exports. - * @public - */ + const maxLines = lines.length; + const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0); -exports.format = format -exports.parse = parse + frame.pre_context = lines + .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) + .map((line) => string.snipLine(line, 0)); + + frame.context_line = string.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); + + frame.post_context = lines + .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) + .map((line) => string.snipLine(line, 0)); +} /** - * Format object to media type. + * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object + * in question), and marks it captured if not. * - * @param {object} obj - * @return {string} - * @public + * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and + * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so + * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because + * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not + * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This + * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we + * see it. + * + * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on + * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent + * object wrapper forms so that this check will always work. However, because we need to flag the exact object which + * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification + * must be done before the exception captured. + * + * @param A thrown exception to check or flag as having been seen + * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) */ - -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') +function checkOrSetAlreadyCaught(exception) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (exception && (exception ).__sentry_captured__) { + return true; } - var parameters = obj.parameters - var type = obj.type - - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') + try { + // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the + // `ExtraErrorData` integration + object.addNonEnumerableProperty(exception , '__sentry_captured__', true); + } catch (err) { + // `exception` is a primitive, so we can't mark it seen } - var string = type + return false; +} - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() +/** + * Checks whether the given input is already an array, and if it isn't, wraps it in one. + * + * @param maybeArray Input to turn into an array, if necessary + * @returns The input, if already an array, or an array with the input as the only element, if not + */ +function arrayify(maybeArray) { + return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; +} - for (var i = 0; i < params.length; i++) { - param = params[i] +exports.addContextToFrame = addContextToFrame; +exports.addExceptionMechanism = addExceptionMechanism; +exports.addExceptionTypeValue = addExceptionTypeValue; +exports.arrayify = arrayify; +exports.checkOrSetAlreadyCaught = checkOrSetAlreadyCaught; +exports.getEventDescription = getEventDescription; +exports.parseSemver = parseSemver; +exports.uuid4 = uuid4; +//# sourceMappingURL=misc.js.map - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') - } - string += '; ' + param + '=' + qstring(parameters[param]) - } - } +/***/ }), - return string -} +/***/ 60851: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public + * Does this filename look like it's part of the app code? */ +function filenameIsInApp(filename, isNative = false) { + const isInternal = + isNative || + (filename && + // It's not internal if it's an absolute linux path + !filename.startsWith('/') && + // It's not internal if it's an absolute windows path + !filename.match(/^[A-Z]:/) && + // It's not internal if the path is starting with a dot + !filename.startsWith('.') && + // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack + !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//)); // Schema from: https://stackoverflow.com/a/3641782 -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } + return !isInternal && filename !== undefined && !filename.includes('node_modules/'); +} - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() +/** Node Stack line parser */ +// eslint-disable-next-line complexity +function node(getModule) { + const FILENAME_MATCH = /^\s*[-]{4,}$/; + const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; + + // eslint-disable-next-line complexity + return (line) => { + const lineMatch = line.match(FULL_MATCH); + + if (lineMatch) { + let object; + let method; + let functionName; + let typeName; + let methodName; + + if (lineMatch[1]) { + functionName = lineMatch[1]; - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } + let methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') { + methodStart--; + } - var obj = new ContentType(type.toLowerCase()) + if (methodStart > 0) { + object = functionName.slice(0, methodStart); + method = functionName.slice(methodStart + 1); + const objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.slice(objectEnd + 1); + object = object.slice(0, objectEnd); + } + } + typeName = undefined; + } - // parse parameters - if (index !== -1) { - var key - var match - var value + if (method) { + typeName = object; + methodName = method; + } - PARAM_REGEXP.lastIndex = index + if (method === '') { + methodName = undefined; + functionName = undefined; + } - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') + if (functionName === undefined) { + methodName = methodName || ''; + functionName = typeName ? `${typeName}.${methodName}` : methodName; } - index += match[0].length - key = match[1].toLowerCase() - value = match[2] + let filename = lineMatch[2] && lineMatch[2].startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2]; + const isNative = lineMatch[5] === 'native'; - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') + // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo` + if (filename && filename.match(/\/[A-Z]:/)) { + filename = filename.slice(1); } - obj.parameters[key] = value + if (!filename && lineMatch[5] && !isNative) { + filename = lineMatch[5]; + } + + return { + filename, + module: getModule ? getModule(filename) : undefined, + function: functionName, + lineno: parseInt(lineMatch[3], 10) || undefined, + colno: parseInt(lineMatch[4], 10) || undefined, + in_app: filenameIsInApp(filename, isNative), + }; } - if (index !== header.length) { - throw new TypeError('invalid parameter format') + if (line.match(FILENAME_MATCH)) { + return { + filename: line, + }; } - } - return obj + return undefined; + }; } -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ +exports.filenameIsInApp = filenameIsInApp; +exports.node = node; +//# sourceMappingURL=node-stack-trace.js.map -function getcontenttype (obj) { - var header - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } +/***/ }), - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } +/***/ 6534: +/***/ ((module, exports, __nccwpck_require__) => { - return header +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const env = __nccwpck_require__(60995); + +/** + * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, + * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + */ + +/** + * Checks whether we're in the Node.js or Browser environment + * + * @returns Answer to given question + */ +function isNodeEnv() { + // explicitly check for browser bundles as those can be optimized statically + // by terser/rollup. + return ( + !env.isBrowserBundle() && + Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' + ); } /** - * Quote a string if necessary. + * Requires a module which is protected against bundler minification. * - * @param {string} val - * @return {string} - * @private + * @param request The module path to resolve */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} -function qstring (val) { - var str = String(val) +/** + * Helper for dynamically loading module that should work with linked dependencies. + * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` + * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during + * build time. `require.resolve` is also not available in any other way, so we cannot create, + * a fake helper like we do with `dynamicRequire`. + * + * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. + * That is to mimic the behavior of `require.resolve` exactly. + * + * @param moduleName module name to require + * @returns possibly required module + */ +function loadModule(moduleName) { + let mod; - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str + try { + mod = dynamicRequire(module, moduleName); + } catch (e) { + // no-empty } - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') + try { + const { cwd } = dynamicRequire(module, 'process'); + mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; + } catch (e) { + // no-empty } - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' + return mod; } -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} +exports.dynamicRequire = dynamicRequire; +exports.isNodeEnv = isNodeEnv; +exports.loadModule = loadModule; +//# sourceMappingURL=node.js.map /***/ }), -/***/ 61579: +/***/ 6811: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Module dependencies. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -var crypto = __nccwpck_require__(6113); +const is = __nccwpck_require__(36958); +const memo = __nccwpck_require__(71200); +const object = __nccwpck_require__(36941); +const stacktrace = __nccwpck_require__(92243); /** - * Sign the given `val` with `secret`. + * Recursively normalizes the given object. * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private + * - Creates a copy to prevent original input mutation + * - Skips non-enumerable properties + * - When stringifying, calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format + * - Translates known global objects/classes to a string representations + * - Takes care of `Error` object serialization + * - Optionally limits depth of final output + * - Optionally limits number of properties/elements included in any single object/array + * + * @param input The object to be normalized. + * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) + * @param maxProperties The max number of elements or properties to be included in any single array or + * object in the normallized output. + * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function normalize(input, depth = 100, maxProperties = +Infinity) { + try { + // since we're at the outermost level, we don't provide a key + return visit('', input, depth, maxProperties); + } catch (err) { + return { ERROR: `**non-serializable** (${err})` }; + } +} -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; +/** JSDoc */ +function normalizeToSize( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object, + // Default Node.js REPL depth + depth = 3, + // 100kB, as 200kB is max payload size, so half sounds reasonable + maxSize = 100 * 1024, +) { + const normalized = normalize(object, depth); -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ + if (jsonSize(normalized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); + } -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; + return normalized ; +} /** - * Private + * Visits a node to perform normalization on it + * + * @param key The key corresponding to the given node + * @param value The node to be visited + * @param depth Optional number indicating the maximum recursion depth + * @param maxProperties Optional maximum number of properties/elements included in any single object/array + * @param memo Optional Memo class handling decycling */ +function visit( + key, + value, + depth = +Infinity, + maxProperties = +Infinity, + memo$1 = memo.memoBuilder(), +) { + const [memoize, unmemoize] = memo$1; -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} - + // Get the simple cases out of the way first + if ( + value == null || // this matches null and undefined -> eqeq not eqeqeq + (['number', 'boolean', 'string'].includes(typeof value) && !is.isNaN(value)) + ) { + return value ; + } -/***/ }), + const stringified = stringifyValue(key, value); -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { + // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. + // Everything else will have already been serialized, so if we don't see that pattern, we're done. + if (!stringified.startsWith('[object ')) { + return stringified; + } -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + // From here on, we can assert that `value` is either an object or an array. + // Do not normalize objects that we know have already been normalized. As a general rule, the + // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that + // have already been normalized. + if ((value )['__sentry_skip_normalization__']) { + return value ; + } + // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there + // We keep a certain amount of depth. + // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state. + const remainingDepth = + typeof (value )['__sentry_override_normalization_depth__'] === 'number' + ? ((value )['__sentry_override_normalization_depth__'] ) + : depth; -/** - * Module exports. - * @public - */ + // We're also done if we've reached the max depth + if (remainingDepth === 0) { + // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. + return stringified.replace('object ', ''); + } -exports.parse = parse; -exports.serialize = serialize; + // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. + if (memoize(value)) { + return '[Circular ~]'; + } -/** - * Module variables. - * @private - */ + // If the value has a `toJSON` method, we call it to extract more information + const valueWithToJSON = value ; + if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { + try { + const jsonValue = valueWithToJSON.toJSON(); + // We need to normalize the return value of `.toJSON()` in case it has circular references + return visit('', jsonValue, remainingDepth - 1, maxProperties, memo$1); + } catch (err) { + // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) + } + } -var decode = decodeURIComponent; -var encode = encodeURIComponent; + // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse + // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each + // property/entry, and keep track of the number of items we add to it. + const normalized = (Array.isArray(value) ? [] : {}) ; + let numAdded = 0; -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ + // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant + // properties are non-enumerable and otherwise would get missed. + const visitable = object.convertToPlainObject(value ); -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + for (const visitKey in visitable) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { + continue; + } -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ - -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(';') - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var index = pair.indexOf('=') - - // skip things that don't look like key=value - if (index < 0) { - continue; + if (numAdded >= maxProperties) { + normalized[visitKey] = '[MaxProperties ~]'; + break; } - var key = pair.substring(0, index).trim() - - // only assign once - if (undefined == obj[key]) { - var val = pair.substring(index + 1, pair.length).trim() - - // quoted values - if (val[0] === '"') { - val = val.slice(1, -1) - } + // Recursively visit all the child nodes + const visitValue = visitable[visitKey]; + normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo$1); - obj[key] = tryDecode(val, dec); - } + numAdded++; } - return obj; + // Once we've visited all the branches, remove the parent from memo storage + unmemoize(value); + + // Return accumulated values + return normalized; } +/* eslint-disable complexity */ /** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. + * Stringify the given value. Handles various known special values and types. * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" + * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn + * the number 1231 into "[Object Number]", nor on `null`, as it will throw. * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public + * @param value The value to stringify + * @returns A stringified representation of the given value */ +function stringifyValue( + key, + // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for + // our internal use, it'll do + value, +) { + try { + if (key === 'domain' && value && typeof value === 'object' && (value )._events) { + return '[Domain]'; + } -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } + // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first + // which won't throw if they are not present. - var value = enc(val); + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; + } - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } + // eslint-disable-next-line no-restricted-globals + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } - var str = name + '=' + value; + // eslint-disable-next-line no-restricted-globals + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; + if (is.isVueViewModel(value)) { + return '[VueViewModel]'; + } - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') + // React's SyntheticEvent thingy + if (is.isSyntheticEvent(value)) { + return '[SyntheticEvent]'; } - str += '; Max-Age=' + Math.floor(maxAge); - } + if (typeof value === 'number' && value !== value) { + return '[NaN]'; + } - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); + if (typeof value === 'function') { + return `[Function: ${stacktrace.getFunctionName(value)}]`; } - str += '; Domain=' + opt.domain; - } + if (typeof value === 'symbol') { + return `[${String(value)}]`; + } - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); + // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion + if (typeof value === 'bigint') { + return `[BigInt: ${String(value)}]`; } - str += '; Path=' + opt.path; - } + // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting + // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as + // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), + // we can make sure that only plain objects come out that way. + const objName = getConstructorName(value); - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + // Handle HTML Elements + if (/^HTML(\w*)Element$/.test(objName)) { + return `[HTMLElement: ${objName}]`; } - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; + return `[object ${objName}]`; + } catch (err) { + return `**non-serializable** (${err})`; } +} +/* eslint-enable complexity */ - if (opt.secure) { - str += '; Secure'; - } +function getConstructorName(value) { + const prototype = Object.getPrototypeOf(value); - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; + return prototype ? prototype.constructor.name : 'null prototype'; +} - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} - return str; +/** Calculates bytes size of input object */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); } /** - * Try decoding a string using a decoding function. + * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint + * across platforms and working directory. * - * @param {string} str - * @param {function} decode - * @private + * @param url The URL to be normalized. + * @param basePath The application base path. + * @returns The normalized URL. */ +function normalizeUrlToBase(url, basePath) { + const escapedBase = basePath + // Backslash to forward + .replace(/\\/g, '/') + // Escape RegExp special characters + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); -function tryDecode(str, decode) { + let newUrl = url; try { - return decode(str); - } catch (e) { - return str; + newUrl = decodeURI(url); + } catch (_Oo) { + // Sometime this breaks } + return ( + newUrl + .replace(/\\/g, '/') + .replace(/webpack:\/?/g, '') // Remove intermediate base path + // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor + .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///') + ); } +exports.normalize = normalize; +exports.normalizeToSize = normalizeToSize; +exports.normalizeUrlToBase = normalizeUrlToBase; +exports.walk = visit; +//# sourceMappingURL=normalize.js.map -/***/ }), - -/***/ 51512: -/***/ ((module, exports) => { - -"use strict"; -function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length { +/***/ 36941: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Helpers. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +const browser = __nccwpck_require__(83732); +const debugBuild = __nccwpck_require__(61782); +const is = __nccwpck_require__(36958); +const logger = __nccwpck_require__(8758); +const string = __nccwpck_require__(98439); /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Replace a method in an object with a wrapped version of itself. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param source An object that contains a method to be wrapped. + * @param name The name of the method to be wrapped. + * @param replacementFactory A higher-order function that takes the original version of the given method and returns a + * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to + * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. + * @returns void */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); +function fill(source, name, replacementFactory) { + if (!(name in source)) { + return; } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + const original = source[name] ; + const wrapped = replacementFactory(original) ; -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + markFunctionWrapped(wrapped, original); } + + source[name] = wrapped; } /** - * Short format for `ms`. + * Defines a non-enumerable property on the given object. * - * @param {Number} ms - * @return {String} - * @api private + * @param obj The object on which to set the property + * @param name The name of the property to be set + * @param value The value to which to set the property */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; +function addNonEnumerableProperty(obj, name, value) { + try { + Object.defineProperty(obj, name, { + // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it + value: value, + writable: true, + configurable: true, + }); + } catch (o_O) { + debugBuild.DEBUG_BUILD && logger.logger.log(`Failed to add non-enumerable property "${name}" to object`, obj); } - return ms + 'ms'; } /** - * Long format for `ms`. + * Remembers the original function on the wrapped function and + * patches up the prototype. * - * @param {Number} ms - * @return {String} - * @api private + * @param wrapped the wrapper function + * @param original the original function that gets wrapped */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; +function markFunctionWrapped(wrapped, original) { + try { + const proto = original.prototype || {}; + wrapped.prototype = original.prototype = proto; + addNonEnumerableProperty(wrapped, '__sentry_original__', original); + } catch (o_O) {} // eslint-disable-line no-empty } /** - * Pluralization helper. + * This extracts the original function if available. See + * `markFunctionWrapped` for more information. + * + * @param func the function to unwrap + * @returns the unwrapped version of the function if available. */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; +function getOriginalFunction(func) { + return func.__sentry_original__; } - -/***/ }), - -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { - /** - * This is the web browser implementation of `debug()`. + * Encodes given object into url-friendly format * - * Expose `debug()` as the module. + * @param object An object that contains serializable values + * @returns string Encoded */ - -exports = module.exports = __nccwpck_require__(18564); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); +function urlEncode(object) { + return Object.keys(object) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) + .join('&'); +} /** - * Colors. + * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their + * non-enumerable properties attached. + * + * @param value Initial source that we have to transform in order for it to be usable by the serializer + * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor + * an Error. */ +function convertToPlainObject( + value, +) -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + { + if (is.isError(value)) { + return { + message: value.message, + name: value.name, + stack: value.stack, + ...getOwnProperties(value), + }; + } else if (is.isEvent(value)) { + const newObj + + = { + type: value.type, + target: serializeEventTarget(value.target), + currentTarget: serializeEventTarget(value.currentTarget), + ...getOwnProperties(value), + }; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + if (typeof CustomEvent !== 'undefined' && is.isInstanceOf(value, CustomEvent)) { + newObj.detail = value.detail; + } -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; + return newObj; + } else { + return value; } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { +/** Creates a string representation of the target of an `Event` object */ +function serializeEventTarget(target) { try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; + return is.isElement(target) ? browser.htmlTreeAsString(target) : Object.prototype.toString.call(target); + } catch (_oO) { + return ''; } -}; +} +/** Filters out all but an object's own properties */ +function getOwnProperties(obj) { + if (typeof obj === 'object' && obj !== null) { + const extractedProps = {}; + for (const property in obj) { + if (Object.prototype.hasOwnProperty.call(obj, property)) { + extractedProps[property] = (obj )[property]; + } + } + return extractedProps; + } else { + return {}; + } +} /** - * Colorize log arguments if enabled. - * - * @api public + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` */ +function extractExceptionKeysForMessage(exception, maxLength = 40) { + const keys = Object.keys(convertToPlainObject(exception)); + keys.sort(); -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; + if (!keys.length) { + return '[object has no keys]'; + } - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (keys[0].length >= maxLength) { + return string.truncate(keys[0], maxLength); + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { + const serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; } - }); + if (includedKeys === keys.length) { + return serialized; + } + return string.truncate(serialized, maxLength); + } - args.splice(lastC, 0, c); + return ''; } /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". + * Given any object, return a new object having removed all fields whose value was `undefined`. + * Works recursively on objects and arrays. * - * @api public + * Attention: This function keeps circular references in the returned object. */ +function dropUndefinedKeys(inputValue) { + // This map keeps track of what already visited nodes map to. + // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular + // references as the input object. + const memoizationMap = new Map(); -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); + // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API + return _dropUndefinedKeys(inputValue, memoizationMap); } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +function _dropUndefinedKeys(inputValue, memoizationMap) { + if (isPojo(inputValue)) { + // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; + } -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; + const returnValue = {}; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); + + for (const key of Object.keys(inputValue)) { + if (typeof inputValue[key] !== 'undefined') { + returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); + } } - } catch(e) {} -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + return returnValue ; + } -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} + if (Array.isArray(inputValue)) { + // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; + } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; + const returnValue = []; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); + + inputValue.forEach((item) => { + returnValue.push(_dropUndefinedKeys(item, memoizationMap)); + }); + + return returnValue ; } - return r; + return inputValue; } -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +function isPojo(input) { + if (!is.isPlainObject(input)) { + return false; + } -exports.enable(load()); + try { + const name = (Object.getPrototypeOf(input) ).constructor.name; + return !name || name === 'Object'; + } catch (e) { + return true; + } +} /** - * Localstorage attempts to return the localstorage. + * Ensure that something is an object. * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper + * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. * - * @return {LocalStorage} - * @api private + * @param wat The subject of the objectification + * @returns A version of `wat` which can safely be used with `Object` class methods */ +function objectify(wat) { + let objectified; + switch (true) { + case wat === undefined || wat === null: + objectified = new String(wat); + break; -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - - -/***/ }), + // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason + // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as + // an object in order to wrap it. + case typeof wat === 'symbol' || typeof wat === 'bigint': + objectified = Object(wat); + break; -/***/ 18564: -/***/ ((module, exports, __nccwpck_require__) => { + // this will catch the remaining primitives: `String`, `Number`, and `Boolean` + case is.isPrimitive(wat): + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + objectified = new (wat ).constructor(wat); + break; + // by process of elimination, at this point we know that `wat` must already be an object + default: + objectified = wat; + break; + } + return objectified; +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(84697); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; +exports.addNonEnumerableProperty = addNonEnumerableProperty; +exports.convertToPlainObject = convertToPlainObject; +exports.dropUndefinedKeys = dropUndefinedKeys; +exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; +exports.fill = fill; +exports.getOriginalFunction = getOriginalFunction; +exports.markFunctionWrapped = markFunctionWrapped; +exports.objectify = objectify; +exports.urlEncode = urlEncode; +//# sourceMappingURL=object.js.map -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ -exports.formatters = {}; +/***/ }), -/** - * Previous log timestamp. - */ +/***/ 36753: +/***/ ((__unused_webpack_module, exports) => { -var prevTime; +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ +// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript +// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js +// +// 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. -function selectColor(namespace) { - var hash = 0, i; +/** JSDoc */ +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + let up = 0; + for (let i = parts.length - 1; i >= 0; i--) { + const last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } } - return exports.colors[Math.abs(hash) % exports.colors.length]; + return parts; } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +const splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/; +/** JSDoc */ +function splitPath(filename) { + // Truncate files names greater than 1024 characters to avoid regex dos + // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172 + const truncated = filename.length > 1024 ? `${filename.slice(-1024)}` : filename; + const parts = splitPathRe.exec(truncated); + return parts ? parts.slice(1) : []; +} - var self = debug; +// path.resolve([from ...], to) +// posix version +/** JSDoc */ +function resolve(...args) { + let resolvedPath = ''; + let resolvedAbsolute = false; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + // Skip empty entries + if (!path) { + continue; } - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charAt(0) === '/'; + } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + // Normalize the path + resolvedPath = normalizeArray( + resolvedPath.split('/').filter(p => !!p), + !resolvedAbsolute, + ).join('/'); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; +} - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); +/** JSDoc */ +function trim(arr) { + let start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') { + break; + } } - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); + let end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') { + break; + } } - return debug; + if (start > end) { + return []; + } + return arr.slice(start, end - start + 1); } -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); +// path.relative(from, to) +// posix version +/** JSDoc */ +function relative(from, to) { + /* eslint-disable no-param-reassign */ + from = resolve(from).slice(1); + to = resolve(to).slice(1); + /* eslint-enable no-param-reassign */ + + const fromParts = trim(from.split('/')); + const toParts = trim(to.split('/')); + + const length = Math.min(fromParts.length, toParts.length); + let samePartsLength = length; + for (let i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; } } -} -/** - * Disable debug output. - * - * @api public - */ + let outputParts = []; + for (let i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } -function disable() { - exports.enable(''); + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +// path.normalize(path) +// posix version +/** JSDoc */ +function normalizePath(path) { + const isPathAbsolute = isAbsolute(path); + const trailingSlash = path.slice(-1) === '/'; -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } + // Normalize the path + let normalizedPath = normalizeArray( + path.split('/').filter(p => !!p), + !isPathAbsolute, + ).join('/'); + + if (!normalizedPath && !isPathAbsolute) { + normalizedPath = '.'; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } + if (normalizedPath && trailingSlash) { + normalizedPath += '/'; } - return false; -} -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ + return (isPathAbsolute ? '/' : '') + normalizedPath; +} -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +// posix version +/** JSDoc */ +function isAbsolute(path) { + return path.charAt(0) === '/'; } +// posix version +/** JSDoc */ +function join(...args) { + return normalizePath(args.join('/')); +} -/***/ }), +/** JSDoc */ +function dirname(path) { + const result = splitPath(path); + const root = result[0]; + let dir = result[1]; -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.slice(0, dir.length - 1); + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); + return root + dir; } +/** JSDoc */ +function basename(path, ext) { + let f = splitPath(path)[2]; + if (ext && f.slice(ext.length * -1) === ext) { + f = f.slice(0, f.length - ext.length); + } + return f; +} -/***/ }), +exports.basename = basename; +exports.dirname = dirname; +exports.isAbsolute = isAbsolute; +exports.join = join; +exports.normalizePath = normalizePath; +exports.relative = relative; +exports.resolve = resolve; +//# sourceMappingURL=path.js.map -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { -/** - * Module dependencies. - */ +/***/ }), -var tty = __nccwpck_require__(76224); -var util = __nccwpck_require__(73837); +/***/ 3067: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -exports = module.exports = __nccwpck_require__(18564); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +const error = __nccwpck_require__(60202); +const syncpromise = __nccwpck_require__(23600); /** - * Colors. + * Creates an new PromiseBuffer object with the specified limit + * @param limit max number of promises that can be stored in the buffer */ +function makePromiseBuffer(limit) { + const buffer = []; -exports.colors = [6, 2, 3, 4, 5, 1]; + function isReady() { + return limit === undefined || buffer.length < limit; + } -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ + /** + * Remove a promise from the queue. + * + * @param task Can be any PromiseLike + * @returns Removed promise. + */ + function remove(task) { + return buffer.splice(buffer.indexOf(task), 1)[0]; + } -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + /** + * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. + * + * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: + * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor + * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By + * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer + * limit check. + * @returns The original promise. + */ + function add(taskProducer) { + if (!isReady()) { + return syncpromise.rejectedSyncPromise(new error.SentryError('Not adding Promise because buffer limit was reached.')); + } + + // start the task and add its promise to the queue + const task = taskProducer(); + if (buffer.indexOf(task) === -1) { + buffer.push(task); + } + void task + .then(() => remove(task)) + // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` + // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't + // have promises, so TS has to polyfill when down-compiling.) + .then(null, () => + remove(task).then(null, () => { + // We have to add another catch here because `remove()` starts a new promise chain. + }), + ); + return task; + } - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); + /** + * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or + * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to + * `true`. + * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and + * `false` otherwise + */ + function drain(timeout) { + return new syncpromise.SyncPromise((resolve, reject) => { + let counter = buffer.length; - obj[prop] = val; - return obj; -}, {}); + if (!counter) { + return resolve(true); + } -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + // wait for `timeout` ms and then resolve to `false` (if not cancelled first) + const capturedSetTimeout = setTimeout(() => { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + // if all promises resolve in time, cancel the timer and resolve to `true` + buffer.forEach(item => { + void syncpromise.resolvedSyncPromise(item).then(() => { + if (!--counter) { + clearTimeout(capturedSetTimeout); + resolve(true); + } + }, reject); + }); + }); + } -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() + return { + $: buffer, + add, + drain, + }; } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +exports.makePromiseBuffer = makePromiseBuffer; +//# sourceMappingURL=promisebuffer.js.map -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} +/***/ }), -/** - * Map %o to `util.inspect()`, all on a single line. - */ +/***/ 25773: +/***/ ((__unused_webpack_module, exports) => { -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ +// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds /** - * Adds ANSI color escape codes if enabled. + * Extracts Retry-After value from the request header or returns default value + * @param header string representation of 'Retry-After' header + * @param now current unix timestamp * - * @api public */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; +function parseRetryAfterHeader(header, now = Date.now()) { + const headerDelay = parseInt(`${header}`, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; } -} -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + const headerDate = Date.parse(`${header}`); + if (!isNaN(headerDate)) { + return headerDate - now; + } -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); + return DEFAULT_RETRY_AFTER; } /** - * Save `namespaces`. + * Gets the time that the given category is disabled until for rate limiting. + * In case no category-specific limit is set but a general rate limit across all categories is active, + * that time is returned. * - * @param {String} namespaces - * @api private + * @return the time in ms that the category is disabled until or 0 if there's no active rate limit. */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } +function disabledUntil(limits, dataCategory) { + return limits[dataCategory] || limits.all || 0; } /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Checks if a category is rate limited */ - -function load() { - return process.env.DEBUG; +function isRateLimited(limits, dataCategory, now = Date.now()) { + return disabledUntil(limits, dataCategory) > now; } /** - * Copied from `node/src/node.js`. + * Update ratelimits from incoming headers. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * @return the updated RateLimits object. */ +function updateRateLimits( + limits, + { statusCode, headers }, + now = Date.now(), +) { + const updatedRateLimits = { + ...limits, + }; -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + // "The name is case-insensitive." + // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get + const rateLimitHeader = headers && headers['x-sentry-rate-limits']; + const retryAfterHeader = headers && headers['retry-after']; - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); + if (rateLimitHeader) { + /** + * rate limit headers are of the form + *
,
,.. + * where each
is of the form + * : : : : + * where + * is a delay in seconds + * is the event type(s) (error, transaction, etc) being rate limited and is of the form + * ;;... + * is what's being limited (org, project, or key) - ignored by SDK + * is an arbitrary string like "org_quota" - ignored by SDK + * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected. + * Only present if rate limit applies to the metric_bucket data category. + */ + for (const limit of rateLimitHeader.trim().split(',')) { + const [retryAfter, categories, , , namespaces] = limit.split(':', 5); + const headerDelay = parseInt(retryAfter, 10); + const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default + if (!categories) { + updatedRateLimits.all = now + delay; + } else { + for (const category of categories.split(';')) { + if (category === 'metric_bucket') { + // namespaces will be present when category === 'metric_bucket' + if (!namespaces || namespaces.split(';').includes('custom')) { + updatedRateLimits[category] = now + delay; + } + } else { + updatedRateLimits[category] = now + delay; + } + } } - break; + } + } else if (retryAfterHeader) { + updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); + } else if (statusCode === 429) { + updatedRateLimits.all = now + 60 * 1000; + } - case 'FILE': - var fs = __nccwpck_require__(57147); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + return updatedRateLimits; +} - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(41808); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); +exports.DEFAULT_RETRY_AFTER = DEFAULT_RETRY_AFTER; +exports.disabledUntil = disabledUntil; +exports.isRateLimited = isRateLimited; +exports.parseRetryAfterHeader = parseRetryAfterHeader; +exports.updateRateLimits = updateRateLimits; +//# sourceMappingURL=ratelimit.js.map - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +/***/ }), - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } +/***/ 57269: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // For supporting legacy API we put the FD here. - stream.fd = fd; +Object.defineProperty(exports, "__esModule", ({ value: true })); - stream._isStdio = true; +const cookie = __nccwpck_require__(51244); +const debugBuild = __nccwpck_require__(61782); +const is = __nccwpck_require__(36958); +const logger = __nccwpck_require__(8758); +const normalize = __nccwpck_require__(6811); +const url = __nccwpck_require__(40825); - return stream; -} +const DEFAULT_INCLUDES = { + ip: false, + request: true, + transaction: true, + user: true, +}; +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; /** - * Init logic for `debug` instances. + * Sets parameterized route as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @deprecated This utility will be removed in v8. */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; +function addRequestDataToTransaction( + transaction, + req, + deps, +) { + if (!transaction) return; + // eslint-disable-next-line deprecation/deprecation + if (!transaction.metadata.source || transaction.metadata.source === 'url') { + // Attempt to grab a parameterized route off of the request + const [name, source] = extractPathForTransaction(req, { path: true, method: true }); + transaction.updateName(name); + // TODO: SEMANTIC_ATTRIBUTE_SENTRY_SOURCE is in core, align this once we merge utils & core + // eslint-disable-next-line deprecation/deprecation + transaction.setMetadata({ source }); + } + transaction.setAttribute('url', req.originalUrl || req.url); + if (req.baseUrl) { + transaction.setAttribute('baseUrl', req.baseUrl); } + // TODO: We need to rewrite this to a flat format? + // eslint-disable-next-line deprecation/deprecation + transaction.setData('query', extractQueryParams(req, deps)); } /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. + * + * Additionally, this function determines and returns the transaction name source + * + * eg. GET /mountpoint/user/:id + * + * @param req A request object + * @param options What to include in the transaction name (method, path, or a custom route name to be + * used instead of the request's route) + * + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */ +function extractPathForTransaction( + req, + options = {}, +) { + const method = req.method && req.method.toUpperCase(); -exports.enable(load()); + let path = ''; + let source = 'url'; + // Check to see if there's a parameterized route we can use (as there is in Express) + if (options.customRoute || req.route) { + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; + source = 'route'; + } -/***/ }), + // Otherwise, just take the original URL + else if (req.originalUrl || req.url) { + path = url.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); + } -/***/ 56323: -/***/ ((module) => { + let name = ''; + if (options.method && method) { + name += method; + } + if (options.method && options.path) { + name += ' '; + } + if (options.path && path) { + name += path; + } -"use strict"; + return [name, source]; +} +/** JSDoc */ +function extractTransaction(req, type) { + switch (type) { + case 'path': { + return extractPathForTransaction(req, { path: true })[0]; + } + case 'handler': { + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || ''; + } + case 'methodPath': + default: { + // if exist _reconstructedRoute return that path instead of route.path + const customRoute = req._reconstructedRoute ? req._reconstructedRoute : undefined; + return extractPathForTransaction(req, { path: true, method: true, customRoute })[0]; + } + } +} -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; +/** JSDoc */ +function extractUserData( + user -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} +, + keys, +) { + const extractedUser = {}; + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + attributes.forEach(key => { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) + return extractedUser; } -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; +/** + * Normalize data from the request object, accounting for framework differences. + * + * @param req The request object from which to extract data + * @param options.include An optional array of keys to include in the normalized data. Defaults to + * DEFAULT_REQUEST_INCLUDES if not provided. + * @param options.deps Injected, platform-specific dependencies + * @returns An object containing normalized request data + */ +function extractRequestData( + req, + options -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} +, +) { + const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const requestData = {}; + + // headers: + // node, express, koa, nextjs: req.headers + const headers = (req.headers || {}) + +; + // method: + // node, express, koa, nextjs: req.method + const method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + // Express 4 mistakenly strips off port number from req.host / req.hostname so we can't rely on them + // See: https://github.com/expressjs/express/issues/3047#issuecomment-236653223 + // Also: https://github.com/getsentry/sentry-javascript/issues/1917 + const host = headers.host || req.hostname || req.host || ''; + // protocol: + // node, nextjs: + // express, koa: req.protocol + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + const originalUrl = req.originalUrl || req.url || ''; + // absolute url + const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; + include.forEach(key => { + switch (key) { + case 'headers': { + requestData.headers = headers; + + // Remove the Cookie header in case cookie data should not be included in the event + if (!include.includes('cookies')) { + delete (requestData.headers ).cookie; + } -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + break; + } + case 'method': { + requestData.method = method; + break; + } + case 'url': { + requestData.url = absoluteUrl; + break; + } + case 'cookies': { + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies + requestData.cookies = + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can + // come off in v8 + req.cookies || (headers.cookie && cookie.parseCookie(headers.cookie)) || {}; + break; + } + case 'query_string': { + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = extractQueryParams(req, deps); + break; + } + case 'data': { + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = is.isString(req.body) ? req.body : JSON.stringify(normalize.normalize(req.body)); + } + break; + } + default: { + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = (req )[key]; + } + } + } + }); -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value + return requestData; } -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} +/** + * Add data from the given request to the given event + * + * @param event The event to which the request data will be added + * @param req Request object + * @param options.include Flags to control what data is included + * @param options.deps Injected platform-specific dependencies + * @returns The mutated `Event` object + */ +function addRequestDataToEvent( + event, + req, + options, +) { + const include = { + ...DEFAULT_INCLUDES, + ...(options && options.include), + }; -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + if (include.request) { + const extractedRequestData = Array.isArray(include.request) + ? extractRequestData(req, { include: include.request, deps: options && options.deps }) + : extractRequestData(req, { deps: options && options.deps }); -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] + event.request = { + ...event.request, + ...extractedRequestData, + }; + } + + if (include.user) { + const extractedUser = req.user && is.isPlainObject(req.user) ? extractUserData(req.user, include.user) : {}; + + if (Object.keys(extractedUser).length) { + event.user = { + ...event.user, + ...extractedUser, + }; + } + } + + // client ip: + // node, nextjs: req.socket.remoteAddress + // express, koa: req.ip + if (include.ip) { + const ip = req.ip || (req.socket && req.socket.remoteAddress); + if (ip) { + event.user = { + ...event.user, + ip_address: ip, + }; + } + } + + if (include.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, include.transaction); + } + + return event; } -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +function extractQueryParams( + req, + deps, +) { + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + let originalUrl = req.originalUrl || req.url || ''; + + if (!originalUrl) { + return; + } + + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. + if (originalUrl.startsWith('/')) { + originalUrl = `http://dogs.are.great${originalUrl}`; + } + + try { + return ( + req.query || + (typeof URL !== 'undefined' && new URL(originalUrl).search.slice(1)) || + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node + (deps && deps.url && deps.url.parse(originalUrl).query) || + undefined + ); + } catch (e2) { + return undefined; + } } -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } +/** + * Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict. + * The header keys will be lower case: e.g. A "Content-Type" header will be stored as "content-type". + */ +// TODO(v8): Make this function return undefined when the extraction fails. +function winterCGHeadersToDict(winterCGHeaders) { + const headers = {}; + try { + winterCGHeaders.forEach((value, key) => { + if (typeof value === 'string') { + // We check that value is a string even though it might be redundant to make sure prototype pollution is not possible. + headers[key] = value; + } + }); + } catch (e) { + debugBuild.DEBUG_BUILD && + logger.logger.warn('Sentry failed extracting headers from a request object. If you see this, please file an issue.'); + } + + return headers; } -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +/** + * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands. + */ +function winterCGRequestToRequestData(req) { + const headers = winterCGHeadersToDict(req.headers); + return { + method: req.method, + url: req.url, + headers, + }; } -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } +exports.DEFAULT_USER_INCLUDES = DEFAULT_USER_INCLUDES; +exports.addRequestDataToEvent = addRequestDataToEvent; +exports.addRequestDataToTransaction = addRequestDataToTransaction; +exports.extractPathForTransaction = extractPathForTransaction; +exports.extractRequestData = extractRequestData; +exports.winterCGHeadersToDict = winterCGHeadersToDict; +exports.winterCGRequestToRequestData = winterCGRequestToRequestData; +//# sourceMappingURL=requestdata.js.map - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination -} -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; +/***/ }), - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; +/***/ 44781: +/***/ ((__unused_webpack_module, exports) => { - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } -} +Object.defineProperty(exports, "__esModule", ({ value: true })); -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } +// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either +// +// a) moving `validSeverityLevels` to `@sentry/types`, +// b) moving the`SeverityLevel` type here, or +// c) importing `validSeverityLevels` from here into `@sentry/types`. +// +// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would +// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the +// type, reminding anyone who changes it to change this list also, will have to do. - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; +const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; -var deepmerge_1 = deepmerge; +/** + * Converts a string-based level into a member of the deprecated {@link Severity} enum. + * + * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. + * + * @param level String representation of Severity + * @returns Severity + */ +function severityFromString(level) { + return severityLevelFromString(level) ; +} -module.exports = deepmerge_1; +/** + * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. + * + * @param level String representation of desired `SeverityLevel`. + * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. + */ +function severityLevelFromString(level) { + return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; +} + +exports.severityFromString = severityFromString; +exports.severityLevelFromString = severityLevelFromString; +exports.validSeverityLevels = validSeverityLevels; +//# sourceMappingURL=severity.js.map /***/ }), -/***/ 42342: -/***/ ((module) => { +/***/ 92243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const nodeStackTrace = __nccwpck_require__(60851); + +const STACKTRACE_FRAME_LIMIT = 50; +// Used to sanitize webpack (error: *) wrapped stack errors +const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; +const STRIP_FRAME_REGEXP = /captureMessage|captureException/; /** - * Custom implementation of a double ended queue. + * Creates a stack parser with the supplied line parsers + * + * StackFrames are returned in the correct order for Sentry Exception + * frames and with Sentry SDK internal frames removed from the top and bottom + * */ -function Denque(array, options) { - var options = options || {}; +function createStackParser(...parsers) { + const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); - this._head = 0; - this._tail = 0; - this._capacity = options.capacity; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } + return (stack, skipFirst = 0) => { + const frames = []; + const lines = stack.split('\n'); + + for (let i = skipFirst; i < lines.length; i++) { + const line = lines[i]; + // Ignore lines over 1kb as they are unlikely to be stack frames. + // Many of the regular expressions use backtracking which results in run time that increases exponentially with + // input size. Huge strings can result in hangs/Denial of Service: + // https://github.com/getsentry/sentry-javascript/issues/2286 + if (line.length > 1024) { + continue; + } + + // https://github.com/getsentry/sentry-javascript/issues/5459 + // Remove webpack (error: *) wrappers + const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line; + + // https://github.com/getsentry/sentry-javascript/issues/7813 + // Skip Error: lines + if (cleanedLine.match(/\S*Error: /)) { + continue; + } + + for (const parser of sortedParsers) { + const frame = parser(cleanedLine); + + if (frame) { + frames.push(frame); + break; + } + } + + if (frames.length >= STACKTRACE_FRAME_LIMIT) { + break; + } + } + + return stripSentryFramesAndReverse(frames); + }; } /** - * ------------- - * PUBLIC API - * ------------- + * Gets a stack parser implementation from Options.stackParser + * @see Options + * + * If options contains an array of line parsers, it is converted into a parser */ +function stackParserFromStackParserOptions(stackParser) { + if (Array.isArray(stackParser)) { + return createStackParser(...stackParser); + } + return stackParser; +} /** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} + * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. + * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the + * function that caused the crash is the last frame in the array. + * @hidden */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; +function stripSentryFramesAndReverse(stack) { + if (!stack.length) { + return []; } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; + + const localStack = Array.from(stack); + + // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) + if (/sentryWrapped/.test(localStack[localStack.length - 1].function || '')) { + localStack.pop(); + } + + // Reversing in the middle of the procedure allows us to just pop the values off the stack + localStack.reverse(); + + // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) + if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) { + localStack.pop(); + + // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')` + // is produced within the hub itself, making it: + // + // Sentry.captureException() + // getCurrentHub().captureException() + // + // instead of just the top `Sentry` call itself. + // This forces us to possibly strip an additional frame in the exact same was as above. + if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || '')) { + localStack.pop(); + } + } + + return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({ + ...frame, + filename: frame.filename || localStack[localStack.length - 1].filename, + function: frame.function || '?', + })); +} + +const defaultFunctionName = ''; /** - * Alias for peekAt() - * @param i - * @returns {*} + * Safely extract function name from itself */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } +} /** - * Returns the first item in the list without removing it. - * @returns {*} + * Node.js stack line parser + * + * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. + * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; +function nodeStackLineParser(getModule) { + return [90, nodeStackTrace.node(getModule)]; +} + +exports.filenameIsInApp = nodeStackTrace.filenameIsInApp; +exports.createStackParser = createStackParser; +exports.getFunctionName = getFunctionName; +exports.nodeStackLineParser = nodeStackLineParser; +exports.stackParserFromStackParserOptions = stackParserFromStackParserOptions; +exports.stripSentryFramesAndReverse = stripSentryFramesAndReverse; +//# sourceMappingURL=stacktrace.js.map + + +/***/ }), + +/***/ 98439: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const is = __nccwpck_require__(36958); /** - * Alias for peek() - * @returns {*} + * Truncates given string to the maximum characters count + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string (0 = unlimited) + * @returns string Encoded */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; +function truncate(str, max = 0) { + if (typeof str !== 'string' || max === 0) { + return str; + } + return str.length <= max ? str : `${str.slice(0, max)}...`; +} /** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; +function snipLine(line, colno) { + let newLine = line; + const lineLength = newLine.length; + if (lineLength <= 150) { + return newLine; + } + if (colno > lineLength) { + // eslint-disable-next-line no-param-reassign + colno = lineLength; + } + + let start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } + + let end = Math.min(start + 140, lineLength); + if (end > lineLength - 5) { + end = lineLength; + } + if (end === lineLength) { + start = Math.max(end - 140, 0); + } + + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = `'{snip} ${newLine}`; + } + if (end < lineLength) { + newLine += ' {snip}'; + } + + return newLine; +} /** - * Returns the current length of the queue - * @return {Number} + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; } -}); + + const output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < input.length; i++) { + const value = input[i]; + try { + // This is a hack to fix a Vue3-specific bug that causes an infinite loop of + // console warnings. This happens when a Vue template is rendered with + // an undeclared variable, which we try to stringify, ultimately causing + // Vue to issue another warning which repeats indefinitely. + // see: https://github.com/getsentry/sentry-javascript/pull/8981 + if (is.isVueViewModel(value)) { + output.push('[VueViewModel]'); + } else { + output.push(String(value)); + } + } catch (e) { + output.push('[value cannot be serialized]'); + } + } + + return output.join(delimiter); +} /** - * Return the number of items on the list, or 0 if empty. - * @returns {number} + * Checks if the given value matches a regex or string + * + * @param value The string to test + * @param pattern Either a regex or a string against which `value` will be matched + * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match + * `pattern` if it contains `pattern`. Only applies to string-type patterns. */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; +function isMatchingPattern( + value, + pattern, + requireExactStringMatch = false, +) { + if (!is.isString(value)) { + return false; + } + + if (is.isRegExp(pattern)) { + return pattern.test(value); + } + if (is.isString(pattern)) { + return requireExactStringMatch ? value === pattern : value.includes(pattern); + } + + return false; +} /** - * Add an item at the beginning of the list. - * @param item + * Test the given string against an array of strings and regexes. By default, string matching is done on a + * substring-inclusion basis rather than a strict equality basis + * + * @param testString The string to test + * @param patterns The patterns against which to test the string + * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to + * count. If false, `testString` will match a string pattern if it contains that pattern. + * @returns */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._capacity && this.size() > this._capacity) this.pop(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; +function stringMatchesSomePattern( + testString, + patterns = [], + requireExactStringMatch = false, +) { + return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); +} + +exports.isMatchingPattern = isMatchingPattern; +exports.safeJoin = safeJoin; +exports.snipLine = snipLine; +exports.stringMatchesSomePattern = stringMatchesSomePattern; +exports.truncate = truncate; +//# sourceMappingURL=string.js.map + + +/***/ }), + +/***/ 58746: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const debugBuild = __nccwpck_require__(61782); +const logger = __nccwpck_require__(8758); +const worldwide = __nccwpck_require__(35291); + +// eslint-disable-next-line deprecation/deprecation +const WINDOW = worldwide.getGlobalObject(); /** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} + * Tells whether current environment supports ErrorEvent objects + * {@link supportsErrorEvent}. + * + * @returns Answer to the given question. */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; +function supportsErrorEvent() { + try { + new ErrorEvent(''); + return true; + } catch (e) { + return false; + } +} /** - * Add an item to the bottom of the list. - * @param item + * Tells whether current environment supports DOMError objects + * {@link supportsDOMError}. + * + * @returns Answer to the given question. */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - if (this._capacity && this.size() > this._capacity) { - this.shift(); +function supportsDOMError() { + try { + // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': + // 1 argument required, but only 0 present. + // @ts-expect-error It really needs 1 argument, not 0. + new DOMError(''); + return true; + } catch (e) { + return false; } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; +} /** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} + * Tells whether current environment supports DOMException objects + * {@link supportsDOMException}. + * + * @returns Answer to the given question. */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; +function supportsDOMException() { + try { + new DOMException(''); + return true; + } catch (e) { + return false; + } +} /** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; + * Tells whether current environment supports Fetch API + * {@link supportsFetch}. + * + * @returns Answer to the given question. + */ +function supportsFetch() { + if (!('fetch' in WINDOW)) { + return false; } - return item; -}; + try { + new Headers(); + new Request('http://www.example.com'); + new Response(); + return true; + } catch (e) { + return false; + } +} /** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} + * isNativeFetch checks if the given function is a native implementation of fetch() */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; +// eslint-disable-next-line @typescript-eslint/ban-types +function isNativeFetch(func) { + return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); +} /** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. + * Tells whether current environment supports Fetch API natively + * {@link supportsNativeFetch}. * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} + * @returns true if `window.fetch` is natively implemented, false otherwise */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; +function supportsNativeFetch() { + if (typeof EdgeRuntime === 'string') { + return true; } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); + + if (!supportsFetch()) { + return false; + } + + // Fast path to avoid DOM I/O + // eslint-disable-next-line @typescript-eslint/unbound-method + if (isNativeFetch(WINDOW.fetch)) { + return true; + } + + // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) + // so create a "pure" iframe to see if that has native fetch + let result = false; + const doc = WINDOW.document; + // eslint-disable-next-line deprecation/deprecation + if (doc && typeof (doc.createElement ) === 'function') { + try { + const sandbox = doc.createElement('iframe'); + sandbox.hidden = true; + doc.head.appendChild(sandbox); + if (sandbox.contentWindow && sandbox.contentWindow.fetch) { + // eslint-disable-next-line @typescript-eslint/unbound-method + result = isNativeFetch(sandbox.contentWindow.fetch); } + doc.head.removeChild(sandbox); + } catch (err) { + debugBuild.DEBUG_BUILD && + logger.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); } - return removed; - } else { - return this.remove(i, count); } -}; -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + return result; +} /** - * Returns true or false whether the list is empty. - * @returns {boolean} + * Tells whether current environment supports ReportingObserver API + * {@link supportsReportingObserver}. + * + * @returns Answer to the given question. */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; +function supportsReportingObserver() { + return 'ReportingObserver' in WINDOW; +} /** - * Returns an array of all queue items. - * @returns {Array} + * Tells whether current environment supports Referrer Policy API + * {@link supportsReferrerPolicy}. + * + * @returns Answer to the given question. */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; +function supportsReferrerPolicy() { + // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default' + // (see https://caniuse.com/#feat=referrer-policy), + // it doesn't. And it throws an exception instead of ignoring this parameter... + // REF: https://github.com/getsentry/raven-js/issues/1233 -/** - * ------------- - * INTERNALS - * ------------- - */ + if (!supportsFetch()) { + return false; + } + + try { + new Request('_', { + referrerPolicy: 'origin' , + }); + return true; + } catch (e) { + return false; + } +} + +exports.isNativeFetch = isNativeFetch; +exports.supportsDOMError = supportsDOMError; +exports.supportsDOMException = supportsDOMException; +exports.supportsErrorEvent = supportsErrorEvent; +exports.supportsFetch = supportsFetch; +exports.supportsNativeFetch = supportsNativeFetch; +exports.supportsReferrerPolicy = supportsReferrerPolicy; +exports.supportsReportingObserver = supportsReportingObserver; +//# sourceMappingURL=supports.js.map + + +/***/ }), + +/***/ 23600: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const is = __nccwpck_require__(36958); + +/* eslint-disable @typescript-eslint/explicit-function-return-type */ + +/** SyncPromise internal states */ +var States; (function (States) { + /** Pending */ + const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; + /** Resolved / OK */ + const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; + /** Rejected / Error */ + const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; +})(States || (States = {})); + +// Overloads so we can call resolvedSyncPromise without arguments and generic argument /** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private + * Creates a resolved sync promise. + * + * @param value the value to resolve the promise with + * @returns the resolved sync promise */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; +function resolvedSyncPromise(value) { + return new SyncPromise(resolve => { + resolve(value); + }); +} /** + * Creates a rejected sync promise. * - * @param fullCopy - * @returns {Array} - * @private + * @param value the value to reject the promise with + * @returns the rejected sync promise */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); - } - return newArray; -}; +function rejectedSyncPromise(reason) { + return new SyncPromise((_, reject) => { + reject(reason); + }); +} /** - * Grows the internal list array. - * @private + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; +class SyncPromise { + + constructor( + executor, + ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this); + this._state = States.PENDING; + this._handlers = []; + + try { + executor(this._resolve, this._reject); + } catch (e) { + this._reject(e); + } + } + + /** JSDoc */ + then( + onfulfilled, + onrejected, + ) { + return new SyncPromise((resolve, reject) => { + this._handlers.push([ + false, + result => { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result ); + } else { + try { + resolve(onfulfilled(result)); + } catch (e) { + reject(e); + } + } + }, + reason => { + if (!onrejected) { + reject(reason); + } else { + try { + resolve(onrejected(reason)); + } catch (e) { + reject(e); + } + } + }, + ]); + this._executeHandlers(); + }); } - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; + /** JSDoc */ + catch( + onrejected, + ) { + return this.then(val => val, onrejected); + } - this._list.length <<= 1; - this._capacityMask = (this._capacityMask << 1) | 1; -}; + /** JSDoc */ + finally(onfinally) { + return new SyncPromise((resolve, reject) => { + let val; + let isRejected; -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; + return this.then( + value => { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, + reason => { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }, + ).then(() => { + if (isRejected) { + reject(val); + return; + } + + resolve(val ); + }); + }); + } + /** JSDoc */ + __init() {this._resolve = (value) => { + this._setResult(States.RESOLVED, value); + };} -module.exports = Denque; + /** JSDoc */ + __init2() {this._reject = (reason) => { + this._setResult(States.REJECTED, reason); + };} + + /** JSDoc */ + __init3() {this._setResult = (state, value) => { + if (this._state !== States.PENDING) { + return; + } + + if (is.isThenable(value)) { + void (value ).then(this._resolve, this._reject); + return; + } + + this._state = state; + this._value = value; + + this._executeHandlers(); + };} + + /** JSDoc */ + __init4() {this._executeHandlers = () => { + if (this._state === States.PENDING) { + return; + } + + const cachedHandlers = this._handlers.slice(); + this._handlers = []; + + cachedHandlers.forEach(handler => { + if (handler[0]) { + return; + } + + if (this._state === States.RESOLVED) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler[1](this._value ); + } + + if (this._state === States.REJECTED) { + handler[2](this._value); + } + + handler[0] = true; + }); + };} +} + +exports.SyncPromise = SyncPromise; +exports.rejectedSyncPromise = rejectedSyncPromise; +exports.resolvedSyncPromise = resolvedSyncPromise; +//# sourceMappingURL=syncpromise.js.map /***/ }), -/***/ 18883: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4907: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const worldwide = __nccwpck_require__(35291); + +const ONE_SECOND_IN_MS = 1000; /** - * Module dependencies. + * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} + * for accessing a high-resolution monotonic clock. */ -var callSiteToString = (__nccwpck_require__(69829).callSiteToString) -var eventListenerCount = (__nccwpck_require__(69829).eventListenerCount) -var relative = (__nccwpck_require__(71017).relative) +/** + * Returns a timestamp in seconds since the UNIX epoch using the Date API. + * + * TODO(v8): Return type should be rounded. + */ +function dateTimestampInSeconds() { + return Date.now() / ONE_SECOND_IN_MS; +} /** - * Module exports. + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. + * + * Wrapping the native API works around differences in behavior from different browsers. */ +function createUnixTimestampInSecondsFunc() { + const { performance } = worldwide.GLOBAL_OBJ ; + if (!performance || !performance.now) { + return dateTimestampInSeconds; + } -module.exports = depd + // Some browser and environments don't have a timeOrigin, so we fallback to + // using Date.now() to compute the starting time. + const approxStartingTimeOrigin = Date.now() - performance.now(); + const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin; + + // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current + // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed. + // + // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the + // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and + // correct for this. + // See: https://github.com/getsentry/sentry-javascript/issues/2590 + // See: https://github.com/mdn/content/issues/4713 + // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6 + return () => { + return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS; + }; +} /** - * Get the path to base files on. + * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the + * availability of the Performance API. + * + * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is + * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The + * skew can grow to arbitrary amounts like days, weeks or months. + * See https://github.com/getsentry/sentry-javascript/issues/2590. */ +const timestampInSeconds = createUnixTimestampInSecondsFunc(); -var basePath = process.cwd() +/** + * Re-exported with an old name for backwards-compatibility. + * TODO (v8): Remove this + * + * @deprecated Use `timestampInSeconds` instead. + */ +const timestampWithMs = timestampInSeconds; /** - * Determine if namespace is contained in the string. + * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. */ +exports._browserPerformanceTimeOriginMode = void 0; -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() +/** + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. + */ +const browserPerformanceTimeOrigin = (() => { + // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or + // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin + // data as reliable if they are within a reasonable threshold of the current time. - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + const { performance } = worldwide.GLOBAL_OBJ ; + if (!performance || !performance.now) { + exports._browserPerformanceTimeOriginMode = 'none'; + return undefined; + } - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true + const threshold = 3600 * 1000; + const performanceNow = performance.now(); + const dateNow = Date.now(); + + // if timeOrigin isn't available set delta to threshold so it isn't used + const timeOriginDelta = performance.timeOrigin + ? Math.abs(performance.timeOrigin + performanceNow - dateNow) + : threshold; + const timeOriginIsReliable = timeOriginDelta < threshold; + + // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin + // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. + // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always + // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the + // Date API. + // eslint-disable-next-line deprecation/deprecation + const navigationStart = performance.timing && performance.timing.navigationStart; + const hasNavigationStart = typeof navigationStart === 'number'; + // if navigationStart isn't available set delta to threshold so it isn't used + const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + const navigationStartIsReliable = navigationStartDelta < threshold; + + if (timeOriginIsReliable || navigationStartIsReliable) { + // Use the more reliable time origin + if (timeOriginDelta <= navigationStartDelta) { + exports._browserPerformanceTimeOriginMode = 'timeOrigin'; + return performance.timeOrigin; + } else { + exports._browserPerformanceTimeOriginMode = 'navigationStart'; + return navigationStart; } } - return false -} + // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. + exports._browserPerformanceTimeOriginMode = 'dateNow'; + return dateNow; +})(); -/** - * Convert a data descriptor to accessor descriptor. - */ +exports.browserPerformanceTimeOrigin = browserPerformanceTimeOrigin; +exports.dateTimestampInSeconds = dateTimestampInSeconds; +exports.timestampInSeconds = timestampInSeconds; +exports.timestampWithMs = timestampWithMs; +//# sourceMappingURL=time.js.map -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - descriptor.get = function getter () { return value } +/***/ }), - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } +/***/ 77354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - delete descriptor.value - delete descriptor.writable +Object.defineProperty(exports, "__esModule", ({ value: true })); - Object.defineProperty(obj, prop, descriptor) +const baggage = __nccwpck_require__(41022); +const misc = __nccwpck_require__(88642); - return descriptor -} +// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here +const TRACEPARENT_REGEXP = new RegExp( + '^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$', // whitespace +); /** - * Create arguments string to keep arity. + * Extract transaction context data from a `sentry-trace` header. + * + * @param traceparent Traceparent string + * + * @returns Object containing data from the header, or undefined if traceparent string is malformed */ +function extractTraceparentData(traceparent) { + if (!traceparent) { + return undefined; + } -function createArgumentsString (arity) { - var str = '' + const matches = traceparent.match(TRACEPARENT_REGEXP); + if (!matches) { + return undefined; + } - for (var i = 0; i < arity; i++) { - str += ', arg' + i + let parentSampled; + if (matches[3] === '1') { + parentSampled = true; + } else if (matches[3] === '0') { + parentSampled = false; } - return str.substr(2) + return { + traceId: matches[1], + parentSampled, + parentSpanId: matches[2], + }; } /** - * Create stack string from stack. + * Create tracing context from incoming headers. + * + * @deprecated Use `propagationContextFromHeaders` instead. */ +// TODO(v8): Remove this function +function tracingContextFromHeaders( + sentryTrace, + baggage$1, +) -function createStackString (stack) { - var str = this.name + ': ' + this.namespace + { + const traceparentData = extractTraceparentData(sentryTrace); + const dynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext(baggage$1); - if (this.message) { - str += ' deprecated ' + this.message - } + const { traceId, parentSpanId, parentSampled } = traceparentData || {}; - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) + if (!traceparentData) { + return { + traceparentData, + dynamicSamplingContext: undefined, + propagationContext: { + traceId: traceId || misc.uuid4(), + spanId: misc.uuid4().substring(16), + }, + }; + } else { + return { + traceparentData, + dynamicSamplingContext: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it + propagationContext: { + traceId: traceId || misc.uuid4(), + parentSpanId: parentSpanId || misc.uuid4().substring(16), + spanId: misc.uuid4().substring(16), + sampled: parentSampled, + dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it + }, + }; } - - return str } /** - * Create deprecate for namespace in caller. + * Create a propagation context from incoming headers. */ +function propagationContextFromHeaders( + sentryTrace, + baggage$1, +) { + const traceparentData = extractTraceparentData(sentryTrace); + const dynamicSamplingContext = baggage.baggageHeaderToDynamicSamplingContext(baggage$1); -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } - - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] + const { traceId, parentSpanId, parentSampled } = traceparentData || {}; - function deprecate (message) { - // call to self as log - log.call(deprecate, message) + if (!traceparentData) { + return { + traceId: traceId || misc.uuid4(), + spanId: misc.uuid4().substring(16), + }; + } else { + return { + traceId: traceId || misc.uuid4(), + parentSpanId: parentSpanId || misc.uuid4().substring(16), + spanId: misc.uuid4().substring(16), + sampled: parentSampled, + dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it + }; } - - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty - - return deprecate } /** - * Determine if namespace is ignored. - */ - -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } - - var str = process.env.NO_DEPRECATION || '' - - // namespace ignored - return containsNamespace(str, namespace) -} - -/** - * Determine if namespace is traced. - */ - -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } - - var str = process.env.TRACE_DEPRECATION || '' - - // namespace traced - return containsNamespace(str, namespace) -} - -/** - * Display deprecation message. + * Create sentry-trace header from span context values. */ - -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } - - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file - - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } - - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] - - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } - - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined - - if (key !== undefined && key in this._warned) { - // already warned - return - } - - this._warned[key] = true - - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } - - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return +function generateSentryTraceHeader( + traceId = misc.uuid4(), + spanId = misc.uuid4().substring(16), + sampled, +) { + let sampledString = ''; + if (sampled !== undefined) { + sampledString = sampled ? '-1' : '-0'; } - - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') + return `${traceId}-${spanId}${sampledString}`; } -/** - * Get call site location as array. - */ - -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() +exports.TRACEPARENT_REGEXP = TRACEPARENT_REGEXP; +exports.extractTraceparentData = extractTraceparentData; +exports.generateSentryTraceHeader = generateSentryTraceHeader; +exports.propagationContextFromHeaders = propagationContextFromHeaders; +exports.tracingContextFromHeaders = tracingContextFromHeaders; +//# sourceMappingURL=tracing.js.map - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } - var site = [file, line, colm] +/***/ }), - site.callSite = callSite - site.name = callSite.getFunctionName() +/***/ 40825: +/***/ ((__unused_webpack_module, exports) => { - return site -} +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Generate a default message from the site. + * Parses string form of URL into an object + * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B + * // intentionally using regex and not href parsing trick because React Native and other + * // environments where DOM might not be available + * @returns parsed URL object */ - -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name - - // make useful anonymous name - if (!funcName) { - funcName = '' - } - - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() - - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } - - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName +function parseUrl(url) { + if (!url) { + return {}; } - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} - -/** - * Format deprecation message without color. - */ - -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() - - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg - - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } - - return formatted - } + const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (caller) { - formatted += ' at ' + formatLocation(caller) + if (!match) { + return {}; } - return formatted + // coerce to undefined values to empty string so we don't get 'undefined' + const query = match[6] || ''; + const fragment = match[8] || ''; + return { + host: match[4], + path: match[5], + protocol: match[2], + search: query, + hash: fragment, + relative: match[5] + query + fragment, // everything minus origin + }; } /** - * Format deprecation message with color. + * Strip the query string and fragment off of a given URL or path (if present) + * + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment */ - -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset - - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } - - return formatted - } - - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } - - return formatted +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; } /** - * Format call site location. + * Returns number of URL segments of a passed string URL. */ - -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] +function getNumberOfUrlSegments(url) { + // split at '/' or at '\/' to split regex urls correctly + return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; } /** - * Get the stack as array of call sites. + * Takes a URL object and returns a sanitized string which is safe to use as span description + * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data */ +function getSanitizedUrlString(url) { + const { protocol, host, path } = url; -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) + const filteredHost = + (host && + host + // Always filter out authority + .replace(/^.*@/, '[filtered]:[filtered]@') + // Don't show standard :80 (http) and :443 (https) ports to reduce the noise + // TODO: Use new URL global if it exists + .replace(/(:80)$/, '') + .replace(/(:443)$/, '')) || + ''; - // capture the stack - Error.captureStackTrace(obj) + return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`; +} - // slice this function off the top - var stack = obj.stack.slice(1) +exports.getNumberOfUrlSegments = getNumberOfUrlSegments; +exports.getSanitizedUrlString = getSanitizedUrlString; +exports.parseUrl = parseUrl; +exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; +//# sourceMappingURL=url.js.map - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - return stack -} +/***/ }), -/** - * Capture call site stack from v8. - */ +/***/ 79110: +/***/ ((__unused_webpack_module, exports) => { -function prepareObjectStackTrace (obj, stack) { - return stack -} +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Return a wrapped function in a deprecation message. + * Recursively traverses an object to update an existing nested key. + * Note: The provided key path must include existing properties, + * the function will not create objects while traversing. + * + * @param obj An object to update + * @param value The value to update the nested key with + * @param keyPath The path to the key to update ex. fizz.buzz.foo */ - -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setNestedKey(obj, keyPath, value) { + // Ex. foo.bar.zoop will extract foo and bar.zoop + const match = keyPath.match(/([a-z_]+)\.(.*)/i); + // The match will be null when there's no more recursing to do, i.e., when we've reached the right level of the object + if (match === null) { + obj[keyPath] = value; + } else { + // `match[1]` is the initial segment of the path, and `match[2]` is the remainder of the path + const innerObj = obj[match[1]]; + setNestedKey(innerObj, match[2], value); } - - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) - - site.name = fn.name - - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') - - return deprecatedfn } /** - * Wrap property in a deprecation message. + * Enforces inclusion of a given integration with specified options in an integration array originally determined by the + * user, by either including the given default instance or by patching an existing user instance with the given options. + * + * Ideally this would happen when integrations are set up, but there isn't currently a mechanism there for merging + * options from a default integration instance with those from a user-provided instance of the same integration, only + * for allowing the user to override a default instance entirely. (TODO: Fix that.) + * + * @param defaultIntegrationInstance An instance of the integration with the correct options already set + * @param userIntegrations Integrations defined by the user. + * @param forcedOptions Options with which to patch an existing user-derived instance on the integration. + * @returns A final integrations array. + * + * @deprecated This will be removed in v8. */ +function addOrUpdateIntegration( + defaultIntegrationInstance, + userIntegrations, + forcedOptions = {}, +) { + return ( + Array.isArray(userIntegrations) + ? addOrUpdateIntegrationInArray(defaultIntegrationInstance, userIntegrations, forcedOptions) + : addOrUpdateIntegrationInFunction( + defaultIntegrationInstance, + // Somehow TS can't figure out that not being an array makes this necessarily a function + userIntegrations , + forcedOptions, + ) + ) ; +} + +function addOrUpdateIntegrationInArray( + defaultIntegrationInstance, + userIntegrations, + forcedOptions, +) { + const userInstance = userIntegrations.find(integration => integration.name === defaultIntegrationInstance.name); -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } - - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } - - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) - - // set site name - site.name = prop - - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } - - var get = descriptor.get - var set = descriptor.set - - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) + if (userInstance) { + for (const [keyPath, value] of Object.entries(forcedOptions)) { + setNestedKey(userInstance, keyPath, value); } - } - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } + return userIntegrations; } - Object.defineProperty(obj, prop, descriptor) + return [...userIntegrations, defaultIntegrationInstance]; } -/** - * Create DeprecationError for deprecation - */ - -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) - - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) - - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString +function addOrUpdateIntegrationInFunction( + defaultIntegrationInstance, + userIntegrationsFunc, + forcedOptions, +) { + const wrapper = defaultIntegrations => { + const userFinalIntegrations = userIntegrationsFunc(defaultIntegrations); + + // There are instances where we want the user to be able to prevent an integration from appearing at all, which they + // would do by providing a function which filters out the integration in question. If that's happened in one of + // those cases, don't add our default back in. + if (defaultIntegrationInstance.allowExclusionByUser) { + const userFinalInstance = userFinalIntegrations.find( + integration => integration.name === defaultIntegrationInstance.name, + ); + if (!userFinalInstance) { + return userFinalIntegrations; } - - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val } - }) - - return error -} + return addOrUpdateIntegrationInArray(defaultIntegrationInstance, userFinalIntegrations, forcedOptions); + }; -/***/ }), + return wrapper; +} -/***/ 35554: -/***/ ((module) => { +exports.addOrUpdateIntegration = addOrUpdateIntegration; +//# sourceMappingURL=userIntegrations.js.map -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ +/***/ }), +/***/ 78075: +/***/ ((__unused_webpack_module, exports) => { -/** - * Module exports. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); -module.exports = callSiteToString +// Based on https://github.com/sindresorhus/escape-string-regexp but with modifications to: +// a) reduce the size by skipping the runtime type - checking +// b) ensure it gets down - compiled for old versions of Node(the published package only supports Node 12+). +// +// MIT License +// +// Copyright (c) Sindre Sorhus (https://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. /** - * Format a CallSite file location to a string. + * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to + * `new RegExp()`. + * + * @param regexString The string to escape + * @returns An version of the string with all special regex characters escaped */ - -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' - - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() - } - - if (fileName) { - fileLocation += fileName - - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber - - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } - } - - return fileLocation || 'unknown source' +function escapeStringForRegex(regexString) { + // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems + // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. + return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); } -/** - * Format a CallSite to a string. - */ +exports.escapeStringForRegex = escapeStringForRegex; +//# sourceMappingURL=escapeStringForRegex.js.map -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) +/***/ }), - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } +/***/ 42159: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - line += functionName +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } +const worldwide = __nccwpck_require__(35291); - if (addSuffix) { - line += ' (' + fileLocation + ')' - } +// Based on https://github.com/angular/angular.js/pull/13945/files - return line -} +// eslint-disable-next-line deprecation/deprecation +const WINDOW = worldwide.getGlobalObject(); /** - * Get constructor name of reviver. + * Tells whether current environment supports History API + * {@link supportsHistory}. + * + * @returns Answer to the given question. */ +function supportsHistory() { + // NOTE: in Chrome App environment, touching history.pushState, *even inside + // a try/catch block*, will cause Chrome to output an error to console.error + // borrowed from: https://github.com/angular/angular.js/pull/13945/files + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const chromeVar = (WINDOW ).chrome; + const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime; + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState; -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null + return !isChromePackagedApp && hasHistoryApi; } +exports.supportsHistory = supportsHistory; +//# sourceMappingURL=supportsHistory.js.map + /***/ }), -/***/ 12078: -/***/ ((module) => { +/***/ 35291: +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** Internal global with common properties and Sentry extensions */ +// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification +// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js +// core-js has the following licence: +// +// Copyright (c) 2014-2022 Denis Pushkarev +// +// 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. + +/** Returns 'obj' if it's the global object, otherwise returns undefined */ +function isGlobalObj(obj) { + return obj && obj.Math == Math ? obj : undefined; +} + +/** Get's the global object for the current JavaScript runtime */ +const GLOBAL_OBJ = + (typeof globalThis == 'object' && isGlobalObj(globalThis)) || + // eslint-disable-next-line no-restricted-globals + (typeof window == 'object' && isGlobalObj(window)) || + (typeof self == 'object' && isGlobalObj(self)) || + (typeof global == 'object' && isGlobalObj(global)) || + (function () { + return this; + })() || + {}; /** - * Module exports. - * @public + * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 */ - -module.exports = eventListenerCount +function getGlobalObject() { + return GLOBAL_OBJ ; +} /** - * Get the count of listeners on an event emitter of a specific type. + * Returns a global singleton contained in the global `__SENTRY__` object. + * + * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory + * function and added to the `__SENTRY__` object. + * + * @param name name of the global singleton on __SENTRY__ + * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` + * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value + * @returns the singleton */ - -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length +function getGlobalSingleton(name, creator, obj) { + const gbl = (obj || GLOBAL_OBJ) ; + const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); + const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); + return singleton; } +exports.GLOBAL_OBJ = GLOBAL_OBJ; +exports.getGlobalObject = getGlobalObject; +exports.getGlobalSingleton = getGlobalSingleton; +//# sourceMappingURL=worldwide.js.map + /***/ }), -/***/ 69829: +/***/ 86661: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ @@ -33258,1575 +40173,1465 @@ function eventListenerCount (emitter, type) { * @private */ -var EventEmitter = (__nccwpck_require__(82361).EventEmitter) +var Negotiator = __nccwpck_require__(60668) +var mime = __nccwpck_require__(14096) /** * Module exports. * @public */ -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - function prepareObjectStackTrace (obj, stack) { - return stack - } - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - - // capture the stack - Error.captureStackTrace(obj) - - // slice the stack - var stack = obj.stack.slice() - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) - -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) +module.exports = Accepts /** - * Define a lazy property. + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public */ -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) - - return val +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) } - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) + this.headers = req.headers + this.negotiator = new Negotiator(req) } /** - * Call toString() on the obj - */ - -function toString (obj) { - return obj.toString() -} - - -/***/ }), - -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ - /* istanbul ignore next */ +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] } - - this.name = 'Deprecation'; } -} - -exports.Deprecation = Deprecation; + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } -/***/ }), + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return first + ? types[mimes.indexOf(first)] + : false +} -"use strict"; -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public */ +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } -/** - * Module dependencies. - * @private - */ + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } -var ReadStream = (__nccwpck_require__(57147).ReadStream) -var Stream = __nccwpck_require__(12781) + return this.negotiator.encodings(encodings)[0] || false +} /** - * Module exports. + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} * @public */ -module.exports = destroy +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} /** - * Destroy a stream. + * Return accepted languages or best fit based on `langs`. * - * @param {object} stream + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} * @public */ -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ - if (!(stream instanceof Stream)) { - return stream + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } } - if (typeof stream.destroy === 'function') { - stream.destroy() + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() } - return stream + return this.negotiator.languages(languages)[0] || false } /** - * Destroy a ReadStream. + * Convert extnames to mime. * - * @param {object} stream + * @param {String} type + * @return {String} * @private */ -function destroyReadStream(stream) { - stream.destroy() - - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } - - return stream +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type } /** - * On open handler to close stream. + * Check if mime is valid. + * + * @param {String} type + * @return {String} * @private */ -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } +function validMime (type) { + return typeof type === 'string' } /***/ }), -/***/ 12437: +/***/ 77784: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* @flow */ -/*:: +"use strict"; -type DotenvParseOptions = { - debug?: boolean -} +const indentString = __nccwpck_require__(94024); +const cleanStack = __nccwpck_require__(8208); -// keys and values from src -type DotenvParseOutput = { [string]: string } +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } -*/ + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } + + return new Error(error); + }); + + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); + + this.name = 'AggregateError'; -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) + Object.defineProperty(this, '_errors', {value: errors}); + } -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } } -const NEWLINE = '\n' -const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ -const RE_NEWLINES = /\\n/g -const NEWLINES_MATCH = /\n|\r|\r\n/ +module.exports = AggregateError; -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} - // convert Buffers before splitting into lines and processing - src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { - // matching "KEY' and 'VAL' in 'KEY=VAL' - const keyValueArr = line.match(RE_INI_KEY_VAL) - // matched? - if (keyValueArr != null) { - const key = keyValueArr[1] - // default undefined or missing values to empty string - let val = (keyValueArr[2] || '') - const end = val.length - 1 - const isDoubleQuoted = val[0] === '"' && val[end] === '"' - const isSingleQuoted = val[0] === "'" && val[end] === "'" - - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) - - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } +/***/ }), - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) - } - }) +/***/ 79560: +/***/ ((module) => { - return obj -} +"use strict"; -// Populates process.env from .env file -function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { - let dotenvPath = path.resolve(process.cwd(), '.env') - let encoding /*: string */ = 'utf8' - let debug = false - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) } } - try { - // specifying an encoding returns a string instead of a buffer - const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) + return result +} - Object.keys(parsed).forEach(function (key) { - if (!Object.prototype.hasOwnProperty.call(process.env, key)) { - process.env[key] = parsed[key] - } else if (debug) { - log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) - } - }) +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] - return { parsed } - } catch (e) { - return { error: e } + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } } + + return result } -module.exports.config = config -module.exports.parse = parse +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} /***/ }), -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 40479: +/***/ ((module) => { "use strict"; -var Buffer = (__nccwpck_require__(21867).Buffer); +/* global SharedArrayBuffer, Atomics */ + +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) -var getParamBytesForAlg = __nccwpck_require__(30528); + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + Atomics.wait(nil, 0, 0, Number(ms)) + } + module.exports = sleep +} else { -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + const target = Date.now() + Number(ms) + while (target > Date.now()){} + } -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } + module.exports = sleep - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); } -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; +/***/ }), - var inputLength = signature.length; +/***/ 52732: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } +var register = __nccwpck_require__(11063); +var addHook = __nccwpck_require__(22027); +var removeHook = __nccwpck_require__(59934); - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} - var rLength = signature[offset++]; +function HookCollection() { + var state = { + registry: {}, + }; - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } + var hook = register.bind(null, state); + bindApi(hook, state); - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + return hook; +} - var rOffset = offset; - offset += rLength; +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); +} - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); - var sLength = signature[offset++]; +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } +/***/ }), - var sOffset = offset; - offset += sLength; +/***/ 22027: +/***/ ((module) => { - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } +module.exports = addHook; - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } - offset = paramBytes; + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} - dst = dst.toString('base64'); - dst = base64Url(dst); - return dst; -} +/***/ }), -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } +/***/ 11063: +/***/ ((module) => { - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } +module.exports = register; - return padding; -} +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); + if (!options) { + options = {}; + } - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } - - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; - - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - - var shortLength = rsBytes < MAX_OCTET; - - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } - return dst; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; - /***/ }), -/***/ 30528: +/***/ 59934: /***/ ((module) => { -"use strict"; - +module.exports = removeHook; -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } + if (index === -1) { + return; + } - throw new Error('Unknown algorithm "' + alg + '"'); + state.registry[name].splice(index, 1); } -module.exports = getParamBytesForAlg; - /***/ }), -/***/ 14401: -/***/ ((module) => { +/***/ 6536: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /*! - * ee-first - * Copyright(c) 2014 Jonathan Ong + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ +/** + * Module dependencies. + * @private + */ + +var deprecate = __nccwpck_require__(60095)('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + /** * Module exports. - * @public + * @type {Parsers} */ -module.exports = first +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') /** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done + * JSON parser. * @public */ -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') +Object.defineProperty(exports, "json", ({ + configurable: true, + enumerable: true, + get: createParserGetter('json') +})) - var cleanups = [] +/** + * Raw parser. + * @public + */ - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] +Object.defineProperty(exports, "raw", ({ + configurable: true, + enumerable: true, + get: createParserGetter('raw') +})) - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') +/** + * Text parser. + * @public + */ - var ee = arr[0] +Object.defineProperty(exports, "text", ({ + configurable: true, + enumerable: true, + get: createParserGetter('text') +})) - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) +/** + * URL-encoded parser. + * @public + */ - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } +Object.defineProperty(exports, "urlencoded", ({ + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +})) - function callback() { - cleanup() - done.apply(null, arguments) - } +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) +function bodyParser (options) { + // use default type for parsers + var opts = Object.create(options || null, { + type: { + configurable: true, + enumerable: true, + value: undefined, + writable: true } - } + }) - function thunk(fn) { - done = fn + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) } +} - thunk.cancel = cleanup +/** + * Create a getter for loading a parser. + * @private + */ - return thunk +function createParserGetter (name) { + return function get () { + return loadParser(name) + } } /** - * Create the event listener. + * Load a parser module. * @private */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +function loadParser (parserName) { + var parser = parsers[parserName] - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } + if (parser !== undefined) { + return parser + } - done(err, ee, event, args) + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = __nccwpck_require__(72162) + break + case 'raw': + parser = __nccwpck_require__(8496) + break + case 'text': + parser = __nccwpck_require__(17211) + break + case 'urlencoded': + parser = __nccwpck_require__(17129) + break } + + // store to prevent invoking require() + return (parsers[parserName] = parser) } /***/ }), -/***/ 16592: -/***/ ((module) => { +/***/ 27946: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module exports. - * @public + * Module dependencies. + * @private */ -module.exports = encodeUrl +var createError = __nccwpck_require__(78024) +var destroy = __nccwpck_require__(32194) +var getBody = __nccwpck_require__(60949) +var iconv = __nccwpck_require__(31748) +var onFinished = __nccwpck_require__(5698) +var unpipe = __nccwpck_require__(66367) +var zlib = __nccwpck_require__(43106) /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private + * Module exports. */ -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +module.exports = read /** - * RegExp to match unmatched surrogate pair. + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options * @private */ -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + unpipe(req) + destroy(stream, true) + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} /** - * String to replace unmatched surrogate pair with. - * @private + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private */ -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} /** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. + * Dump the contents of a request. * - * @param {string} url - * @return {string} - * @public + * @param {object} req + * @param {function} callback + * @api private */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } } /***/ }), -/***/ 23505: +/***/ 72162: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -var util = __nccwpck_require__(73837); -var isArrayish = __nccwpck_require__(7604); - -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } +/** + * Module dependencies. + * @private + */ - message = message instanceof Error - ? message.message - : (message || this.message); +var bytes = __nccwpck_require__(34531) +var contentType = __nccwpck_require__(20756) +var createError = __nccwpck_require__(78024) +var debug = __nccwpck_require__(2830)('body-parser:json') +var read = __nccwpck_require__(27946) +var typeis = __nccwpck_require__(27323) - Error.call(this, message); - Error.captureStackTrace(this, errorExError); +/** + * Module exports. + */ - this.name = name; +module.exports = json - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex - var modifier = properties[key]; +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); +function json (options) { + var opts = options || {} - var overwrittenStack = null; + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } + if (strict) { + var first = firstchar(body) - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } - var modifier = properties[key]; + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + req.body = req.body || {} - return stack.join('\n'); - }; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - Object.defineProperty(this, 'stack', stackDescriptor); - }; + debug('content-type %j', req.headers['content-type']) - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - return errorExError; -}; + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ - return message; - } - }; -}; +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR - if (v) { - return str.replace('%s', v.toString()); - } + for (var i = index + 1; i < str.length; i++) { + partial += JSON_SYNTAX_CHAR + } + } - return null; - } - }; -}; + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} -module.exports = errorEx; +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} /***/ }), -/***/ 94070: -/***/ ((module) => { +/***/ 8496: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module variables. - * @private + * Module dependencies. */ -var matchHtmlRegExp = /["'&<>]/; +var bytes = __nccwpck_require__(34531) +var debug = __nccwpck_require__(2830)('body-parser:raw') +var read = __nccwpck_require__(27946) +var typeis = __nccwpck_require__(27323) /** * Module exports. - * @public */ -module.exports = escapeHtml; +module.exports = raw /** - * Escape special characters in the given string of html. + * Create a middleware to parse raw bodies. * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public + * @param {object} [options] + * @return {function} + * @api public */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); +function raw (options) { + var opts = options || {} - if (!match) { - return str; + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') } - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - if (lastIndex !== index) { - html += str.substring(lastIndex, index); + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - lastIndex = index + 1; - html += escape; + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) } +} - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } /***/ }), -/***/ 69972: +/***/ 17211: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ -/** - * Module exports. - * @public - */ - -module.exports = etag - /** * Module dependencies. - * @private */ -var crypto = __nccwpck_require__(6113) -var Stats = (__nccwpck_require__(57147).Stats) +var bytes = __nccwpck_require__(34531) +var contentType = __nccwpck_require__(20756) +var debug = __nccwpck_require__(2830)('body-parser:text') +var read = __nccwpck_require__(27946) +var typeis = __nccwpck_require__(27323) /** - * Module variables. - * @private + * Module exports. */ -var toString = Object.prototype.toString +module.exports = text /** - * Generate an entity tag. + * Create a middleware to parse text bodies. * - * @param {Buffer|string} entity - * @return {string} - * @private + * @param {object} [options] + * @return {function} + * @api public */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') } - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length + function parse (buf) { + return buf + } - return '"' + len.toString(16) + '-' + hash + '"' -} + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } -/** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public - */ + req.body = req.body || {} -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats + debug('content-type %j', req.headers['content-type']) - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) + // get charset + var charset = getCharset(req) || defaultCharset - return weak - ? 'W/' + tag - : tag + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } } /** - * Determine if object is a Stats object. + * Get the charset of a request. * - * @param {object} obj - * @return {boolean} + * @param {object} req * @api private */ -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined } - - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' } /** - * Generate a tag for a stat. + * Get the simple type checker. * - * @param {object} stat - * @return {string} - * @private + * @param {string} type + * @return {function} */ -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) - - return '"' + size + '-' + mtime + '"' +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } } /***/ }), -/***/ 95449: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright (c) 2015, Yahoo Inc. All rights reserved. - * Copyrights licensed under the New BSD License. - * See the accompanying LICENSE file for terms. - */ -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -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 __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var Handlebars = __nccwpck_require__(97492); -var fs = __nccwpck_require__(77758); -var path = __nccwpck_require__(71017); -var util_1 = __nccwpck_require__(73837); -var globSync = __nccwpck_require__(91957); -var glob = (0, util_1.promisify)(globSync); -var readFile = (0, util_1.promisify)(fs.readFile); -// ----------------------------------------------------------------------------- -var defaultConfig = { - handlebars: Handlebars, - extname: ".handlebars", - encoding: "utf8", - layoutsDir: undefined, - partialsDir: undefined, - defaultLayout: "main", - helpers: undefined, - compilerOptions: undefined, - runtimeOptions: undefined, -}; -var ExpressHandlebars = /** @class */ (function () { - function ExpressHandlebars(config) { - if (config === void 0) { config = {}; } - // Config properties with defaults. - Object.assign(this, defaultConfig, config); - // save given config to override other settings. - this.config = config; - // Express view engine integration point. - this.engine = this.renderView.bind(this); - // Normalize `extname`. - if (this.extname.charAt(0) !== ".") { - this.extname = "." + this.extname; - } - // Internal caches of compiled and precompiled templates. - this.compiled = {}; - this.precompiled = {}; - // Private internal file system cache. - this._fsCache = {}; - } - ExpressHandlebars.prototype.getPartials = function (options) { - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var partialsDirs, dirs, partials, _i, dirs_1, dir, templates, namespace, rename, filePaths, getTemplateNameFn, _a, filePaths_1, filePath, partialName; - var _this = this; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof this.partialsDir === "undefined") { - return [2 /*return*/, {}]; - } - partialsDirs = Array.isArray(this.partialsDir) ? this.partialsDir : [this.partialsDir]; - return [4 /*yield*/, Promise.all(partialsDirs.map(function (dir) { return __awaiter(_this, void 0, void 0, function () { - var dirPath, dirTemplates, dirNamespace, dirRename, templates, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - // Support `partialsDir` collection with object entries that contain a - // templates promise and a namespace. - if (typeof dir === "string") { - dirPath = dir; - } - else if (typeof dir === "object") { - dirTemplates = dir.templates; - dirNamespace = dir.namespace; - dirRename = dir.rename; - dirPath = dir.dir; - } - // We must have some path to templates, or templates themselves. - if (!dirPath && !dirTemplates) { - throw new Error("A partials dir must be a string or config object"); - } - _a = dirTemplates; - if (_a) return [3 /*break*/, 2]; - return [4 /*yield*/, this.getTemplates(dirPath, options)]; - case 1: - _a = (_b.sent()); - _b.label = 2; - case 2: - templates = _a; - return [2 /*return*/, { - templates: templates, - namespace: dirNamespace, - rename: dirRename, - }]; - } - }); - }); }))]; - case 1: - dirs = _b.sent(); - partials = {}; - for (_i = 0, dirs_1 = dirs; _i < dirs_1.length; _i++) { - dir = dirs_1[_i]; - templates = dir.templates, namespace = dir.namespace, rename = dir.rename; - filePaths = Object.keys(templates); - getTemplateNameFn = typeof rename === "function" - ? rename - : this._getTemplateName.bind(this); - for (_a = 0, filePaths_1 = filePaths; _a < filePaths_1.length; _a++) { - filePath = filePaths_1[_a]; - partialName = getTemplateNameFn(filePath, namespace); - partials[partialName] = templates[filePath]; - } - } - return [2 /*return*/, partials]; - } - }); - }); - }; - ExpressHandlebars.prototype.getTemplate = function (filePath, options) { - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var encoding, cache, template, err_1; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - filePath = path.resolve(filePath); - encoding = options.encoding || this.encoding; - cache = options.precompiled ? this.precompiled : this.compiled; - template = options.cache && cache[filePath]; - if (template) { - return [2 /*return*/, template]; - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - cache[filePath] = this._getFile(filePath, { cache: options.cache, encoding: encoding }) - .then(function (file) { - var compileTemplate = (options.precompiled ? _this._precompileTemplate : _this._compileTemplate).bind(_this); - return compileTemplate(file, _this.compilerOptions); - }); - return [4 /*yield*/, cache[filePath]]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - err_1 = _a.sent(); - delete cache[filePath]; - throw err_1; - case 4: return [2 /*return*/]; - } - }); - }); - }; - ExpressHandlebars.prototype.getTemplates = function (dirPath, options) { - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var cache, filePaths, templates, hash, i; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - cache = options.cache; - return [4 /*yield*/, this._getDir(dirPath, { cache: cache })]; - case 1: - filePaths = _a.sent(); - return [4 /*yield*/, Promise.all(filePaths.map(function (filePath) { - return _this.getTemplate(path.join(dirPath, filePath), options); - }))]; - case 2: - templates = _a.sent(); - hash = {}; - for (i = 0; i < filePaths.length; i++) { - hash[filePaths[i]] = templates[i]; - } - return [2 /*return*/, hash]; - } - }); - }); - }; - ExpressHandlebars.prototype.render = function (filePath, context, options) { - if (context === void 0) { context = {}; } - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var encoding, _a, template, partials, helpers, runtimeOptions, data, html; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - encoding = options.encoding || this.encoding; - return [4 /*yield*/, Promise.all([ - this.getTemplate(filePath, { cache: options.cache, encoding: encoding }), - (options.partials || this.getPartials({ cache: options.cache, encoding: encoding })), - ])]; - case 1: - _a = _b.sent(), template = _a[0], partials = _a[1]; - helpers = __assign(__assign({}, this.helpers), options.helpers); - runtimeOptions = __assign(__assign({}, this.runtimeOptions), options.runtimeOptions); - data = __assign(__assign({}, options.data), { exphbs: __assign(__assign({}, options), { filePath: filePath, helpers: helpers, partials: partials, runtimeOptions: runtimeOptions }) }); - html = this._renderTemplate(template, context, __assign(__assign({}, runtimeOptions), { data: data, helpers: helpers, partials: partials })); - return [2 /*return*/, html]; - } - }); - }); - }; - ExpressHandlebars.prototype.renderView = function (viewPath, options, callback) { - if (options === void 0) { options = {}; } - if (callback === void 0) { callback = null; } - return __awaiter(this, void 0, void 0, function () { - var context, promise, view, views, viewsPath, encoding, helpers, partials, _a, renderOptions, html, layoutPath, err_2; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof options === "function") { - callback = options; - options = {}; - } - context = options; - promise = null; - if (!callback) { - promise = new Promise(function (resolve, reject) { - callback = function (err, value) { err !== null ? reject(err) : resolve(value); }; - }); - } - views = options.settings && options.settings.views; - viewsPath = this._resolveViewsPath(views, viewPath); - if (viewsPath) { - view = this._getTemplateName(path.relative(viewsPath, viewPath)); - this.partialsDir = this.config.partialsDir || path.join(viewsPath, "partials/"); - this.layoutsDir = this.config.layoutsDir || path.join(viewsPath, "layouts/"); - } - encoding = options.encoding || this.encoding; - helpers = __assign(__assign({}, this.helpers), options.helpers); - _a = [{}]; - return [4 /*yield*/, this.getPartials({ cache: options.cache, encoding: encoding })]; - case 1: - partials = __assign.apply(void 0, [__assign.apply(void 0, _a.concat([_b.sent()])), (options.partials || {})]); - renderOptions = { - cache: options.cache, - encoding: encoding, - view: view, - layout: "layout" in options ? options.layout : this.defaultLayout, - data: options.data, - helpers: helpers, - partials: partials, - runtimeOptions: options.runtimeOptions, - }; - _b.label = 2; - case 2: - _b.trys.push([2, 6, , 7]); - return [4 /*yield*/, this.render(viewPath, context, renderOptions)]; - case 3: - html = _b.sent(); - layoutPath = this._resolveLayoutPath(renderOptions.layout); - if (!layoutPath) return [3 /*break*/, 5]; - return [4 /*yield*/, this.render(layoutPath, __assign(__assign({}, context), { body: html }), __assign(__assign({}, renderOptions), { layout: undefined }))]; - case 4: - html = _b.sent(); - _b.label = 5; - case 5: - callback(null, html); - return [3 /*break*/, 7]; - case 6: - err_2 = _b.sent(); - callback(err_2); - return [3 /*break*/, 7]; - case 7: return [2 /*return*/, promise]; - } - }); - }); - }; - // -- Protected Hooks ---------------------------------------------------------- - ExpressHandlebars.prototype._compileTemplate = function (template, options) { - if (options === void 0) { options = {}; } - return this.handlebars.compile(template.trim(), options); - }; - ExpressHandlebars.prototype._precompileTemplate = function (template, options) { - if (options === void 0) { options = {}; } - return this.handlebars.precompile(template.trim(), options); - }; - ExpressHandlebars.prototype._renderTemplate = function (template, context, options) { - if (context === void 0) { context = {}; } - if (options === void 0) { options = {}; } - return template(context, options).trim(); - }; - // -- Private ------------------------------------------------------------------ - ExpressHandlebars.prototype._getDir = function (dirPath, options) { - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var cache, dir, pattern, err_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - dirPath = path.resolve(dirPath); - cache = this._fsCache; - dir = options.cache && cache[dirPath]; - if (!dir) return [3 /*break*/, 2]; - return [4 /*yield*/, dir]; - case 1: return [2 /*return*/, (_a.sent()).concat()]; - case 2: - pattern = "**/*" + this.extname; - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - dir = cache[dirPath] = glob(pattern, { - cwd: dirPath, - follow: true, - }); - // @ts-ignore FIXME: not sure how to throw error in glob for test coverage - if (options._throwTestError) { - throw new Error("test"); - } - return [4 /*yield*/, dir]; - case 4: return [2 /*return*/, (_a.sent()).concat()]; - case 5: - err_3 = _a.sent(); - delete cache[dirPath]; - throw err_3; - case 6: return [2 /*return*/]; - } - }); - }); - }; - ExpressHandlebars.prototype._getFile = function (filePath, options) { - if (options === void 0) { options = {}; } - return __awaiter(this, void 0, void 0, function () { - var cache, encoding, file, err_4; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - filePath = path.resolve(filePath); - cache = this._fsCache; - encoding = options.encoding || this.encoding; - file = options.cache && cache[filePath]; - if (file) { - return [2 /*return*/, file]; - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - cache[filePath] = readFile(filePath, { encoding: encoding || "utf8" }); - return [4 /*yield*/, cache[filePath]]; - case 2: return [2 /*return*/, _a.sent()]; - case 3: - err_4 = _a.sent(); - delete cache[filePath]; - throw err_4; - case 4: return [2 /*return*/]; - } - }); - }); - }; - ExpressHandlebars.prototype._getTemplateName = function (filePath, namespace) { - if (namespace === void 0) { namespace = null; } - var name = filePath; - if (name.endsWith(this.extname)) { - name = name.substring(0, name.length - this.extname.length); - } - if (namespace) { - name = namespace + "/" + name; - } - return name; - }; - ExpressHandlebars.prototype._resolveViewsPath = function (views, file) { - if (!Array.isArray(views)) { - return views; - } - var lastDir = path.resolve(file); - var dir = path.dirname(lastDir); - var absoluteViews = views.map(function (v) { return path.resolve(v); }); - // find the closest parent - while (dir !== lastDir) { - var index = absoluteViews.indexOf(dir); - if (index >= 0) { - return views[index]; - } - lastDir = dir; - dir = path.dirname(lastDir); - } - // cannot resolve view - return null; - }; - ExpressHandlebars.prototype._resolveLayoutPath = function (layoutPath) { - if (!layoutPath) { - return null; - } - if (!path.extname(layoutPath)) { - layoutPath += this.extname; - } - return path.resolve(this.layoutsDir || "", layoutPath); - }; - return ExpressHandlebars; -}()); -exports["default"] = ExpressHandlebars; -//# sourceMappingURL=express-handlebars.js.map - -/***/ }), - -/***/ 21670: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright (c) 2014, Yahoo Inc. All rights reserved. - * Copyrights licensed under the New BSD License. - * See the accompanying LICENSE file for terms. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.engine = exports.create = exports.ExpressHandlebars = void 0; -var express_handlebars_1 = __nccwpck_require__(95449); -exports.ExpressHandlebars = express_handlebars_1.default; -function create(config) { - if (config === void 0) { config = {}; } - return new express_handlebars_1.default(config); -} -exports.create = create; -function engine(config) { - if (config === void 0) { config = {}; } - return create(config).engine; -} -exports.engine = engine; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 71204: +/***/ 17129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -module.exports = __nccwpck_require__(22587); - - -/***/ }), - -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman + * body-parser + * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -34838,6457 +41643,5286 @@ module.exports = __nccwpck_require__(22587); * @private */ -var finalhandler = __nccwpck_require__(30810); -var Router = __nccwpck_require__(24963); -var methods = __nccwpck_require__(58752); -var middleware = __nccwpck_require__(92636); -var query = __nccwpck_require__(79768); -var debug = __nccwpck_require__(38237)('express:application'); -var View = __nccwpck_require__(99209); -var http = __nccwpck_require__(13685); -var compileETag = (__nccwpck_require__(53561).compileETag); -var compileQueryParser = (__nccwpck_require__(53561).compileQueryParser); -var compileTrust = (__nccwpck_require__(53561).compileTrust); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var merge = __nccwpck_require__(44429); -var resolve = (__nccwpck_require__(71017).resolve); -var setPrototypeOf = __nccwpck_require__(40414) -var slice = Array.prototype.slice; +var bytes = __nccwpck_require__(34531) +var contentType = __nccwpck_require__(20756) +var createError = __nccwpck_require__(78024) +var debug = __nccwpck_require__(2830)('body-parser:urlencoded') +var deprecate = __nccwpck_require__(60095)('body-parser') +var read = __nccwpck_require__(27946) +var typeis = __nccwpck_require__(27323) /** - * Application prototype. + * Module exports. */ -var app = exports = module.exports = {}; +module.exports = urlencoded /** - * Variable for trust proxy inheritance back-compat - * @private + * Cache of parser modules. */ -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +var parsers = Object.create(null) /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods + * Create a middleware to parse urlencoded bodies. * - * @private + * @param {object} [options] + * @return {function} + * @public */ -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +function urlencoded (options) { + var opts = options || {} - this.defaultConfiguration(); -}; + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } -/** - * Initialize application configuration. - * @private - */ + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + var depth = typeof opts.depth !== 'number' + ? Number(opts.depth || 32) + : opts.depth -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - debug('booting in %s mode', env); + function parse (body) { + return body.length + ? queryparse(body) + : {} + } - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); - - // setup locals - this.locals = Object.create(null); - - // top-most app is mounted at / - this.mountpath = '/'; - - // default locals - this.locals.settings = this.settings; + req.body = req.body || {} - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - if (env === 'production') { - this.enable('view cache'); - } + debug('content-type %j', req.headers['content-type']) - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - }); -}; -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify, + depth: depth + }) } -}; +} /** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. + * Get the extended query parser. * - * @private + * @param {object} options */ -app.handle = function handle(req, res, callback) { - var router = this._router; +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); + var depth = typeof options.depth !== 'number' + ? Number(options.depth || 32) + : options.depth + var parse = parser('qs') - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') } - router.handle(req, res, done); -}; - -/** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. - * - * @public - */ - -app.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } + if (isNaN(depth) || depth < 0) { + throw new TypeError('option depth must be a zero or a positive number') } - var fns = flatten(slice.call(arguments, offset)); - - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 } - // setup router - this.lazyrouter(); - var router = this._router; + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) } - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); - - // mounted an app - fn.emit('mount', this); - }, this); + var arrayLimit = Math.max(100, paramCount) - return this; -}; + debug('parse extended urlencoding') + try { + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: depth, + strictDepth: true, + parameterLimit: parameterLimit + }) + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, 'The input exceeded the depth', { + type: 'querystring.parse.rangeError' + }) + } else { + throw err + } + } + } +} /** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. + * Get the charset of a request. * - * @public + * @param {object} req + * @api private */ -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you don't need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. + * Count the number of parameters, stopping once limit reached * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public + * @param {string} body + * @param {number} limit + * @api private */ -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); - } +function parameterCount (body, limit) { + var count = 0 + var index = 0 - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ - // store engine - this.engines[extension] = fn; + if (count === limit) { + return undefined + } + } - return this; -}; + return count +} /** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. + * Get parser for module name dynamically. * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public + * @param {string} name + * @return {function} + * @api private */ -app.param = function param(name, fn) { - this.lazyrouter(); +function parser (name) { + var mod = parsers[name] - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } + if (mod !== undefined) { + return mod.parse + } - return this; + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = __nccwpck_require__(40240) + break + case 'querystring': + mod = __nccwpck_require__(83480) + break } - this._router.param(name, fn); + // store to prevent invoking require() + parsers[name] = mod - return this; -}; + return mod.parse +} /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. + * Get the simple query parser. * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public + * @param {object} options */ -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') - debug('set "%s" to %o', setting, val); + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } - // set value - this.settings[setting] = val; + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } - break; + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) } - - return this; -}; +} /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". + * Get the simple type checker. * - * @return {String} - * @private + * @param {string} type + * @return {function} */ -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; - -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public - */ +/***/ }), -app.disabled = function disabled(setting) { - return !this.set(setting); -}; +/***/ 78812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +"use strict"; -app.enable = function enable(setting) { - return this.set(setting, true); -}; -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +var Batcher, Events, parser; +parser = __nccwpck_require__(29700); +Events = __nccwpck_require__(31914); -app.disable = function disable(setting) { - return this.set(setting, false); -}; +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ + this._resetPromise(); -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); + this._lastFlush = Date.now(); } - this.lazyrouter(); - - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); - -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public - */ + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } -app.all = function all(path) { - this.lazyrouter(); + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); - var route = this._router.route(path); - var args = slice.call(arguments, 1); + this._resolve(); - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - return this; -}; + add(data) { + var ret; -// del -> delete alias + this._arr.push(data); -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + ret = this._promise; -/** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public - */ + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; + return ret; + } - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; } - // merge app.locals - merge(renderOptions, this.locals); - - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } + ; + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + return Batcher; +}.call(void 0); - // merge options - merge(renderOptions, opts); +module.exports = Batcher; - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } +/***/ }), - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } +/***/ 68760: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // view - if (!view) { - var View = this.get('view'); +"use strict"; - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } - } +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - // render - tryRender(view, renderOptions, done); -}; +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } -/** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @public - */ +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -/** - * Try rendering a view. - * @private - */ +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} +var Bottleneck, + DEFAULT_PRIORITY, + Events, + Job, + LocalDatastore, + NUM_PRIORITIES, + Queues, + RedisDatastore, + States, + Sync, + parser, + splice = [].splice; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(29700); +Queues = __nccwpck_require__(91363); +Job = __nccwpck_require__(42448); +LocalDatastore = __nccwpck_require__(37099); +RedisDatastore = __nccwpck_require__(41827); +Events = __nccwpck_require__(31914); +States = __nccwpck_require__(5685); +Sync = __nccwpck_require__(39216); +Bottleneck = function () { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); -/***/ }), + this._validateOptions(options, invalid); -/***/ 22587: -/***/ ((module, exports, __nccwpck_require__) => { + parser.load(options, this.instanceDefaults, this); + this._queues = new Queues(NUM_PRIORITIES); + this._scheduled = {}; + this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events(this); + this._submitLock = new Sync("submit", this.Promise); + this._registerLock = new Sync("register", this.Promise); + storeOptions = parser.load(options, this.storeDefaults, {}); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + this._store = function () { + if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { + storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); + return new LocalDatastore(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }.call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } -/** - * Module dependencies. - */ + _validateOptions(options, invalid) { + if (!(options != null && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } -var bodyParser = __nccwpck_require__(97076) -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var mixin = __nccwpck_require__(11149); -var proto = __nccwpck_require__(313); -var Route = __nccwpck_require__(23699); -var Router = __nccwpck_require__(24963); -var req = __nccwpck_require__(71260); -var res = __nccwpck_require__(64934); + ready() { + return this._store.ready; + } -/** - * Expose `createApplication()`. - */ + clients() { + return this._store.clients; + } -exports = module.exports = createApplication; + channel() { + return `b_${this.id}`; + } -/** - * Create an express application. - * - * @return {Function} - * @api public - */ + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; + publish(message) { + return this._store.__publish__(message); + } - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + chain(_limiter) { + this._limiter = _limiter; + return this; + } - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + queued(priority) { + return this._queues.queued(priority); + } - app.init(); - return app; -} + clusterQueued() { + return this._store.__queued__(); + } -/** - * Expose the prototypes. - */ + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } -exports.application = proto; -exports.request = req; -exports.response = res; + running() { + return this._store.__running__(); + } -/** - * Expose constructors. - */ + done() { + return this._store.__done__(); + } -exports.Route = Route; -exports.Router = Router; + jobStatus(id) { + return this._states.jobStatus(id); + } -/** - * Expose middleware - */ + jobs(status) { + return this._states.statusJobs(status); + } -exports.json = bodyParser.json -exports.query = __nccwpck_require__(79768); -exports.raw = bodyParser.raw -exports["static"] = __nccwpck_require__(13146); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded + counts() { + return this._states.statusCounts(); + } -/** - * Replace removed middleware with an appropriate error message. - */ + _randomIndex() { + return Math.random().toString(36).slice(2); + } -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] + check(weight = 1) { + return this._store.__check__(weight); + } -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } + _free(index, job, options, eventInfo) { + var _this = this; -/***/ }), + return _asyncToGenerator(function* () { + var e, running; -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + try { + var _ref = yield _this._store.__free__(index, options.weight); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + running = _ref.running; + _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && _this.empty()) { + return _this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } + })(); + } -/** - * Module dependencies. - * @private - */ + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function () { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } -var setPrototypeOf = __nccwpck_require__(40414) + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; -/** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ + if (this.queued() === 0) { + return this.Promise.resolve(null); + } -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; + queue = this._queues.getFirst(); - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + var _next2 = next = queue.first(); - res.locals = res.locals || Object.create(null); + options = _next2.options; + args = _next2.args; - next(); - }; -}; + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, { + args, + options + }); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({ + success, + wait, + reservoir + }) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, { + success, + args, + options + }); + if (success) { + queue.shift(); + empty = this.empty(); -/***/ }), + if (empty) { + this.Events.trigger("empty"); + } -/***/ 79768: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; -/** - * Module dependencies. - */ + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch(e => { + return this.Events.trigger("error", e); + }); + } -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); + _dropAllQueued(message) { + return this._queues.shiftAll(function (job) { + return job.doDrop({ + message + }); + }); + } -/** - * @param {Object} options - * @return {Function} - * @api public - */ + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; + waitForExecuting = at => { + var finished; - if (typeof options === 'function') { - queryparse = options; - opts = undefined; - } + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; - } + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } + done = options.dropWaitingJobs ? (this._run = function (index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; - next(); - }; -}; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } -/***/ }), + this._dropAllQueued(options.dropErrorMessage); -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + this._receive = function (job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } -/** - * Module dependencies. - * @private - */ + _addToQueue(job) { + var _this2 = this; -var accepts = __nccwpck_require__(83633); -var deprecate = __nccwpck_require__(18883)('express'); -var isIP = (__nccwpck_require__(41808).isIP); -var typeis = __nccwpck_require__(71159); -var http = __nccwpck_require__(13685); -var fresh = __nccwpck_require__(83136); -var parseRange = __nccwpck_require__(26435); -var parse = __nccwpck_require__(89808); -var proxyaddr = __nccwpck_require__(80140); + return _asyncToGenerator(function* () { + var args, blocked, error, options, reachedHWM, shifted, strategy; + args = job.args; + options = job.options; -/** - * Request prototype. - * @public - */ + try { + var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); -var req = Object.create(http.IncomingMessage.prototype) + reachedHWM = _ref2.reachedHWM; + blocked = _ref2.blocked; + strategy = _ref2.strategy; + } catch (error1) { + error = error1; -/** - * Module exports. - * @public - */ + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error + }); -module.exports = req + job.doDrop({ + error + }); + return false; + } -/** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param {String} name - * @return {String} - * @public - */ + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } + if (shifted != null) { + shifted.doDrop(); + } - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } - var lc = name.toLowerCase(); + return reachedHWM; + } + } - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; + job.doQueue(reachedHWM, blocked); -/** - * To do: update docs. - * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" - * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public - */ + _this2._queues.push(job); -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; + yield _this2._drainAll(); + return reachedHWM; + })(); + } -/** - * Check if the given `encoding`s are accepted. - * - * @param {String} ...encoding - * @return {String|Array} - * @public - */ + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); + submit(...args) { + var cb, fn, job, options, ref, ref1, task; -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ + if (typeof args[0] === "function") { + var _ref3, _ref4, _splice$call, _splice$call2; -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + options = parser.load({}, this.jobDefaults); + } else { + var _ref5, _ref6, _splice$call3, _splice$call4; -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); + ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + options = parser.load(options, this.jobDefaults); + } -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ + task = (...args) => { + return new this.Promise(function (resolve, reject) { + return fn(...args, function (...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function (args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function (args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); + schedule(...args) { + var job, options, task; -/** - * Parse Range header field, capping to the given `size`. - * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. - * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. - * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. - * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. - * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} - * @public - */ + if (typeof args[0] === "function") { + var _args = args; -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; + var _args2 = _toArray(_args); -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @public - */ + task = _args2[0]; + args = _args2.slice(1); + options = {}; + } else { + var _args3 = args; -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + var _args4 = _toArray(_args3); - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); + } - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - return defaultValue; -}; + this._receive(job); -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the given mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param {String|Array} types... - * @return {String|false|null} - * @public - */ + return job.promise; + } -req.is = function is(types) { - var arr = types; + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; - } - } + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; - return typeis(this, arr); -}; + wrapped.withOptions = function (options, ...args) { + return schedule(options, fn, ...args); + }; -/** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. - * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. - * - * @return {String} - * @public - */ + return wrapped; + } -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); + updateSettings(options = {}) { + var _this3 = this; - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + currentReservoir() { + return this._store.__currentReservoir__(); + } - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ + } -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); + ; + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events; + Bottleneck.version = Bottleneck.prototype.version = (__nccwpck_require__(88349)/* .version */ .r); + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(72360); + Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(49216); + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(91400); + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(58468); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(78812); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + return Bottleneck; +}.call(void 0); -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public - */ +module.exports = Bottleneck; -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); +/***/ }), -/** - * When "trust proxy" is set, trusted proxy addresses + client. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. - * - * @return {Array} - * @public - */ +/***/ 72360: +/***/ ((module) => { -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); +"use strict"; - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() - return addrs -}); +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; -/** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - * - * @return {Array} - * @public - */ +/***/ }), -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +/***/ 55327: +/***/ ((module) => { - if (!hostname) return []; +"use strict"; - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; - return subdomains.slice(offset); -}); +var DLList; +DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ + push(value) { + var node; + this.length++; -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); + if (typeof this.incr === "function") { + this.incr(); + } -/** - * Parse the "Host" header field to a hostname. - * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. - * - * @return {String} - * @public - */ + node = { + value, + prev: this._last, + next: null + }; -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() + return void 0; } - if (!host) return; + shift() { + var value; - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + if (this._first == null) { + return; + } else { + this.length--; - return index !== -1 - ? host.substring(0, index) - : host; -}); + if (typeof this.decr === "function") { + this.decr(); + } + } -// TODO: change req.host to return host in next major + value = this._first.value; -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ + return value; + } -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode + first() { + if (this._first != null) { + return this._first.value; + } + } - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; + getArray() { + var node, ref, results; + node = this._first; + results = []; - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + + return results; } - return false; -}); + forEachShift(cb) { + var node; + node = this.shift(); -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public - */ + while (node != null) { + cb(node), node = this.shift(); + } -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); + return void 0; + } -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @public - */ + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } -/** - * Helper function for creating a getter on an object. - * - * @param {Object} obj - * @param {String} name - * @param {Function} getter - * @private - */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); -} + return results; + } +}; +module.exports = DLList; /***/ }), -/***/ 64934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 31914: +/***/ ((module) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module dependencies. - * @private - */ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -var Buffer = (__nccwpck_require__(21867).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var deprecate = __nccwpck_require__(18883)('express'); -var encodeUrl = __nccwpck_require__(16592); -var escapeHtml = __nccwpck_require__(94070); -var http = __nccwpck_require__(13685); -var isAbsolute = (__nccwpck_require__(53561).isAbsolute); -var onFinished = __nccwpck_require__(24694); -var path = __nccwpck_require__(71017); -var statuses = __nccwpck_require__(57415) -var merge = __nccwpck_require__(44429); -var sign = (__nccwpck_require__(61579).sign); -var normalizeType = (__nccwpck_require__(53561).normalizeType); -var normalizeTypes = (__nccwpck_require__(53561).normalizeTypes); -var setCharset = (__nccwpck_require__(53561).setCharset); -var cookie = __nccwpck_require__(93658); -var send = __nccwpck_require__(95287); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = __nccwpck_require__(85931); +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -/** - * Response prototype. - * @public - */ +var Events; +Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; -var res = Object.create(http.ServerResponse.prototype) + if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { + throw new Error("An Emitter already exists for this object"); + } -/** - * Module exports. - * @public - */ - -module.exports = res - -/** - * Module variables. - * @private - */ - -var charsetRegExp = /;\s*charset\s*=/; - -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; -res.status = function status(code) { - this.statusCode = code; - return this; -}; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; -/** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @public - */ + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; + _addListener(name, status, cb) { + var base; -/** - * Send a response. - * - * Examples: - * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * - * @param {string|number|boolean|object|Buffer} body - * @public - */ + if ((base = this._events)[name] == null) { + base[name] = []; + } -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; + this._events[name].push({ + cb, + status + }); - // settings - var app = this.app; + return this.instance; + } - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; + return 0; } } - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } + trigger(name, ...args) { + var _this = this; - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } + return _asyncToGenerator(function* () { + var e, promises; - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); + try { + if (name !== "debug") { + _this.trigger("debug", `Event triggered: ${name}`, args); } - } else { - return this.json(chunk); - } - break; - } - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + if (_this._events[name] == null) { + return; + } - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } + _this._events[name] = _this._events[name].filter(function (listener) { + return listener.status !== "none"; + }); + promises = _this._events[name].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (listener) { + var e, returned; - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + if (listener.status === "none") { + return; + } - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length - } + if (listener.status === "once") { + listener.status = "none"; + } - this.set('Content-Length', len); - } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } + if (typeof (returned != null ? returned.then : void 0) === "function") { + return yield returned; + } else { + return returned; + } + } catch (error) { + e = error; - // freshness - if (req.fresh) this.statusCode = 304; + if (true) { + _this.trigger("error", e); + } - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } + return null; + } + }); - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + return (yield Promise.all(promises)).find(function (x) { + return x != null; + }); + } catch (error) { + e = error; + + if (true) { + _this.trigger("error", e); + } + + return null; + } + })(); } - return this; }; +module.exports = Events; -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ +/***/ }), -res.json = function json(obj) { - var val = obj; +/***/ 49216: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } +"use strict"; - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - return this.send(body); -}; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -res.jsonp = function jsonp(obj) { - var val = obj; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - // allow status / body - if (arguments.length === 2) { - // res.jsonp(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } +var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(29700); +Events = __nccwpck_require__(31914); +RedisConnection = __nccwpck_require__(91400); +IORedisConnection = __nccwpck_require__(58468); +Scripts = __nccwpck_require__(71479); - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; - } +Group = function () { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser.load(this.limiterOptions, this.defaults, this); + this.Events = new Events(this); + this.instances = {}; + this.Bottleneck = __nccwpck_require__(68760); - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); + this._startAutoCleanup(); - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); + this.sharedConnection = this.connection != null; - if (body === undefined) { - // empty argument - body = '' - } else if (typeof body === 'string') { - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029') + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } + } } - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } - return this.send(body); -}; + deleteKey(key = "") { + var _this = this; -/** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); - * - * @param {number} statusCode - * @public - */ + return _asyncToGenerator(function* () { + var deleted, instance; + instance = _this.instances[key]; -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) + if (_this.connection) { + deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); + } - this.statusCode = statusCode; - this.type('txt'); + if (instance != null) { + delete _this.instances[key]; + yield instance.disconnect(); + } - return this.send(body); -}; + return instance != null || deleted > 0; + })(); + } -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public - */ + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } + return results; + } - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } + keys() { + return Object.keys(this.instances); + } - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + clusterKeys() { + var _this2 = this; - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } + return _asyncToGenerator(function* () { + var cursor, end, found, i, k, keys, len, next, start; - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); + if (_this2.connection == null) { + return _this2.Promise.resolve(_this2.keys()); + } - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + keys = []; + cursor = null; + start = `b_${_this2.id}-`.length; + end = "_settings".length; - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + while (cursor !== 0) { + var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.headersSent` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public - */ + var _ref2 = _slicedToArray(_ref, 2); -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; + next = _ref2[0]; + found = _ref2[1]; + cursor = ~~next; - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } - // create file stream - var file = send(req, path, opts); + return keys; + })(); + } - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); + _startAutoCleanup() { + var _this3 = this; - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + var base; + clearInterval(this.interval); + return typeof (base = this.interval = setInterval( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e, k, ref, results, time, v; + time = Date.now(); + ref = _this3.instances; + results = []; -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); + for (k in ref) { + v = ref[k]; -/** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * occurred. Be sure to check `res.headersSent` if you plan to respond. - * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. - * - * This method uses `res.sendFile()`. - * - * @public - */ + try { + if (yield v._store.__groupCheck__(time)) { + results.push(_this3.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null + return results; + }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; + } - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null - } + updateSettings(options = {}) { + parser.overwrite(options, this.defaults, this); + parser.overwrite(options, options, this.limiterOptions); - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] + disconnect(flush = true) { + var ref; + + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; } } + } - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers + ; + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + return Group; +}.call(void 0); - // Resolve the full path for sendFile - var fullPath = resolve(path); +module.exports = Group; - // send file - return this.sendFile(fullPath, opts, done) -}; +/***/ }), -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @public - */ +/***/ 58468: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; +"use strict"; - return this.set('Content-Type', ct); -}; -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'application/json': function () { - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @public - */ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -res.format = function(obj){ - var req = this.req; - var next = req.next; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - var key = keys.length > 0 - ? req.accepts(keys) - : false; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - this.vary("Accept"); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - return this; -}; +var Events, IORedisConnection, Scripts, parser; +parser = __nccwpck_require__(29700); +Events = __nccwpck_require__(31914); +Scripts = __nccwpck_require__(71479); -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ +IORedisConnection = function () { + class IORedisConnection { + constructor(options = {}) { + parser.load(options, this.defaults, this); -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } + if (this.Redis == null) { + this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option. + } - this.set('Content-Disposition', contentDisposition(filename)); + if (this.Events == null) { + this.Events = new Events(this); + } - return this; -}; + this.terminated = false; -/** - * Append additional header `field` with value `val`. - * - * Example: - * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); - * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ + if (this.clusterNodes != null) { + this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + } else if (this.client != null && this.client.duplicate == null) { + this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options); + } else { + if (this.client == null) { + this.client = new this.Redis(this.clientOptions); + } -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; + this.subscriber = this.client.duplicate(); + } - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val] - } + this.limiters = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + this._loadScripts(); - return this.set(field, value); -}; + return { + client: this.client, + subscriber: this.subscriber + }; + }); + } -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); - } + if (client.status === "ready") { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); } - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); + _loadScripts() { + return Scripts.names.forEach(name => { + return this.client.defineCommand(name, { + lua: Scripts.payload(name) + }); + }); } - } - return this; -}; -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public - */ + __runCommand__(cmd) { + var _this = this; -res.get = function(field){ - return this.getHeader(field); -}; + return _asyncToGenerator(function* () { + var _, deleted; -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + yield _this.ready; -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); + var _ref = yield _this.client.pipeline([cmd]).exec(); - return this.cookie(name, '', opts); -}; + var _ref2 = _slicedToArray(_ref, 1); -/** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + var _ref2$ = _slicedToArray(_ref2[0], 2); -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; + _ = _ref2$[0]; + deleted = _ref2$[1]; + return deleted; + })(); + } - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + return this.subscriber.subscribe(channel, () => { + this.limiters[channel] = instance; + return resolve(); + }); + }); + })); + } - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); + __removeLimiter__(instance) { + var _this2 = this; - if (signed) { - val = 's:' + sign(val, secret); - } + return [instance.channel(), instance.channel_client()].forEach( + /*#__PURE__*/ + function () { + var _ref3 = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield _this2.subscriber.unsubscribe(channel); + } - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } + return delete _this2.limiters[channel]; + }); - if (opts.path == null) { - opts.path = '/'; - } + return function (_x) { + return _ref3.apply(this, arguments); + }; + }()); + } - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [keys.length].concat(keys, args, cb); + } - return this; -}; + __scriptFn__(name) { + return this.client[name].bind(this.client); + } -/** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); - * - * @param {String} url - * @return {ServerResponse} for chaining - * @public - */ + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); -res.location = function location(url) { - var loc = url; + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } + + this.limiters = {}; + this.terminated = true; + + if (flush) { + return this.Promise.all([this.client.quit(), this.subscriber.quit()]); + } else { + this.client.disconnect(); + this.subscriber.disconnect(); + return this.Promise.resolve(); + } + } - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; } - // set location - return this.set('Location', encodeUrl(loc)); -}; + ; + IORedisConnection.prototype.datastore = "ioredis"; + IORedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + clusterNodes: null, + client: null, + Promise: Promise, + Events: null + }; + return IORedisConnection; +}.call(void 0); -/** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - * - * @public - */ +module.exports = IORedisConnection; -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; +/***/ }), - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; +/***/ 42448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(29700); +BottleneckError = __nccwpck_require__(72360); +Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; } + + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; } - // Set location header - address = this.location(address).get('Location'); + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, + _randomIndex() { + return Math.random().toString(36).slice(2); + } - default: function(){ - body = ''; + doDrop({ + error, + message = "This job has been dropped by Bottleneck" + } = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError(message)); + } + + this.Events.trigger("dropped", { + args: this.args, + options: this.options, + task: this.task, + promise: this.promise + }); + return true; + } else { + return false; } - }); + } - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); + if (!(status === expected || expected === "DONE" && status === null)) { + throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } } -}; -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public - */ + doReceive() { + this._states.start(this.options.id); -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; + return this.Events.trigger("received", { + args: this.args, + options: this.options + }); } - vary(this, field); + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); - return this; -}; + this._states.next(this.options.id); -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @public - */ + return this.Events.trigger("queued", { + args: this.args, + options: this.options, + reachedHWM, + blocked + }); + } -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + + return this.Events.trigger("scheduled", { + args: this.args, + options: this.options + }); } - // merge res.locals - opts._locals = self.locals; + doExecute(chained, clearGlobalState, run, free) { + var _this = this; - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; + return _asyncToGenerator(function* () { + var error, eventInfo, passed; - // render - app.render(view, opts, done); -}; + if (_this.retryCount === 0) { + _this._assertStatus("RUNNING"); -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; + _this._states.next(_this.options.id); + } else { + _this._assertStatus("EXECUTING"); + } - // request aborted - function onaborted() { - if (done) return; - done = true; + eventInfo = { + args: _this.args, + options: _this.options, + retryCount: _this.retryCount + }; - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } + _this.Events.trigger("executing", eventInfo); - // directory - function ondirectory() { - if (done) return; - done = true; + try { + passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } + if (clearGlobalState()) { + _this.doDone(eventInfo); - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } + yield free(_this.options, eventInfo); - // ended - function onend() { - if (done) return; - done = true; - callback(); - } + _this._assertStatus("DONE"); - // file - function onfile() { - streaming = false; + return _this._resolve(passed); + } + } catch (error1) { + error = error1; + return _this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + })(); } - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + doExpire(clearGlobalState, run, free) { + var error, eventInfo; - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } - if (done) return; - done = true; - callback(); - }); - } + this._assertStatus("EXECUTING"); - // streaming - function onstream() { - streaming = true; + eventInfo = { + args: this.args, + options: this.options, + retryCount: this.retryCount + }; + error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); } - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); + _onFailure(error, eventInfo, clearGlobalState, run, free) { + var _this2 = this; - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); + return _asyncToGenerator(function* () { + var retry, retryAfter; - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } + if (clearGlobalState()) { + retry = yield _this2.Events.trigger("failed", error, eventInfo); - // pipe - file.pipe(res); -} + if (retry != null) { + retryAfter = ~~retry; -/** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. - * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} - * @private - */ + _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); + _this2.retryCount++; + return run(retryAfter); + } else { + _this2.doDone(eventInfo); - if (escape && typeof json === 'string') { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c + yield free(_this2.options, eventInfo); + + _this2._assertStatus("DONE"); + + return _this2._reject(error); + } } - }) + })(); } - return json -} + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + + this._states.next(this.options.id); + + return this.Events.trigger("done", eventInfo); + } +}; +module.exports = Job; /***/ }), -/***/ 24963: +/***/ 37099: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -/** - * Module dependencies. - * @private - */ +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -var Route = __nccwpck_require__(23699); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); -var mixin = __nccwpck_require__(44429); -var debug = __nccwpck_require__(38237)('express:router'); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var parseUrl = __nccwpck_require__(89808); -var setPrototypeOf = __nccwpck_require__(40414) +var BottleneckError, LocalDatastore, parser; +parser = __nccwpck_require__(29700); +BottleneckError = __nccwpck_require__(72360); +LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; -/** - * Module variables. - * @private - */ + this._startHeartbeat(); + } -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; + _startHeartbeat() { + var base; -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function - * @public - */ + if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { + return typeof (base = this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); -var proto = module.exports = function(options) { - var opts = options || {}; + if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - function router(req, res, next) { - router.handle(req, res, next); - } + this.instance._drainAll(this.computeCapacity()); + } - // mixin Router class functions - setPrototypeOf(router, proto) + if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + var _this$storeOptions = this.storeOptions; + amount = _this$storeOptions.reservoirIncreaseAmount; + maximum = _this$storeOptions.reservoirIncreaseMaximum; + reservoir = _this$storeOptions.reservoir; + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; - - return router; -}; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -/** - * Map the given param placeholder `name`(s) to the given callback. - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); - * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ + __publish__(message) { + var _this = this; -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); } - // apply param functions - var params = this._params; - var len = params.length; - var ret; + __disconnect__(flush) { + var _this2 = this; - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); } - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); + }); } - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; } - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Dispatch a req, res into the router. - * @private - */ + __updateSettings__(options) { + var _this3 = this; -proto.handle = function handle(req, res, out) { - var self = this; + return _asyncToGenerator(function* () { + yield _this3.yieldLoop(); + parser.overwrite(options, options, _this3.storeOptions); - debug('dispatching %s %s', req.method, req.url); + _this3._startHeartbeat(); - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; + _this3.instance._drainAll(_this3.computeCapacity()); - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; + return true; + })(); + } - // middleware and routes - var stack = self.stack; + __running__() { + var _this4 = this; - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); + } - // setup next layer - req.next = next; + __queued__() { + var _this5 = this; - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); } - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; - - next(); + __done__() { + var _this6 = this; - function next(err) { - var layerError = err === 'route' - ? null - : err; + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); + } - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } + __groupCheck__(time) { + var _this7 = this; - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions2 = this.storeOptions; + maxConcurrent = _this$storeOptions2.maxConcurrent; + reservoir = _this$storeOptions2.reservoir; - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; + if (maxConcurrent != null && reservoir != null) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; } + } - // get pathname of request - var path = getPathname(req); + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } - if (path == null) { - return done(layerError); - } + __incrementReservoir__(incr) { + var _this8 = this; - // find next matching layer - var layer; - var match; - var route; + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; + _this8.instance._drainAll(_this8.computeCapacity()); - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } + return reservoir; + })(); + } - if (match !== true) { - continue; - } + __currentReservoir__() { + var _this9 = this; - if (!route) { - // process non-route handlers normally - continue; - } + return _asyncToGenerator(function* () { + yield _this9.yieldLoop(); + return _this9.storeOptions.reservoir; + })(); + } - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } + isBlocked(now) { + return this._unblockTime >= now; + } - var method = req.method; - var has_method = route._handles_method(method); + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; + } - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } + __check__(weight) { + var _this10 = this; - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } + return _asyncToGenerator(function* () { + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); + } - // no match - if (match !== true) { - return done(layerError); - } + __register__(index, weight, expiration) { + var _this11 = this; - // store route for dispatch on change - if (route) { - req.route = route; - } + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; + } - if (route) { - return layer.handle_request(req, res, next); + wait = Math.max(_this11._nextRequest - now, 0); + _this11._nextRequest = now + wait + _this11.storeOptions.minTime; + return { + success: true, + wait, + reservoir: _this11.storeOptions.reservoir + }; + } else { + return { + success: false + }; } + })(); + } - trim_prefix(layer, layerError, layerPath, path); - }); + strategyIsBlock() { + return this.storeOptions.strategy === 3; } - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path is a prefix match - if (layerPath !== path.substr(0, layerPath.length)) { - next(layerError) - return + __submit__(queueLength, weight) { + var _this12 = this; + + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); + + if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); } - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) + now = Date.now(); + reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); + blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); + if (blocked) { + _this12._unblockTime = now + _this12.computePenalty(); + _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; + _this12.instance._dropAllQueued(); } - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); + } - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + __free__(index, weight) { + var _this13 = this; - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; + + _this13.instance._drainAll(_this13.computeCapacity()); + + return { + running: _this13._running + }; + })(); } + }; +module.exports = LocalDatastore; -/** - * Process any parameters for the layer. - * @private - */ +/***/ }), -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; +/***/ 91363: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // captured parameters from the layer, keys and values - var keys = layer.keys; +"use strict"; - // fast track - if (!keys || keys.length === 0) { - return done(); - } - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; +var DLList, Events, Queues; +DLList = __nccwpck_require__(55327); +Events = __nccwpck_require__(31914); +Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events(this); + this._length = 0; - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } + this._lists = function () { + var j, ref, results; + results = []; - if (i >= keys.length ) { - return done(); - } + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList(() => { + return this.incr(); + }, () => { + return this.decr(); + })); + } - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; + return results; + }.call(this); + } - if (paramVal === undefined || !paramCallbacks) { - return param(); + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); } + } - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; - - // next param - return param(paramCalled.error); + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); } + } - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; + push(job) { + return this._lists[job.options.priority].push(job); + } - paramCallback(); + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; + shiftAll(fn) { + return this._lists.forEach(function (list) { + return list.forEachShift(fn); + }); + } - // store updated value - paramCalled.value = req.params[key.name]; + getFirst(arr = this._lists) { + var j, len, list; - if (err) { - // store error - paramCalled.error = err; - param(err); - return; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + + if (list.length > 0) { + return list; + } } - if (!fn) return param(); + return []; + } - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); } - param(); }; +module.exports = Queues; -/** - * Use the given middleware function, with optional path, defaulting to "/". - * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. - * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. - * - * @public - */ - -proto.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var callbacks = flatten(slice.call(arguments, offset)); - - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } - - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; - - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) - } +/***/ }), - // add the middleware - debug('use %o %s', path, fn.name || '') +/***/ 91400: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); +"use strict"; - layer.route = undefined; - this.stack.push(layer); - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - return this; -}; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -/** - * Create a new Route for the given path. - * - * Each route contains a separate middleware stack and VERB handlers. - * - * See the Route api documentation for details on adding handlers - * and middleware to routes. - * - * @param {String} path - * @return {Route} - * @public - */ +var Events, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(29700); +Events = __nccwpck_require__(31914); +Scripts = __nccwpck_require__(71479); -proto.route = function route(path) { - var route = new Route(path); +RedisConnection = function () { + class RedisConnection { + constructor(options = {}) { + parser.load(options, this.defaults, this); - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); + if (this.Redis == null) { + this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option. + } - layer.route = route; + if (this.Events == null) { + this.Events = new Events(this); + } - this.stack.push(layer); - return route; -}; + this.terminated = false; -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + if (this.client == null) { + this.client = this.Redis.createClient(this.clientOptions); + } -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); + this.subscriber = this.client.duplicate(); + this.limiters = {}; + this.shas = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + return this._loadScripts(); + }).then(() => { + return { + client: this.client, + subscriber: this.subscriber + }; + }); } - } -} -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } -} + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') + if (client.ready) { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} + _loadScript(name) { + return new this.Promise((resolve, reject) => { + var payload; + payload = Scripts.payload(name); + return this.client.multi([["script", "load", payload]]).exec((err, replies) => { + if (err != null) { + return reject(err); + } -// get type for error message -function gettype(obj) { - var type = typeof obj; + this.shas[name] = replies[0]; + return resolve(replies[0]); + }); + }); + } - if (type !== 'object') { - return type; - } + _loadScripts() { + return this.Promise.all(Scripts.names.map(k => { + return this._loadScript(k); + })); + } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} + __runCommand__(cmd) { + var _this = this; -/** - * Match path to a layer. - * - * @param {Layer} layer - * @param {string} path - * @private - */ + return _asyncToGenerator(function* () { + yield _this.ready; + return new _this.Promise((resolve, reject) => { + return _this.client.multi([cmd]).exec_atomic(function (err, replies) { + if (err != null) { + return reject(err); + } else { + return resolve(replies[0]); + } + }); + }); + })(); + } -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; - } -} + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + var handler; -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } + handler = chan => { + if (chan === channel) { + this.subscriber.removeListener("subscribe", handler); + this.limiters[channel] = instance; + return resolve(); + } + }; - // make copy of parent for base - var obj = mixin({}, parent); + this.subscriber.on("subscribe", handler); + return this.subscriber.subscribe(channel); + }); + })); + } - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); - } + __removeLimiter__(instance) { + var _this2 = this; - var i = 0; - var o = 0; + return this.Promise.all([instance.channel(), instance.channel_client()].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield new _this2.Promise((resolve, reject) => { + return _this2.subscriber.unsubscribe(channel, function (err, chan) { + if (err != null) { + return reject(err); + } - // determine numeric gaps - while (i in params) { - i++; - } + if (chan === channel) { + return resolve(); + } + }); + }); + } - while (o in parent) { - o++; - } + return delete _this2.limiters[channel]; + }); - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); + } - // create holes for the merge when necessary - if (i < o) { - delete params[i]; + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [this.shas[name], keys.length].concat(keys, args, cb); } - } - return mixin(obj, params); -} + __scriptFn__(name) { + return this.client.evalsha.bind(this.client); + } -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; - } + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; + this.limiters = {}; + this.terminated = true; + this.client.end(flush); + this.subscriber.end(flush); + return this.Promise.resolve(); } - return fn.apply(this, arguments); - }; -} - -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); } -} - -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); - - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; - } - fn.apply(this, args); + ; + RedisConnection.prototype.datastore = "redis"; + RedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + client: null, + Promise: Promise, + Events: null }; -} + return RedisConnection; +}.call(void 0); +module.exports = RedisConnection; /***/ }), -/***/ 25624: +/***/ 41827: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -/** - * Module dependencies. - * @private - */ +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(38237)('express:router:layer'); +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -/** - * Module variables. - * @private - */ +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -var hasOwnProperty = Object.prototype.hasOwnProperty; +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -/** - * Module exports. - * @public - */ +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -module.exports = Layer; +var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; +parser = __nccwpck_require__(29700); +BottleneckError = __nccwpck_require__(72360); +RedisConnection = __nccwpck_require__(91400); +IORedisConnection = __nccwpck_require__(58468); +RedisDatastore = class RedisDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.originalId = this.instance.id; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this.clients = {}; + this.capacityPriorityCounters = {}; + this.sharedConnection = this.connection != null; -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); - } + if (this.connection == null) { + this.connection = this.instance.datastore === "redis" ? new RedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + Promise: this.Promise, + Events: this.instance.Events + }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + clusterNodes: this.clusterNodes, + Promise: this.Promise, + Events: this.instance.Events + }) : void 0; + } - debug('new %o', path) - var opts = options || {}; + this.instance.connection = this.connection; + this.instance.datastore = this.connection.datastore; + this.ready = this.connection.ready.then(clients => { + this.clients = clients; + return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); + }).then(() => { + return this.connection.__addLimiter__(this.instance); + }).then(() => { + return this.runScript("register_client", [this.instance.queued()]); + }).then(() => { + var base; - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); + if (typeof (base = this.heartbeat = setInterval(() => { + return this.runScript("heartbeat", []).catch(e => { + return this.instance.Events.trigger("error", e); + }); + }, this.heartbeatInterval)).unref === "function") { + base.unref(); + } - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false -} + return this.clients; + }); + } -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ + __publish__(message) { + var _this = this; -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; + return _asyncToGenerator(function* () { + var client; - if (fn.length !== 4) { - // not a standard error handler - return next(error); - } + var _ref = yield _this.ready; - try { - fn(error, req, res, next); - } catch (err) { - next(err); + client = _ref.client; + return client.publish(_this.instance.channel(), `message:${message.toString()}`); + })(); } -}; -/** - * Handle the request for the layer. - * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ + onMessage(channel, message) { + var _this2 = this; -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; + return _asyncToGenerator(function* () { + var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; - if (fn.length > 3) { - // not a standard request handler - return next(); - } + try { + pos = message.indexOf(":"); + var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; + type = _ref2[0]; + data = _ref2[1]; - try { - fn(req, res, next); - } catch (err) { - next(err); - } -}; + if (type === "capacity") { + return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); + } else if (type === "capacity-priority") { + var _data$split = data.split(":"); -/** - * Check if this route matches `path`, if so - * populate `.params`. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -Layer.prototype.match = function match(path) { - var match - - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } - - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true - } - - // match the path - match = this.regexp.exec(path) - } - - if (!match) { - this.params = undefined; - this.path = undefined; - return false; - } - - // store values - this.params = {}; - this.path = match[0] + var _data$split2 = _slicedToArray(_data$split, 3); - var keys = this.keys; - var params = this.params; + rawCapacity = _data$split2[0]; + priorityClient = _data$split2[1]; + counter = _data$split2[2]; + capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) + if (priorityClient === _this2.clientId) { + drained = yield _this2.instance._drainAll(capacity); + newCapacity = capacity != null ? capacity - (drained || 0) : ""; + return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); + } else if (priorityClient === "") { + clearTimeout(_this2.capacityPriorityCounters[counter]); + delete _this2.capacityPriorityCounters[counter]; + return _this2.instance._drainAll(capacity); + } else { + return _this2.capacityPriorityCounters[counter] = setTimeout( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e; - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } + try { + delete _this2.capacityPriorityCounters[counter]; + yield _this2.runScript("blacklist_client", [priorityClient]); + return yield _this2.instance._drainAll(capacity); + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + }), 1000); + } + } else if (type === "message") { + return _this2.instance.Events.trigger("message", data); + } else if (type === "blocked") { + return yield _this2.instance._dropAllQueued(); + } + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + })(); } - return true; -}; - -/** - * Decode param value. - * - * @param {string} val - * @return {string} - * @private - */ - -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } + __disconnect__(flush) { + clearInterval(this.heartbeat); - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; + if (this.sharedConnection) { + return this.connection.__removeLimiter__(this.instance); + } else { + return this.connection.disconnect(flush); } - - throw err; } -} - - -/***/ }), - -/***/ 23699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - + runScript(name, args) { + var _this3 = this; -/** - * Module dependencies. - * @private - */ - -var debug = __nccwpck_require__(38237)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); + return _asyncToGenerator(function* () { + if (!(name === "init" || name === "register_client")) { + yield _this3.ready; + } -/** - * Module variables. - * @private - */ + return new _this3.Promise((resolve, reject) => { + var all_args, arr; + all_args = [Date.now(), _this3.clientId].concat(args); -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; + _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); -/** - * Module exports. - * @public - */ + arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { + if (err != null) { + return reject(err); + } -module.exports = Route; + return resolve(replies); + }); + return _this3.connection.__scriptFn__(name)(...arr); + }).catch(e => { + if (e.message === "SETTINGS_KEY_NOT_FOUND") { + if (name === "heartbeat") { + return _this3.Promise.resolve(); + } else { + return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { + return _this3.runScript(name, args); + }); + } + } else if (e.message === "UNKNOWN_CLIENT") { + return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { + return _this3.runScript(name, args); + }); + } else { + return _this3.Promise.reject(e); + } + }); + })(); + } -/** - * Initialize `Route` with the given `path`, - * - * @param {String} path - * @public - */ + prepareArray(arr) { + var i, len, results, x; + results = []; -function Route(path) { - this.path = path; - this.stack = []; + for (i = 0, len = arr.length; i < len; i++) { + x = arr[i]; + results.push(x != null ? x.toString() : ""); + } - debug('new %o', path) + return results; + } - // route handlers for various http methods - this.methods = {}; -} + prepareObject(obj) { + var arr, k, v; + arr = []; -/** - * Determine if the route handles a given method. - * @private - */ + for (k in obj) { + v = obj[k]; + arr.push(k, v != null ? v.toString() : ""); + } -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; + return arr; } - var name = method.toLowerCase(); + prepareInitSettings(clear) { + var args; + args = this.prepareObject(Object.assign({}, this.storeOptions, { + id: this.originalId, + version: this.instance.version, + groupTimeout: this.timeout, + clientTimeout: this.clientTimeout + })); + args.unshift(clear ? 1 : 0, this.instance.version); + return args; + } - if (name === 'head' && !this.methods['head']) { - name = 'get'; + convertBool(b) { + return !!b; } - return Boolean(this.methods[name]); -}; + __updateSettings__(options) { + var _this4 = this; -/** - * @return {Array} supported HTTP methods - * @private - */ + return _asyncToGenerator(function* () { + yield _this4.runScript("update_settings", _this4.prepareObject(options)); + return parser.overwrite(options, options, _this4.storeOptions); + })(); + } -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); + __running__() { + return this.runScript("running", []); + } - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); + __queued__() { + return this.runScript("queued", []); } - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); + __done__() { + return this.runScript("done", []); } - return methods; -}; + __groupCheck__() { + var _this5 = this; -/** - * dispatch req, res into this route - * @private - */ + return _asyncToGenerator(function* () { + return _this5.convertBool((yield _this5.runScript("group_check", []))); + })(); + } -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); + __incrementReservoir__(incr) { + return this.runScript("increment_reservoir", [incr]); } - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; + __currentReservoir__() { + return this.runScript("current_reservoir", []); } - req.route = this; + __check__(weight) { + var _this6 = this; - next(); + return _asyncToGenerator(function* () { + return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); + })(); + } - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } + __register__(index, weight, expiration) { + var _this7 = this; - // signal to exit router - if (err && err === 'router') { - return done(err) - } + return _asyncToGenerator(function* () { + var reservoir, success, wait; - var layer = stack[idx++]; - if (!layer) { - return done(err); - } + var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); - if (layer.method && layer.method !== method) { - return next(err); - } + var _ref5 = _slicedToArray(_ref4, 3); - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } + success = _ref5[0]; + wait = _ref5[1]; + reservoir = _ref5[2]; + return { + success: _this7.convertBool(success), + wait, + reservoir + }; + })(); } -}; - -/** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); - * - * @param {function} handler - * @return {Route} for chaining - * @api public - */ -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + __submit__(queueLength, weight) { + var _this8 = this; - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } + return _asyncToGenerator(function* () { + var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; - var layer = Layer('/', {}, handle); - layer.method = undefined; + try { + var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); - this.methods._all = true; - this.stack.push(layer); - } + var _ref7 = _slicedToArray(_ref6, 3); - return this; -}; + reachedHWM = _ref7[0]; + blocked = _ref7[1]; + strategy = _ref7[2]; + return { + reachedHWM: _this8.convertBool(reachedHWM), + blocked: _this8.convertBool(blocked), + strategy + }; + } catch (error) { + e = error; -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); + if (e.message.indexOf("OVERWEIGHT") === 0) { + var _e$message$split = e.message.split(":"); - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; + var _e$message$split2 = _slicedToArray(_e$message$split, 3); - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); + overweight = _e$message$split2[0]; + weight = _e$message$split2[1]; + maxConcurrent = _e$message$split2[2]; + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); + } else { + throw e; + } } + })(); + } - debug('%s %o', method, this.path) - - var layer = Layer('/', {}, handle); - layer.method = method; - - this.methods[method] = true; - this.stack.push(layer); - } + __free__(index, weight) { + var _this9 = this; - return this; - }; -}); + return _asyncToGenerator(function* () { + var running; + running = yield _this9.runScript("free", _this9.prepareArray([index])); + return { + running + }; + })(); + } +}; +module.exports = RedisDatastore; /***/ }), -/***/ 53561: +/***/ 71479: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @api private - */ - -var Buffer = (__nccwpck_require__(21867).Buffer) -var contentDisposition = __nccwpck_require__(53921); -var contentType = __nccwpck_require__(99915); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var mime = (__nccwpck_require__(95287).mime); -var etag = __nccwpck_require__(69972); -var proxyaddr = __nccwpck_require__(80140); -var qs = __nccwpck_require__(22760); -var querystring = __nccwpck_require__(63477); -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.etag = createETagGenerator({ weak: false }) - -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.wetag = createETagGenerator({ weak: true }) - -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +var headers, lua, templates; +lua = __nccwpck_require__(46495); +headers = { + refs: lua["refs.lua"], + validate_keys: lua["validate_keys.lua"], + validate_client: lua["validate_client.lua"], + refresh_expiration: lua["refresh_expiration.lua"], + process_tick: lua["process_tick.lua"], + conditions_check: lua["conditions_check.lua"], + get_time: lua["get_time.lua"] }; -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); - -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ - -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; +exports.allKeys = function (id) { + return [ + /* + HASH + */ + `b_${id}_settings`, + /* + HASH + job index -> weight + */ + `b_${id}_job_weights`, + /* + ZSET + job index -> expiration + */ + `b_${id}_job_expirations`, + /* + HASH + job index -> client + */ + `b_${id}_job_clients`, + /* + ZSET + client -> sum running + */ + `b_${id}_client_running`, + /* + HASH + client -> num queued + */ + `b_${id}_client_num_queued`, + /* + ZSET + client -> last job registered + */ + `b_${id}_client_last_registered`, + /* + ZSET + client -> last seen + */ + `b_${id}_client_last_seen`]; }; -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ - -exports.normalizeTypes = function(types){ - var ret = []; - - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); +templates = { + init: { + keys: exports.allKeys, + headers: ["process_tick"], + refresh_expiration: true, + code: lua["init.lua"] + }, + group_check: { + keys: exports.allKeys, + headers: [], + refresh_expiration: false, + code: lua["group_check.lua"] + }, + register_client: { + keys: exports.allKeys, + headers: ["validate_keys"], + refresh_expiration: false, + code: lua["register_client.lua"] + }, + blacklist_client: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["blacklist_client.lua"] + }, + heartbeat: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["heartbeat.lua"] + }, + update_settings: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["update_settings.lua"] + }, + running: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["running.lua"] + }, + queued: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["queued.lua"] + }, + done: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["done.lua"] + }, + check: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: false, + code: lua["check.lua"] + }, + submit: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["submit.lua"] + }, + register: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["register.lua"] + }, + free: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["free.lua"] + }, + current_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["current_reservoir.lua"] + }, + increment_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["increment_reservoir.lua"] } +}; +exports.names = Object.keys(templates); - return ret; +exports.keys = function (name, id) { + return templates[name].keys(id); }; -/** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private - */ +exports.payload = function (name) { + var template; + template = templates[name]; + return Array.prototype.concat(headers.refs, template.headers.map(function (h) { + return headers[h]; + }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); +}; -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); +/***/ }), -/** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private - */ +/***/ 5685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; +"use strict"; - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; + +var BottleneckError, States; +BottleneckError = __nccwpck_require__(72360); +States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function () { + return 0; + }); + } + + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + + if (current != null && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; } } - return ret; -} + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ + remove(id) { + var current; + current = this._jobs[id]; -exports.compileETag = function(val) { - var fn; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } - if (typeof val === 'function') { - return val; + return current != null; } - switch (val) { - case true: - case 'weak': - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; } - return fn; -} + statusJobs(status) { + var k, pos, ref, results, v; -/** - * Compile "query parser" value to function. - * - * @param {String|Function} val - * @return {Function} - * @api private - */ + if (status != null) { + pos = this.status.indexOf(status); -exports.compileQueryParser = function compileQueryParser(val) { - var fn; + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } - if (typeof val === 'function') { - return val; + ref = this._jobs; + results = []; + + for (k in ref) { + v = ref[k]; + + if (v === pos) { + results.push(k); + } + } + + return results; + } else { + return Object.keys(this._jobs); + } } - switch (val) { - case true: - case 'simple': - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); } - return fn; -} +}; +module.exports = States; -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ +/***/ }), -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; +/***/ 39216: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (val === true) { - // Support plain true/false - return function(){ return true }; - } +"use strict"; - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(',') - .map(function (v) { return v.trim() }) - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - return proxyaddr.compile(val || []); -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ +var DLList, Sync; +DLList = __nccwpck_require__(55327); +Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList(); + } -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; + isEmpty() { + return this._queue.length === 0; } - // parse type - var parsed = contentType.parse(type); + _tryToRun() { + var _this = this; - // set charset - parsed.parameters.charset = charset; + return _asyncToGenerator(function* () { + var args, cb, error, reject, resolve, returned, task; - // format type - return contentType.format(parsed); -}; + if (_this._running < 1 && _this._queue.length > 0) { + _this._running++; -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ + var _this$_queue$shift = _this._queue.shift(); -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body + task = _this$_queue$shift.task; + args = _this$_queue$shift.args; + resolve = _this$_queue$shift.resolve; + reject = _this$_queue$shift.reject; + cb = yield _asyncToGenerator(function* () { + try { + returned = yield task(...args); + return function () { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function () { + return reject(error); + }; + } + })(); + _this._running--; - return etag(buf, options) + _this._tryToRun(); + + return cb(); + } + })(); } -} -/** - * Parse an extended query string with qs. - * - * @return {Object} - * @private - */ + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function (_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); -} + this._queue.push({ + task, + args, + resolve, + reject + }); -/** - * Return new empty object. - * - * @return {Object} - * @api private - */ + this._tryToRun(); -function newObject() { - return {}; -} + return promise; + } +}; +module.exports = Sync; /***/ }), -/***/ 99209: +/***/ 62203: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = __nccwpck_require__(68760); -/** - * Module dependencies. - * @private - */ +/***/ }), -var debug = __nccwpck_require__(38237)('express:view'); -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); +/***/ 29700: +/***/ ((__unused_webpack_module, exports) => { -/** - * Module variables. - * @private - */ +"use strict"; -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; -/** - * Module exports. - * @public - */ +exports.load = function (received, defaults, onto = {}) { + var k, ref, v; -module.exports = View; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } -/** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup - * - * @param {string} name - * @param {object} options - * @public - */ + return onto; +}; -function View(name, options) { - var opts = options || {}; +exports.overwrite = function (received, defaults, onto = {}) { + var k, v; - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; + for (k in received) { + v = received[k]; - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); + if (defaults[k] !== void 0) { + onto[k] = v; + } } - var fileName = name; + return onto; +}; - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; +/***/ }), - fileName += this.ext; - } +/***/ 63251: +/***/ (function(module) { - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; - // default engine export - var fn = require(mod).__express + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } - opts.engines[this.ext] = fn - } + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; - // store loaded engine - this.engine = opts.engines[this.ext]; + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; - // lookup path - this.path = this.lookup(fileName); -} + var parser = { + load: load, + overwrite: overwrite + }; -/** - * Lookup view by the given `name` - * - * @param {string} name - * @private - */ + var DLList; -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } - debug('lookup "%s"', name); + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); + first() { + if (this._first != null) { + return this._first.value; + } + } - // resolve the file - path = this.resolve(dir, file); - } + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - return path; -}; + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } -/** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private - */ + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; + }; -/** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file - * @private - */ + var DLList_1 = DLList; -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; + var Events; - // . - var path = join(dir, file); - var stat = tryStat(path); + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - if (stat && stat.isFile()) { - return path; - } + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } - if (stat && stat.isFile()) { - return path; - } -}; + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } -/** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private - */ + }; -function tryStat(path) { - debug('stat "%s"', path); + var Events_1 = Events; - try { - return fs.statSync(path); - } catch (e) { - return undefined; - } -} + var DLList$1, Events$1, Queues; + DLList$1 = DLList_1; -/***/ }), + Events$1 = Events_1; -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } -"use strict"; + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } -const validator = __nccwpck_require__(74174) -const parse = __nccwpck_require__(96214) -const redactor = __nccwpck_require__(17333) -const restorer = __nccwpck_require__(98806) -const { groupRedact, nestedRedact } = __nccwpck_require__(54865) -const state = __nccwpck_require__(41012) -const rx = __nccwpck_require__(9158) -const validate = validator() -const noop = (o) => o -noop.restore = noop + push(job) { + return this._lists[job.options.priority].push(job); + } -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } -module.exports = fastRedact + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } -function fastRedact (opts = {}) { - const paths = Array.from(new Set(opts.paths || [])) - const serialize = 'serialize' in opts ? ( - opts.serialize === false ? opts.serialize - : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) - ) : JSON.stringify - const remove = opts.remove - if (remove === true && serialize !== JSON.stringify) { - throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') - } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - if (paths.length === 0) return serialize || noop + }; - validate({ paths, serialize, censor }) + var Queues_1 = Queues; - const { wildcards, wcLen, secret } = parse({ paths, censor }) + var BottleneckError; - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true + BottleneckError = class BottleneckError extends Error {}; - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) -} + var BottleneckError_1 = BottleneckError; + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; -/***/ }), + NUM_PRIORITIES = 10; -/***/ 54865: -/***/ ((module) => { + DEFAULT_PRIORITY = 5; -"use strict"; + parser$1 = parser; + BottleneckError$1 = BottleneckError_1; -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } -function groupRestore ({ keys, values, target }) { - if (target == null) return - const length = keys.length - for (var i = 0; i < length; i++) { - const k = keys[i] - target[k] = values[i] - } -} + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } -function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return { keys: null, values: null, target: null, flat: true } - const keys = Object.keys(target) - const keysLength = keys.length - const pathLength = path.length - const pathWithKey = censorFctTakesPath ? [...path] : undefined - const values = new Array(keysLength) + _randomIndex() { + return Math.random().toString(36).slice(2); + } - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } - } - return { keys, values, target, flat: true } -} + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } -function nestedRestore (arr) { - const length = arr.length - for (var i = 0; i < length; i++) { - const { key, target, value } = arr[i] - if (has(target, key)) { - target[key] = value - } - /* istanbul ignore else */ - if (typeof target === 'object') { - const targetKeys = Object.keys(target) - for (var j = 0; j < targetKeys.length; j++) { - const tKey = targetKeys[j] - const subTarget = target[tKey] - if (has(subTarget, key)) { - subTarget[key] = value - } - } - } - } -} + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } -function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return - const keys = Object.keys(target) - const keysLength = keys.length - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - const { value, parent, exists } = - specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } - } - return store -} + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } -function has (obj, prop) { - return obj !== undefined && obj !== null - ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop)) - : false -} + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } -function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { - const afterPathLen = afterPath.length - const lastPathIndex = afterPathLen - 1 - const originalKey = k - var i = -1 - var n - var nv - var ov - var oov = null - var exists = true - var wc = null - ov = n = o[k] - if (typeof n !== 'object') return { value: null, parent: null, exists } - while (n != null && ++i < afterPathLen) { - k = afterPath[i] - oov = ov - if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) { - exists = false - break - } - if (k === '*') { - wc = k - if (i !== lastPathIndex) { - continue - } - } - if (wc) { - const wcKeys = Object.keys(n) - for (var j = 0; j < wcKeys.length; j++) { - const wck = wcKeys[j] - const wcov = n[wck] - const kIsWc = k === '*' - if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) { - if (kIsWc) { - ov = wcov - } else { - ov = wcov[k] - } - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - if (kIsWc) { - n[wck] = nv - } else { - wcov[k] = (nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov) ? wcov[k] : nv - } - } - } - wc = null - } else { - ov = n[k] - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv - n = n[k] - } - if (typeof n !== 'object') break - } - return { value: ov, parent: oov, exists } -} + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } -function get (o, p) { - var i = -1 - var l = p.length - var n = o - while (n != null && ++i < l) { - n = n[p[i]] - } - return n -} + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } -/***/ }), + }; -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var Job_1 = Job; -"use strict"; + var BottleneckError$2, LocalDatastore, parser$2; + parser$2 = parser; -const rx = __nccwpck_require__(9158) + BottleneckError$2 = BottleneckError_1; -module.exports = parse + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } -function parse ({ paths }) { - const wildcards = [] - var wcLen = 0 - const secret = paths.reduce(function (o, strPath, ix) { - var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) - const leadingBracket = strPath[0] === '[' - path = path.map((p) => { - if (p[0] === '[') return p.substr(1, p.length - 2) - else return p - }) - const star = path.indexOf('*') - if (star > -1) { - const before = path.slice(0, star) - const beforeStr = before.join('.') - const after = path.slice(star + 1, path.length) - const nested = after.length > 0 - wcLen++ - wildcards.push({ - before, - beforeStr, - after, - nested - }) - } else { - o[strPath] = { - path: path, - val: undefined, - precensored: false, - circle: '', - escPath: JSON.stringify(strPath), - leadingBracket: leadingBracket - } - } - return o - }, {}) + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } - return { wildcards, wcLen, secret } -} + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } -/***/ }), + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -"use strict"; + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } + async __running__() { + await this.yieldLoop(); + return this._running; + } -const rx = __nccwpck_require__(9158) + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -module.exports = redactor + async __done__() { + await this.yieldLoop(); + return this._done; + } -function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { - /* eslint-disable-next-line */ - const redact = Function('o', ` - if (typeof o !== 'object' || o == null) { - ${strictImpl(strict, serialize)} - } - const { censor, secret } = this - ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} - this.compileRestore() - ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} - ${resultTmpl(serialize)} - `).bind(state) + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } - if (serialize === false) { - redact.restore = (o) => state.restore(o) - } + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } - return redact -} + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -function redactTmpl (secret, isCensorFct, censorFctTakesPath) { - return Object.keys(secret).map((path) => { - const { escPath, leadingBracket, path: arrPath } = secret[path] - const skip = leadingBracket ? 1 : 0 - const delim = leadingBracket ? '' : '.' - const hops = [] - var match - while ((match = rx.exec(path)) !== null) { - const [ , ix ] = match - const { index, input } = match - if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) - } - var existence = hops.map((p) => `o${delim}${p}`).join(' && ') - if (existence.length === 0) existence += `o${delim}${path} != null` - else existence += ` && o${delim}${path} != null` + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` + isBlocked(now) { + return this._unblockTime >= now; + } - return ` - if (${existence}) { - const val = o${delim}${path} - if (val === censor) { - secret[${escPath}].precensored = true - } else { - secret[${escPath}].val = val - o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} - ${circularDetection} - } - } - ` - }).join('\n') -} + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } -function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { - return hasWildcards === true ? ` - { - const { wildcards, wcLen, groupRedact, nestedRedact } = this - for (var i = 0; i < wcLen; i++) { - const { before, beforeStr, after, nested } = wildcards[i] - if (nested === true) { - secret[beforeStr] = secret[beforeStr] || [] - nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) - } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) - } - } - ` : '' -} + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` -} + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } -/***/ }), + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + }; -"use strict"; + var LocalDatastore_1 = LocalDatastore; + var BottleneckError$3, States; -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) + BottleneckError$3 = BottleneckError_1; -module.exports = restorer + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } -function restorer ({ secret, wcLen }) { - return function compileRestore () { - if (this.restore) return - const paths = Object.keys(secret) - const resetters = resetTmpl(secret, paths) - const hasWildcards = wcLen > 0 - const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } - /* eslint-disable-next-line */ - this.restore = Function( - 'o', - restoreTmpl(resetters, paths, hasWildcards) - ).bind(state) - } -} + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } -/** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. - * - * @param {object} secret Compiled object describing which target fields should - * be censored and the field states. - * @param {string[]} paths The list of paths to censor as provided at - * initialization time. - * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. - */ -function resetTmpl (secret, paths) { - return paths.map((path) => { - const { circle, escPath, leadingBracket } = secret[path] - const delim = leadingBracket ? '' : '.' - const reset = circle - ? `o.${circle} = secret[${escPath}].val` - : `o${delim}${path} = secret[${escPath}].val` - const clear = `secret[${escPath}].val = undefined` - return ` - if (secret[${escPath}].val !== undefined) { - try { ${reset} } catch (e) {} - ${clear} - } - ` - }).join('') -} + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } -/** - * Creates the body of the restore function - * - * Restoration of the redacted object happens - * backwards, in reverse order of redactions, - * so that repeated redactions on the same object - * property can be eventually rolled back to the - * original value. - * - * This way dynamic redactions are restored first, - * starting from the last one working backwards and - * followed by the static ones. - * - * @returns {string} the body of the restore function - */ -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = len - 1; i >= ${paths.length}; i--) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null - } - ` : '' + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } - return ` - const secret = this.secret - ${dynamicReset} - ${resetters} - return o - ` -} + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } -/***/ }), + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -/***/ 9158: -/***/ ((module) => { + }; -"use strict"; + var States_1 = States; + var DLList$2, Sync; -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g + DLList$2 = DLList_1; -/* -Regular expression explanation: + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) + isEmpty() { + return this._queue.length === 0; + } -Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture - group (which will be capture group $1) that matches anything - within square brackets. Expansion is lazy so it will - stop matching as soon as the first closing bracket is met `]` - (rather than continuing to match until the final closing bracket). -*/ + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } -/***/ }), + }; -/***/ 41012: -/***/ ((module) => { + var Sync_1 = Sync; -"use strict"; + var version = "2.19.5"; + var version$1 = { + version: version + }; + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -module.exports = state + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -function state (o) { - const { - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - } = o - const builder = [{ secret, censor, compileRestore }] - if (serialize !== false) builder.push({ serialize }) - if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) - return Object.assign(...builder) -} + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/***/ }), + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + parser$3 = parser; -"use strict"; + Events$2 = Events_1; + RedisConnection$1 = require$$2; -const { createContext, runInContext } = __nccwpck_require__(26144) + IORedisConnection$1 = require$$3; -module.exports = validator + Scripts$1 = require$$4; -function validator (opts = {}) { - const { - ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', - ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` - } = opts + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } - return function validate ({ paths }) { - paths.forEach((s) => { - if (typeof s !== 'string') { - throw Error(ERR_PATHS_MUST_BE_STRINGS()) - } - try { - if (/〇/.test(s)) throw Error() - const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) - const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') - if (/\n|\r|;/.test(expr)) throw Error() - if (/\/\*/.test(expr)) throw Error() - runInContext(` - (function () { - 'use strict' - o${expr} - if ([o${expr}].length !== 1) throw Error() - })() - `, createContext({ o: proxy, 〇: null }), { - codeGeneration: { strings: false, wasm: false } - }) - } catch (e) { - throw Error(ERR_INVALID_PATH(s)) - } - }) - } -} + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } -/***/ }), + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } -/***/ 17676: -/***/ ((module) => { + keys() { + return Object.keys(this.instances); + } -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } -var LIMIT_REPLACE_NODE = '[...]' -var CIRCULAR_REPLACE_NODE = '[Circular]' + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } -var arr = [] -var replacerStack = [] + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } -function defaultOptions () { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - } -} + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } -// Regular stringify -function stringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; - decirc(obj, '', 0, [], undefined, 0, options) - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - } - return res -} + return Group; -function setReplace (replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k, replace]) - } - } else { - parent[k] = replace - arr.push([parent, k, val]) - } -} + }).call(commonjsGlobal); -function decirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } + var Group_1 = Group; - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } + var Batcher, Events$3, parser$4; - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } + parser$4 = parser; - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, i, stack, val, depth, options) - } - } - stack.pop() - } -} + Events$3 = Events_1; -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 - } - return 0 -} + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } -function deterministicStringify (obj, replacer, spacer, options) { - if (typeof options === 'undefined') { - options = defaultOptions() - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj - var res - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - } catch (_) { - return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') - } finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - } - return res -} + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } -function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { - depth += 1 - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) - return - } - } - try { - if (typeof val.toJSON === 'function') { - return - } - } catch (_) { - return - } + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } - if ( - typeof options.depthLimit !== 'undefined' && - depth > options.depthLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - if ( - typeof options.edgesLimit !== 'undefined' && - edgeIndex + 1 > options.edgesLimit - ) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent) - return - } + return Batcher; - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options) - } - } else { - // Create a temporary object in the required way - var tmp = {} - var keys = Object.keys(val).sort(compareFunction) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - deterministicDecirc(val[key], key, i, stack, val, depth, options) - tmp[key] = val[key] - } - if (typeof parent !== 'undefined') { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } - } - stack.pop() - } -} + }).call(commonjsGlobal); -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues (replacer) { - replacer = - typeof replacer !== 'undefined' - ? replacer - : function (k, v) { - return v - } - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i] - if (part[1] === key && part[0] === val) { - val = part[2] - replacerStack.splice(i, 1) - break - } - } - } - return replacer.call(this, key, val) - } -} + var Batcher_1 = Batcher; + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/***/ }), + var require$$8 = getCjsExportFromNamespace(version$2); -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; -"use strict"; + NUM_PRIORITIES$1 = 10; -/* -Copyright (c) 2014 Petka Antonov - -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. -*/ -function Url() { - //For more efficient internal representation and laziness. - //The non-underscore versions of these properties are accessor functions - //defined on the prototype. - this._protocol = null; - this._href = ""; - this._port = -1; - this._query = null; + DEFAULT_PRIORITY$1 = 5; - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; + parser$5 = parser; - this._prependSlash = false; -} + Queues$1 = Queues_1; -var querystring = __nccwpck_require__(63477); + Job$1 = Job_1; -Url.queryString = querystring; + LocalDatastore$1 = LocalDatastore_1; -Url.prototype.parse = -function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (typeof str !== "string") { - throw new TypeError("Parameter 'url' must be a string, not " + - typeof str); - } - var start = 0; - var end = str.length - 1; + RedisDatastore$1 = require$$4$1; - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; + Events$4 = Events_1; - start = this._parseProtocol(str, start, end); + States$1 = States_1; - //Javascript doesn't have host - if (this._protocol !== "javascript") { - start = this._parseHost(str, start, end, hostDenotesSlash); - var proto = this._protocol; - if (!this.hostname && - (this.slashes || (proto && !slashProtocols[proto]))) { - this.hostname = this.host = ""; - } - } + Sync$1 = Sync_1; - if (start <= end) { - var ch = str.charCodeAt(start); + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } - if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x23 /*'#'*/) { - this._parseHash(str, start, end, disableAutoEscapeChars); - } - else if (this._protocol !== "javascript") { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else { //For javascript the pathname is just the rest of it - this.pathname = str.slice(start, end + 1 ); - } + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } - } + ready() { + return this._store.ready; + } - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; - } + clients() { + return this._store.clients; + } - if (parseQueryString) { - var search = this.search; - if (search == null) { - search = this.search = ""; - } - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - //This calls a setter function, there is no .query data property - this.query = Url.queryString.parse(search); - } -}; + channel() { + return `b_${this.id}`; + } -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); -}; + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -Url.prototype.format = function Url$format() { - var auth = this.auth || ""; + publish(message) { + return this._store.__publish__(message); + } - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ":"); - auth += "@"; - } + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - var protocol = this.protocol || ""; - var pathname = this.pathname || ""; - var hash = this.hash || ""; - var search = this.search || ""; - var query = ""; - var hostname = this.hostname || ""; - var port = this.port || ""; - var host = false; - var scheme = ""; + chain(_limiter) { + this._limiter = _limiter; + return this; + } - //Cache the result of the getter function - var q = this.query; - if (q && typeof q === "object") { - query = Url.queryString.stringify(q); - } + queued(priority) { + return this._queues.queued(priority); + } - if (!search) { - search = query ? "?" + query : ""; - } + clusterQueued() { + return this._store.__queued__(); + } - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); - } + running() { + return this._store.__running__(); + } - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); + done() { + return this._store.__done__(); + } + jobStatus(id) { + return this._states.jobStatus(id); + } - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; + jobs(status) { + return this._states.statusJobs(status); + } - if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { - pathname = "/" + pathname; - } - if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) - search = "?" + search; - if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) - hash = "#" + hash; + counts() { + return this._states.statusCounts(); + } - pathname = escapePathName(pathname); - search = escapeSearch(search); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - return scheme + (host === false ? "" : host) + pathname + search + hash; -}; + check(weight = 1) { + return this._store.__check__(weight); + } -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - var result = this._clone(); + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - // if the relative url is empty, then there"s nothing left to do here. - if (!relative.href) { - result._href = ""; - return result; - } + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative._protocol) { - relative._copyPropsTo(result, true); + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } - if (slashProtocols[result._protocol] && - result.hostname && !result.pathname) { - result.pathname = "/"; - } - result._href = ""; - return result; - } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } - if (relative._protocol && relative._protocol !== result._protocol) { - // if it"s a known url protocol, then changing - // the protocol does weird things - // first, if it"s not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that"s known to be hostless. - // anything else is assumed to be absolute. - if (!slashProtocols[relative._protocol]) { - relative._copyPropsTo(result, false); - result._href = ""; - return result; - } + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - result._protocol = relative._protocol; - if (!relative.host && relative._protocol !== "javascript") { - var relPath = (relative.pathname || "").split("/"); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ""; - if (!relative.hostname) relative.hostname = ""; - if (relPath[0] !== "") relPath.unshift(""); - if (relPath.length < 2) relPath.unshift(""); - result.pathname = relPath.join("/"); - } else { - result.pathname = relative.pathname; - } + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } - result.search = relative.search; - result.host = relative.host || ""; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result._port = relative._port; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; - } + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - var isSourceAbs = - (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); - var isRelAbs = ( - relative.host || - (relative.pathname && - relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) - ); - var mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)); - - var removeAllDots = mustEndAbs; - - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ""; - result._port = -1; - if (result.host) { - if (srcPath[0] === "") srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ""; - if (relative._protocol) { - relative.hostname = ""; - relative._port = -1; - if (relative.host) { - if (relPath[0] === "") relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = ""; - } - mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); - } - - if (isRelAbs) { - // it"s absolute. - result.host = relative.host ? - relative.host : result.host; - result.hostname = relative.hostname ? - relative.hostname : result.hostname; - result.search = relative.search; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it"s relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - } else if (relative.search) { - // just pull out the search. - // like href="?foo". - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result._href = ""; - return result; - } + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; - } + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === "." || last === "..") || - last === ""); + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === ".") { - srcPath.splice(i, 1); - } else if (last === "..") { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } - } + currentReservoir() { + return this._store.__currentReservoir__(); + } - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); - } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); - } + } + Bottleneck.default = Bottleneck; - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); + Bottleneck.Events = Events$4; - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? "" : - srcPath.length ? srcPath.shift() : ""; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); - } + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; -var punycode = __nccwpck_require__(85477); -Url.prototype._hostIdna = function Url$_hostIdna(hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - return punycode.toASCII(hostname); -}; + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; -var escapePathName = Url.prototype._escapePathName = -function Url$_escapePathName(pathname) { - if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { - return pathname; - } - //Avoid closure creation to keep this inlinable - return _escapePath(pathname); -}; + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; -var escapeSearch = Url.prototype._escapeSearch = -function Url$_escapeSearch(search) { - if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; - //Avoid closure creation to keep this inlinable - return _escapeSearch(search); -}; + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; -Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { - var doLowerCase = false; - var protocolCharacters = this._protocolCharacters; + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; - if (ch === 0x3A /*':'*/) { - var protocol = str.slice(start, i); - if (doLowerCase) protocol = protocol.toLowerCase(); - this._protocol = protocol; - return i + 1; - } - else if (protocolCharacters[ch] === 1) { - if (ch < 0x61 /*'a'*/) - doLowerCase = true; - } - else { - return start; - } + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; - } - return start; -}; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; -Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { - var auth = str.slice(start, end + 1); - if (decode) { - auth = decodeURIComponent(auth); - } - this.auth = auth; -}; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; -Url.prototype._parsePort = function Url$_parsePort(str, start, end) { - //Internal format is integer for more efficient parsing - //and for efficient trimming of leading zeros - var port = 0; - //Distinguish between :0 and : (no port number at all) - var hadChars = false; - var validPort = true; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + return Bottleneck; - if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { - port = (10 * port) + (ch - 0x30 /*'0'*/); - hadChars = true; - } - else { - validPort = false; - if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { - validPort = true; - } - break; - } + }).call(commonjsGlobal); - } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; - } - return 0; - } + var Bottleneck_1 = Bottleneck; - this._port = port; - return i - start; -}; + var lib = Bottleneck_1; -Url.prototype._parseHost = -function Url$_parseHost(str, start, end, slashesDenoteHost) { - var hostEndingCharacters = this._hostEndingCharacters; - var first = str.charCodeAt(start); - var second = str.charCodeAt(start + 1); - if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && - (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { - this.slashes = true; - - //The string starts with // - if (start === 0) { - //The string is just "//" - if (end < 2) return start; - //If slashes do not denote host and there is no auth, - //there is no host when the string starts with // - var hasAuth = - containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); - if (!hasAuth && !slashesDenoteHost) { - this.slashes = null; - return start; - } - } - //There is a host that starts after the // - start += 2; - } - //If there is no slashes, there is no hostname if - //1. there was no protocol at all - else if (!this._protocol || - //2. there was a protocol that requires slashes - //e.g. in 'http:asd' 'asd' is not a hostname - slashProtocols[this._protocol] - ) { - return start; - } + return lib; - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; +}))); - var j = -1; - //Find the last occurrence of an @-sign until hostending character is met - //also mark if decoding is needed for the auth portion - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/***/ }), - if (ch === 0x40 /*'@'*/) { - j = i; - } - //This check is very, very cheap. Unneeded decodeURIComponent is very - //very expensive - else if (ch === 0x25 /*'%'*/) { - authNeedsDecoding = true; - } - else if (hostEndingCharacters[ch] === 1) { - break; - } - } +/***/ 39516: +/***/ ((module) => { - //@-sign was found at index j, everything to the left from it - //is auth part - if (j > -1) { - this._parseAuth(str, start, j - 1, authNeedsDecoding); - //hostname starts after the last @-sign - start = hostNameStart = j + 1; - } +module.exports = function btoa(str) { + return new Buffer(str).toString('base64') +} - //Host name is starting with a [ - if (str.charCodeAt(start) === 0x5B /*'['*/) { - for (var i = start + 1; i <= end; ++i) { - var ch = str.charCodeAt(i); - //Assume valid IP6 is between the brackets - if (ch === 0x5D /*']'*/) { - if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 2, end) + 1; - } - var hostname = str.slice(start + 1, i).toLowerCase(); - this.hostname = hostname; - this.host = this._port > 0 ? - "[" + hostname + "]:" + this._port : - "[" + hostname + "]"; - this.pathname = "/"; - return i + portLength + 1; - } - } - //Empty hostname, [ starts a path - return start; - } +/***/ }), - for (var i = start; i <= end; ++i) { - if (charsAfterDot > 62) { - this.hostname = this.host = str.slice(start, i); - return i; - } - var ch = str.charCodeAt(i); +/***/ 39732: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (ch === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 1, end) + 1; - hostNameEnd = i - 1; - break; - } - else if (ch < 0x61 /*'a'*/) { - if (ch === 0x2E /*'.'*/) { - //Node.js ignores this error - /* - if (lastCh === DOT || lastCh === -1) { - this.hostname = this.host = ""; - return start; - } - */ - charsAfterDot = -1; - } - else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { - doLowerCase = true; - } - //Valid characters other than ASCII letters -, _, +, 0-9 - else if (!(ch === 0x2D /*'-'*/ || - ch === 0x5F /*'_'*/ || - ch === 0x2B /*'+'*/ || - (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) - ) { - if (hostEndingCharacters[ch] === 0 && - this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - } - else if (ch >= 0x7B /*'{'*/) { - if (ch <= 0x7E /*'~'*/) { - if (this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - idna = true; - } - lastCh = ch; - charsAfterDot++; - } +"use strict"; +/*jshint node:true */ - //Node.js ignores this error - /* - if (lastCh === DOT) { - hostNameEnd--; - } - */ +var Buffer = (__nccwpck_require__(20181).Buffer); // browserify +var SlowBuffer = (__nccwpck_require__(20181).SlowBuffer); - if (hostNameEnd + 1 !== start && - hostNameEnd - hostNameStart <= 256) { - var hostname = str.slice(hostNameStart, hostNameEnd + 1); - if (doLowerCase) hostname = hostname.toLowerCase(); - if (idna) hostname = this._hostIdna(hostname); - this.hostname = hostname; - this.host = this._port > 0 ? hostname + ":" + this._port : hostname; - } +module.exports = bufferEq; - return hostNameEnd + 1 + portLength; +function bufferEq(a, b) { -}; + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} -Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { - if (!noProtocol) { - input._protocol = this._protocol; - } - input._href = this._href; - input._port = this._port; - input._prependSlash = this._prependSlash; - input.auth = this.auth; - input.slashes = this.slashes; - input.host = this.host; - input.hostname = this.hostname; - input.hash = this.hash; - input.search = this.search; - input.pathname = this.pathname; +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; }; -Url.prototype._clone = function Url$_clone() { - var ret = new Url(); - ret._protocol = this._protocol; - ret._href = this._href; - ret._port = this._port; - ret._prependSlash = this._prependSlash; - ret.auth = this.auth; - ret.slashes = this.slashes; - ret.host = this.host; - ret.hostname = this.hostname; - ret.hash = this.hash; - ret.search = this.search; - ret.pathname = this.pathname; - return ret; +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; }; -Url.prototype._getComponentEscaped = -function Url$_getComponentEscaped(str, start, end, isAfterQuery) { - var cur = start; - var i = start; - var ret = ""; - var autoEscapeMap = isAfterQuery ? - this._afterQueryAutoEscapeMap : this._autoEscapeMap; - for (; i <= end; ++i) { - var ch = str.charCodeAt(i); - var escaped = autoEscapeMap[ch]; - if (escaped !== "" && escaped !== undefined) { - if (cur < i) ret += str.slice(cur, i); - ret += escaped; - cur = i + 1; - } - } - if (cur < i + 1) ret += str.slice(cur, i); - return ret; -}; +/***/ }), -Url.prototype._parsePath = -function Url$_parsePath(str, start, end, disableAutoEscapeChars) { - var pathStart = start; - var pathEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; - var prePath = this._port === -2 ? "/:" : ""; - - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } +/***/ 34531: +/***/ ((module) => { - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } +"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ - var path; - if (escape) { - path = this._getComponentEscaped(str, pathStart, pathEnd, false); - } - else { - path = str.slice(pathStart, pathEnd + 1); - } - this.pathname = prePath === "" - ? (this._prependSlash ? "/" + path : path) - : prePath + path; -}; -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/** + * Module exports. + * @public + */ - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; - if (queryStart > queryEnd) { - this.search = ""; - return; - } +/** + * Module variables. + * @private + */ - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); - } - else { - query = str.slice(queryStart, queryEnd + 1); - } - this.search = query; -}; +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; - } +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - this.hash = disableAutoEscapeChars ? - str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), }; -Object.defineProperty(Url.prototype, "port", { - get: function() { - if (this._port >= 0) { - return ("" + this._port); - } - return null; - }, - set: function(v) { - if (v == null) { - this._port = -1; - } - else { - this._port = parseInt(v, 10); - } - } -}); +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; - } - var search = this.search; +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ - if (search) { - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - if (search !== "") { - this._query = search; - return search; - } - } - return search; - }, - set: function(v) { - this._query = v; - } -}); +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } -Object.defineProperty(Url.prototype, "path", { - get: function() { - var p = this.pathname || ""; - var s = this.search || ""; - if (p || s) { - return p + s; - } - return (p == null && s) ? ("/" + s) : null; - }, - set: function() {} -}); + if (typeof value === 'number') { + return format(value, options); + } -Object.defineProperty(Url.prototype, "protocol", { - get: function() { - var proto = this._protocol; - return proto ? proto + ":" : proto; - }, - set: function(v) { - if (typeof v === "string") { - var end = v.length - 1; - if (v.charCodeAt(end) === 0x3A /*':'*/) { - this._protocol = v.slice(0, end); - } - else { - this._protocol = v; - } - } - else if (v == null) { - this._protocol = null; - } - } -}); + return null; +} -Object.defineProperty(Url.prototype, "href", { - get: function() { - var href = this._href; - if (!href) { - href = this._href = this.format(); - } - return href; - }, - set: function(v) { - this._href = v; - } -}); +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ -Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (str instanceof Url) return str; - var ret = new Url(); - ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); - return ret; -}; +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } -Url.format = function Url$Format(obj) { - if (typeof obj === "string") { - obj = Url.parse(obj); - } - if (!(obj instanceof Url)) { - return Url.prototype.format.call(obj); + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; } - return obj.format(); -}; + } -Url.resolve = function Url$Resolve(source, relative) { - return Url.parse(source, false, true).resolve(relative); -}; + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); -Url.resolveObject = function Url$ResolveObject(source, relative) { - if (!source) return relative; - return Url.parse(source, false, true).resolveObject(relative); -}; + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); -} + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); + return str + unitSeparator + unit; } -//Search `char1` (integer code for a character) in `string` -//starting from `fromIndex` and ending at `string.length - 1` -//or when a stop character is found -function containsCharacter(string, char1, fromIndex, stopCharacterTable) { - var len = string.length; - for (var i = fromIndex; i < len; ++i) { - var ch = string.charCodeAt(i); +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } - } - return false; -} +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } -//See if `char1` or `char2` (integer codes for characters) -//is contained in `string` -function containsCharacter2(string, char1, char2) { - for (var i = 0, len = string.length; i < len; ++i) { - var ch = string.charCodeAt(i); - if (ch === char1 || ch === char2) return true; - } - return false; -} + if (typeof val !== 'string') { + return null; + } -//Makes an array of 128 uint8's which represent boolean values. -//Spec is an array of ascii code points or ascii code point ranges -//ranges are expressed as [start, end] + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; -//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and -//0x7A (lowercaseletter 'z') as `true`: -// -//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); -//a[0x30]; //1 -//a[0x15]; //0 -//a[0x35]; //1 -function makeAsciiTable(spec) { - var ret = new Uint8Array(128); - spec.forEach(function(item){ - if (typeof item === "number") { - ret[item] = 1; - } - else { - var start = item[0]; - var end = item[1]; - for (var j = start; j <= end; ++j) { - ret[j] = 1; - } - } - }); + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } - return ret; + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); } -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; +/***/ }), -var autoEscapeMap = new Array(128); +/***/ 22639: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; -} +var bind = __nccwpck_require__(37564); -for (var i = 0, len = autoEscape.length; i < len; ++i) { - var c = autoEscape[i]; - var esc = encodeURIComponent(c); - if (esc === c) { - esc = escape(c); - } - autoEscapeMap[c.charCodeAt(0)] = esc; -} -var afterQueryAutoEscapeMap = autoEscapeMap.slice(); -autoEscapeMap[0x5C /*'\'*/] = "/"; +var $apply = __nccwpck_require__(33945); +var $call = __nccwpck_require__(88093); +var $reflectApply = __nccwpck_require__(31330); -var slashProtocols = Url.prototype._slashProtocols = { - http: true, - https: true, - gopher: true, - file: true, - ftp: true, +/** @type {import('./actualApply')} */ +module.exports = $reflectApply || bind.call($call, $apply); - "http:": true, - "https:": true, - "gopher:": true, - "file:": true, - "ftp:": true -}; -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; +/***/ }), -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); +/***/ 33945: +/***/ ((module) => { -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); +"use strict"; -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) -); -//If these characters end a host name, the path will not be prepended a / -Url.prototype._noPrependSlashHostEnders = makeAsciiTable( - [ - "<", ">", "'", "`", " ", "\r", - "\n", "\t", "{", "}", "|", - "^", "`", "\"", "%", ";" - ].map(function(v) { - return v.charCodeAt(0); - }) -); +/** @type {import('./functionApply')} */ +module.exports = Function.prototype.apply; -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; -module.exports = Url; +/***/ }), -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url - }; -}; +/***/ 88093: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./functionCall')} */ +module.exports = Function.prototype.call; /***/ }), -/***/ 30810: +/***/ 88705: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +var bind = __nccwpck_require__(37564); +var $TypeError = __nccwpck_require__(73314); -/** - * Module dependencies. - * @private - */ +var $call = __nccwpck_require__(88093); +var $actualApply = __nccwpck_require__(22639); -var debug = __nccwpck_require__(38237)('finalhandler') -var encodeUrl = __nccwpck_require__(16592) -var escapeHtml = __nccwpck_require__(94070) -var onFinished = __nccwpck_require__(24694) -var parseUrl = __nccwpck_require__(89808) -var statuses = __nccwpck_require__(57415) -var unpipe = __nccwpck_require__(3124) +/** @type {import('.')} */ +module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); +}; -/** - * Module variables. - * @private - */ -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g +/***/ }), -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished +/***/ 31330: +/***/ ((module) => { -/** - * Create a minimal HTML document. - * - * @param {string} message - * @private - */ +"use strict"; -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} +/** @type {import('./reflectApply')} */ +module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; -/** - * Module exports. - * @public - */ -module.exports = finalhandler +/***/ }), -/** - * Create a function to handle the final response. - * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public - */ +/***/ 23105: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function finalhandler (req, res, options) { - var opts = options || {} +"use strict"; - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' - // get error callback - var onerror = opts.onerror +var GetIntrinsic = __nccwpck_require__(60470); - return function (err) { - var headers - var msg - var status +var callBindBasic = __nccwpck_require__(88705); - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + // eslint-disable-next-line no-extra-parens + var intrinsic = /** @type {Parameters[0][0]} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; +}; - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) - } - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } +/***/ }), - debug('default %s', status) +/***/ 8208: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) - } - - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return - } +"use strict"; - // send response - send(req, res, status, headers, msg) - } -} +const os = __nccwpck_require__(70857); -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined - } +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); - var headers = Object.create(null) - var keys = Object.keys(err.headers) + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] - } + const match = pathMatches[1]; - return headers -} + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } -/** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private - */ + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } -function getErrorMessage (err, status, env) { - var msg + return line; + }) + .join('\n'); +}; - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() - } - } +/***/ }), - return msg || statuses[status] -} +/***/ 58999: +/***/ ((module) => { -/** - * Get status code from Error object. +/* + * Copyright 2001-2010 Georges Menie (www.menie.org) + * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) + * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) + * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * @param {Error} err - * @return {number} - * @private + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the University of California, Berkeley nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } - - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } - - return undefined -} - -/** - * Get resource name for the request. +/* CRC16 implementation according to CCITT standards. * - * This is typically just the original pathname of the request - * but will fallback to "resource" is that cannot be determined. + * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the + * following parameters: * - * @param {IncomingMessage} req - * @return {string} - * @private + * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" + * Width : 16 bit + * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) + * Initialization : 0000 + * Reflect Input byte : False + * Reflect Output CRC : False + * Xor constant to output CRC : 0000 + * Output for "123456789" : 31C3 */ -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' - } -} +var lookup = [ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +]; /** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} - * @private + * Convert a string to a UTF8 array - faster than via buffer + * @param str + * @returns {Array} */ +var toUTF8Array = function toUTF8Array(str) { + var char; + var i = 0; + var p = 0; + var utf8 = []; + var len = str.length; -function getResponseStatusCode (res) { - var status = res.statusCode - - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 + for (; i < len; i++) { + char = str.charCodeAt(i); + if (char < 128) { + utf8[p++] = char; + } else if (char < 2048) { + utf8[p++] = (char >> 6) | 192; + utf8[p++] = (char & 63) | 128; + } else if ( + ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && + ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { + char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); + utf8[p++] = (char >> 18) | 240; + utf8[p++] = ((char >> 12) & 63) | 128; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; + } else { + utf8[p++] = (char >> 12) | 224; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; + } } - return status -} - -/** - * Determine if the response headers have been sent. - * - * @param {object} res - * @returns {boolean} - * @private - */ - -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent -} + return utf8; +}; /** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message - * @private + * Convert a string into a redis slot hash. + * @param str + * @returns {number} */ +var generate = module.exports = function generate(str) { + var char; + var i = 0; + var start = -1; + var result = 0; + var resultHash = 0; + var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; + var len = utf8.length; -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) - - // response status - res.statusCode = status - res.statusMessage = statuses[status] - - // response headers - setHeaders(res, headers) - - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') - - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) - - if (req.method === 'HEAD') { - res.end() - return + while (i < len) { + char = utf8[i++]; + if (start === -1) { + if (char === 0x7B) { + start = i; + } + } else if (char !== 0x7D) { + resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); + } else if (i - 1 !== start) { + return resultHash & 0x3FFF; } - res.end(body, 'utf8') - } - - if (isFinished(req)) { - write() - return + result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); } - // unpipe everything from the request - unpipe(req) - - // flush the request - onFinished(req, write) - req.resume() -} + return result & 0x3FFF; +}; /** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers - * @private + * Convert an array of multiple strings into a redis slot hash. + * Returns -1 if one of the keys is not for the same slot as the others + * @param keys + * @returns {number} */ +module.exports.generateMulti = function generateMulti(keys) { + var i = 1; + var len = keys.length; + var base = generate(keys[0]); -function setHeaders (res, headers) { - if (!headers) { - return - } - - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) + while (i < len) { + if (generate(keys[i++]) !== base) return -1; } -} - - -/***/ }), - -/***/ 9486: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const path = __nccwpck_require__(71017); -const locatePath = __nccwpck_require__(63447); - -module.exports = (filename, opts = {}) => { - const startDir = path.resolve(opts.cwd || ''); - const {root} = path.parse(startDir); - - const filenames = [].concat(filename); - - return new Promise(resolve => { - (function find(dir) { - locatePath(filenames, {cwd: dir}).then(file => { - if (file) { - resolve(path.join(dir, file)); - } else if (dir === root) { - resolve(null); - } else { - find(path.dirname(dir)); - } - }); - })(startDir); - }); -}; - -module.exports.sync = (filename, opts = {}) => { - let dir = path.resolve(opts.cwd || ''); - const {root} = path.parse(dir); - - const filenames = [].concat(filename); - - // eslint-disable-next-line no-constant-condition - while (true) { - const file = locatePath.sync(filenames, {cwd: dir}); - - if (file) { - return path.join(dir, file); - } - if (dir === root) { - return null; - } - - dir = path.dirname(dir); - } + return base; }; /***/ }), -/***/ 35298: -/***/ ((module) => { - -"use strict"; - - -// You may be tempted to copy and paste this, -// but take a look at the commit history first, -// this is a moving target so relying on the module -// is the best way to make sure the optimization -// method is kept up to date and compatible with -// every Node version. - -function flatstr (s) { - s | 0 - return s -} - -module.exports = flatstr - -/***/ }), - -/***/ 46868: -/***/ ((module) => { +/***/ 18111: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * forwarded + * content-disposition * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ @@ -41300,60543 +46934,90627 @@ module.exports = flatstr * @public */ -module.exports = forwarded +module.exports = contentDisposition +module.exports.parse = parse /** - * Get all addresses in the request, using the `X-Forwarded-For` header. - * - * @param {object} req - * @return {array} - * @public + * Module dependencies. + * @private */ -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') - } - - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = getSocketAddr(req) - var addrs = [socketAddr].concat(proxyAddrs) - - // return all addresses - return addrs -} +var basename = (__nccwpck_require__(16928).basename) +var Buffer = (__nccwpck_require__(93058).Buffer) /** - * Get the socket address for a request. - * - * @param {object} req - * @return {string} + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") * @private */ -function getSocketAddr (req) { - return req.socket - ? req.socket.remoteAddress - : req.connection.remoteAddress -} +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex /** - * Parse the X-Forwarded-For header. - * - * @param {string} header + * RegExp to match percent encoding escape. * @private */ -function parse (header) { - var end = header.length - var list = [] - var start = header.length - - // gather addresses, backwards - for (var i = header.length - 1; i >= 0; i--) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i - } - break - case 0x2c: /* , */ - if (start !== end) { - list.push(header.substring(start, end)) - } - start = end = i - break - default: - start = i - break - } - } - - // final address - if (start !== end) { - list.push(header.substring(start, end)) - } - - return list -} - - -/***/ }), - -/***/ 83136: -/***/ ((module) => { +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g -"use strict"; -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed +/** + * RegExp to match non-latin1 characters. + * @private */ - +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g /** - * RegExp to check for no-cache token in Cache-Control. + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = * @private */ -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex /** - * Module exports. - * @public + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private */ -module.exports = fresh +var QUOTE_REGEXP = /([\\"])/g /** - * Check freshness of the response using request and response headers. + * RegExp for various RFC 2616 grammar * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private */ -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] - - // unconditional request - if (!modifiedSince && !noneMatch) { - return false - } - - // Always return stale when Cache-Control: no-cache - // to support end-to-end reload requests - // https://tools.ietf.org/html/rfc2616#section-14.9.4 - var cacheControl = reqHeaders['cache-control'] - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false - } - - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] - - if (!etag) { - return false - } - - var etagStale = true - var matches = parseTokenList(noneMatch) - for (var i = 0; i < matches.length; i++) { - var match = matches[i] - if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { - etagStale = false - break - } - } - - if (etagStale) { - return false - } - } - - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - if (modifiedStale) { - return false - } - } +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ - return true -} +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ /** - * Parse an HTTP Date into a number. + * RegExp for various RFC 6266 grammar * - * @param {string} date + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = * @private */ -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) - - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN -} +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex /** - * Parse a HTTP token list. + * Create an attachment Content-Disposition header. * - * @param {string} str - * @private + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public */ -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 +function contentDisposition (filename, options) { + var opts = options || {} - // gather tokens - for (var i = 0, len = str.length; i < len; i++) { - switch (str.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(str.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break - } - } + // get type + var type = opts.type || 'attachment' - // final token - list.push(str.substring(start, end)) + // get parameters + var params = createparams(filename, opts.fallback) - return list + // format into string + return format(new ContentDisposition(type, params)) } +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ -/***/ }), - -/***/ 46863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function createparams (filename, fallback) { + if (filename === undefined) { + return + } -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __nccwpck_require__(57147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(71734) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} + var params = {} -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') } - if (typeof cache === 'function') { - cb = cache - cache = null + // fallback defaults to true + if (fallback === undefined) { + fallback = true } - 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) + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') } - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') } -} - -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} - -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} - - -/***/ }), - -/***/ 71734: -/***/ ((__unused_webpack_module, 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__(71017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(57147); -// JavaScript implementation of realpath, ported from node pre-v6 - -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + // restrict to file base name + var name = basename(filename) -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; + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) - return callback; + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name } - 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); - } - } + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name } -} - -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} - -var normalize = pathModule.normalize; -// 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; + return params } -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +function format (obj) { + var parameters = obj.parameters + var type = obj.type - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') } - var original = p, - seenLinks = {}, - knownHard = {}; + // start with normalized type + var string = String(type).toLowerCase() - // 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; + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - start(); + for (var i = 0; i < params.length; i++) { + param = params[i] - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; + string += '; ' + param + '=' + val } } - // 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; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } + return string +} - 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; - } +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ - // 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; - } +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + if (!match) { + throw new TypeError('invalid extended field value') } - if (cache) cache[original] = p; - - return p; -}; + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') } - // make p is absolute - p = pathModule.resolve(p); + return value +} - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ - var original = p, - seenLinks = {}, - knownHard = {}; +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} - // 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; +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ - start(); +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + var match = DISPOSITION_TYPE_REGEXP.exec(string) - // 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); - } + if (!match) { + throw new TypeError('invalid type format') } - // 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); - } + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') } - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') } - return fs.lstat(base, gotStat); - } + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) - function gotStat(err, stat) { - if (err) return cb(err); + // overwrite existing value + params[key] = value + continue + } - // 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); + if (typeof params[key] === 'string') { + continue } - // 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); - } + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') } - fs.stat(base, function(err) { - if (err) return cb(err); - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); + params[key] = value } - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') } - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; + return new ContentDisposition(type, params) +} +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ -/***/ }), +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} -/***/ 19320: -/***/ ((module) => { +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ -"use strict"; +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ -/* eslint no-invalid-this: 1 */ +function qstring (val) { + var str = String(val) -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; +function ustring (val) { + var str = String(val) - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + return 'UTF-8\'\'' + encoded +} - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ - return bound; -}; +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} /***/ }), -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 20756: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -var implementation = __nccwpck_require__(19320); - -module.exports = Function.prototype.bind || implementation; +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ -/***/ }), +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex -/***/ 47625: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} +/** + * Module exports. + * @public + */ -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var minimatch = __nccwpck_require__(83973) -var isAbsolute = __nccwpck_require__(38714) -var Minimatch = minimatch.Minimatch +exports.format = format +exports.parse = parse -function alphasort (a, b) { - return a.localeCompare(b, 'en') -} +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ -function setupIgnores (self, options) { - self.ignore = options.ignore || [] +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] + var parameters = obj.parameters + var type = obj.type - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') } -} -// 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 }) - } + var string = type - 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 - - 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 - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } - } + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - if (!nou) - all = Object.keys(all) + for (var i = 0; i < params.length; i++) { + param = params[i] - if (!self.nosort) - all = all.sort(alphasort) + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } - // 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 - }) + string += '; ' + param + '=' + qstring(parameters[param]) } } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all + return string } -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) +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') } - return m -} + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string -// 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 (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - - return abs -} - - -// 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 - - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false + var index = header.indexOf(';') + var type = index !== -1 + ? header.slice(0, index).trim() + : header.trim() - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + var obj = new ContentType(type.toLowerCase()) -/***/ }), + // parse parameters + if (index !== -1) { + var key + var match + var value -/***/ 91957: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + PARAM_REGEXP.lastIndex = index -// 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. + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -module.exports = glob + index += match[0].length + key = match[1].toLowerCase() + value = match[2] -var rp = __nccwpck_require__(46863) -var minimatch = __nccwpck_require__(83973) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(44124) -var EE = (__nccwpck_require__(82361).EventEmitter) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(38714) -var globSync = __nccwpck_require__(29010) -var common = __nccwpck_require__(47625) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(52492) -var util = __nccwpck_require__(73837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + if (value.charCodeAt(0) === 0x22 /* " */) { + // remove quotes + value = value.slice(1, -1) -var once = __nccwpck_require__(1223) + // remove escapes + if (value.indexOf('\\') !== -1) { + value = value.replace(QESC_REGEXP, '$1') + } + } -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} + obj.parameters[key] = value + } - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } } - return new Glob(pattern, options, cb) + return obj } -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ -// old api surface -glob.glob = glob +function getcontenttype (obj) { + var header -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] } - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') } - return origin -} -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true + return header +} - var g = new Glob(pattern, options) - var set = g.minimatch.set +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ - if (!pattern) - return false +function qstring (val) { + var str = String(val) - if (set.length > 1) - return true + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') } - return false + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' } -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) - } +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} - 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 +/***/ 34349: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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) +/** + * Module dependencies. + */ - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } +var crypto = __nccwpck_require__(76982); - var self = this - this._processing = 0 +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ - this._emitQueue = [] - this._processQueue = [] - this.paused = false +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; - if (this.noprocess) - return this +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ - if (n === 0) - return done() +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false +/** + * Private + */ - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } - } +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); } -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - common.finish(this) - this.emit('end', this.found) -} +/***/ }), -Glob.prototype._realpath = function () { - if (this._didRealpath) - return +/***/ 3814: +/***/ ((__unused_webpack_module, exports) => { - this._didRealpath = true +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - var n = this.matches.length - if (n === 0) - return this._finish() - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) - function next () { - if (--n === 0) - self._finish() - } -} +/** + * Module exports. + * @public + */ -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() +exports.parse = parse; +exports.serialize = serialize; - var found = Object.keys(matchset) - var self = this - var n = found.length +/** + * Module variables. + * @private + */ - if (n === 0) - return cb() +var __toString = Object.prototype.toString - 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 +/** + * RegExp to match cookie-name in RFC 6265 sec 4.1.1 + * This refers out to the obsoleted definition of token in RFC 2616 sec 2.2 + * which has been replaced by the token definition in RFC 7230 appendix B. + * + * cookie-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / + * "*" / "+" / "-" / "." / "^" / "_" / + * "`" / "|" / "~" / DIGIT / ALPHA + */ - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} +var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} +/** + * RegExp to match cookie-value in RFC 6265 sec 4.1.1 + * + * cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + * cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + * ; US-ASCII characters excluding CTLs, + * ; whitespace DQUOTE, comma, semicolon, + * ; and backslash + */ -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} +/** + * RegExp to match domain-value in RFC 6265 sec 4.1.1 + * + * domain-value = + * ; defined in [RFC1034], Section 3.5, as + * ; enhanced by [RFC1123], Section 2.1 + * =