country-flag-cli 0.0.19 → 0.0.23

Sign up to get free protection for your applications and to get access to all the features.
package/dist/cli.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../node_modules/commander/index.js", "../node_modules/tslib/tslib.js", "../node_modules/@sentry/types/src/loglevel.ts", "../node_modules/@sentry/types/src/session.ts", "../node_modules/@sentry/types/src/severity.ts", "../node_modules/@sentry/types/src/status.ts", "../node_modules/@sentry/types/src/transaction.ts", "../node_modules/@sentry/types/src/transport.ts", "../node_modules/@sentry/types/src/index.ts", "../node_modules/@sentry/utils/src/async.ts", "../node_modules/@sentry/utils/src/node.ts", "../node_modules/@sentry/utils/src/global.ts", "../node_modules/@sentry/utils/src/is.ts", "../node_modules/@sentry/utils/src/browser.ts", "../node_modules/@sentry/utils/src/polyfill.ts", "../node_modules/@sentry/utils/src/error.ts", "../node_modules/@sentry/utils/src/dsn.ts", "../node_modules/@sentry/utils/src/logger.ts", "../node_modules/@sentry/utils/src/memo.ts", "../node_modules/@sentry/utils/src/stacktrace.ts", "../node_modules/@sentry/utils/src/string.ts", "../node_modules/@sentry/utils/src/object.ts", "../node_modules/@sentry/utils/src/supports.ts", "../node_modules/@sentry/utils/src/instrument.ts", "../node_modules/@sentry/utils/src/misc.ts", "../node_modules/@sentry/utils/src/path.ts", "../node_modules/@sentry/utils/src/syncpromise.ts", "../node_modules/@sentry/utils/src/promisebuffer.ts", "../node_modules/@sentry/utils/src/time.ts", "../node_modules/@sentry/utils/src/index.ts", "../node_modules/@sentry/hub/src/scope.ts", "../node_modules/@sentry/hub/src/session.ts", "../node_modules/@sentry/hub/src/hub.ts", "../node_modules/@sentry/hub/src/sessionflusher.ts", "../node_modules/@sentry/hub/src/index.ts", "../node_modules/@sentry/minimal/src/index.ts", "../node_modules/@sentry/core/src/api.ts", "../node_modules/@sentry/core/src/integration.ts", "../node_modules/@sentry/core/src/baseclient.ts", "../node_modules/@sentry/core/src/transports/noop.ts", "../node_modules/@sentry/core/src/basebackend.ts", "../node_modules/@sentry/core/src/request.ts", "../node_modules/@sentry/core/src/sdk.ts", "../node_modules/@sentry/core/src/version.ts", "../node_modules/@sentry/core/src/integrations/functiontostring.ts", "../node_modules/@sentry/core/src/integrations/inboundfilters.ts", "../node_modules/@sentry/core/src/integrations/index.ts", "../node_modules/@sentry/core/src/index.ts", "../node_modules/lru_map/lru.js", "../node_modules/@sentry/node/src/stacktrace.ts", "../node_modules/@sentry/node/src/parsers.ts", "../node_modules/@sentry/node/src/version.ts", "../node_modules/@sentry/node/src/transports/base/index.ts", "../node_modules/ms/index.js", "../node_modules/debug/src/common.js", "../node_modules/debug/src/browser.js", "../node_modules/has-flag/index.js", "../node_modules/supports-color/index.js", "../node_modules/debug/src/node.js", "../node_modules/debug/src/index.js", "../node_modules/agent-base/src/promisify.ts", "../node_modules/agent-base/src/index.ts", "../node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../node_modules/https-proxy-agent/src/agent.ts", "../node_modules/https-proxy-agent/src/index.ts", "../node_modules/@sentry/node/src/transports/http.ts", "../node_modules/@sentry/node/src/transports/https.ts", "../node_modules/@sentry/node/src/transports/index.ts", "../node_modules/@sentry/node/src/backend.ts", "../node_modules/@sentry/node/src/client.ts", "../node_modules/@sentry/node/src/integrations/console.ts", "../node_modules/@sentry/node/src/integrations/utils/http.ts", "../node_modules/@sentry/node/src/integrations/http.ts", "../node_modules/@sentry/node/src/integrations/utils/errorhandling.ts", "../node_modules/@sentry/node/src/integrations/onuncaughtexception.ts", "../node_modules/@sentry/node/src/integrations/onunhandledrejection.ts", "../node_modules/@sentry/node/src/integrations/linkederrors.ts", "../node_modules/@sentry/node/src/integrations/modules.ts", "../node_modules/@sentry/node/src/integrations/index.ts", "../node_modules/@sentry/node/src/sdk.ts", "../node_modules/@sentry/node/src/utils.ts", "../node_modules/@sentry/tracing/src/spanstatus.ts", "../node_modules/@sentry/tracing/src/utils.ts", "../node_modules/@sentry/tracing/src/errors.ts", "../node_modules/@sentry/tracing/src/constants.ts", "../node_modules/@sentry/tracing/src/span.ts", "../node_modules/@sentry/tracing/src/transaction.ts", "../node_modules/@sentry/tracing/src/idletransaction.ts", "../node_modules/@sentry/tracing/src/hubextensions.ts", "../node_modules/@sentry/tracing/src/integrations/node/express.ts", "../node_modules/@sentry/tracing/src/integrations/node/postgres.ts", "../node_modules/@sentry/tracing/src/integrations/node/mysql.ts", "../node_modules/@sentry/tracing/src/integrations/node/mongo.ts", "../node_modules/@sentry/tracing/src/browser/backgroundtab.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/bindReporter.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/generateUniqueID.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/initMetric.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/observe.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/onHidden.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getCLS.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/getVisibilityWatcher.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getFID.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getLCP.ts", "../node_modules/@sentry/tracing/src/browser/metrics.ts", "../node_modules/@sentry/tracing/src/browser/request.ts", "../node_modules/@sentry/tracing/src/browser/router.ts", "../node_modules/@sentry/tracing/src/browser/browsertracing.ts", "../node_modules/@sentry/tracing/src/browser/index.ts", "../node_modules/@sentry/tracing/src/integrations/index.ts", "../node_modules/@sentry/tracing/src/index.ts", "../node_modules/cookie/index.js", "../node_modules/@sentry/node/src/handlers.ts", "../node_modules/@sentry/node/src/index.ts", "../node_modules/@sentry/integrations/src/angular.ts", "../node_modules/@sentry/integrations/src/captureconsole.ts", "../node_modules/@sentry/integrations/src/debug.ts", "../node_modules/@sentry/integrations/src/dedupe.ts", "../node_modules/@sentry/integrations/src/ember.ts", "../node_modules/@sentry/integrations/src/extraerrordata.ts", "../node_modules/localforage/dist/localforage.js", "../node_modules/@sentry/integrations/src/offline.ts", "../node_modules/@sentry/integrations/src/reportingobserver.ts", "../node_modules/@sentry/integrations/src/rewriteframes.ts", "../node_modules/@sentry/integrations/src/sessiontiming.ts", "../node_modules/@sentry/integrations/src/transaction.ts", "../node_modules/@sentry/integrations/src/vue.ts", "../node_modules/@sentry/integrations/src/index.ts", "../src/cli.ts", "../src/index.ts"],
4
- "sourcesContent": ["/**\n * Module dependencies.\n */\n\nvar EventEmitter = require('events').EventEmitter;\nvar spawn = require('child_process').spawn;\nvar path = require('path');\nvar dirname = path.dirname;\nvar basename = path.basename;\nvar fs = require('fs');\n\n/**\n * Inherit `Command` from `EventEmitter.prototype`.\n */\n\nrequire('util').inherits(Command, EventEmitter);\n\n/**\n * Expose the root command.\n */\n\nexports = module.exports = new Command();\n\n/**\n * Expose `Command`.\n */\n\nexports.Command = Command;\n\n/**\n * Expose `Option`.\n */\n\nexports.Option = Option;\n\n/**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {String} flags\n * @param {String} description\n * @api public\n */\n\nfunction Option(flags, description) {\n this.flags = flags;\n this.required = flags.indexOf('<') >= 0;\n this.optional = flags.indexOf('[') >= 0;\n this.bool = flags.indexOf('-no-') === -1;\n flags = flags.split(/[ ,|]+/);\n if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();\n this.long = flags.shift();\n this.description = description || '';\n}\n\n/**\n * Return option name.\n *\n * @return {String}\n * @api private\n */\n\nOption.prototype.name = function() {\n return this.long\n .replace('--', '')\n .replace('no-', '');\n};\n\n/**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {String}\n * @api private\n */\n\nOption.prototype.attributeName = function() {\n return camelcase(this.name());\n};\n\n/**\n * Check if `arg` matches the short or long flag.\n *\n * @param {String} arg\n * @return {Boolean}\n * @api private\n */\n\nOption.prototype.is = function(arg) {\n return this.short === arg || this.long === arg;\n};\n\n/**\n * Initialize a new `Command`.\n *\n * @param {String} name\n * @api public\n */\n\nfunction Command(name) {\n this.commands = [];\n this.options = [];\n this._execs = {};\n this._allowUnknownOption = false;\n this._args = [];\n this._name = name || '';\n}\n\n/**\n * Add command `name`.\n *\n * The `.action()` callback is invoked when the\n * command `name` is specified via __ARGV__,\n * and the remaining arguments are applied to the\n * function for access.\n *\n * When the `name` is \"*\" an un-matched command\n * will be passed as the first arg, followed by\n * the rest of __ARGV__ remaining.\n *\n * Examples:\n *\n * program\n * .version('0.0.1')\n * .option('-C, --chdir <path>', 'change the working directory')\n * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')\n * .option('-T, --no-tests', 'ignore test hook')\n *\n * program\n * .command('setup')\n * .description('run remote setup commands')\n * .action(function() {\n * console.log('setup');\n * });\n *\n * program\n * .command('exec <cmd>')\n * .description('run the given remote command')\n * .action(function(cmd) {\n * console.log('exec \"%s\"', cmd);\n * });\n *\n * program\n * .command('teardown <dir> [otherDirs...]')\n * .description('run teardown commands')\n * .action(function(dir, otherDirs) {\n * console.log('dir \"%s\"', dir);\n * if (otherDirs) {\n * otherDirs.forEach(function (oDir) {\n * console.log('dir \"%s\"', oDir);\n * });\n * }\n * });\n *\n * program\n * .command('*')\n * .description('deploy the given env')\n * .action(function(env) {\n * console.log('deploying \"%s\"', env);\n * });\n *\n * program.parse(process.argv);\n *\n * @param {String} name\n * @param {String} [desc] for git-style sub-commands\n * @return {Command} the new command\n * @api public\n */\n\nCommand.prototype.command = function(name, desc, opts) {\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n var args = name.split(/ +/);\n var cmd = new Command(args.shift());\n\n if (desc) {\n cmd.description(desc);\n this.executables = true;\n this._execs[cmd._name] = true;\n if (opts.isDefault) this.defaultExecutable = cmd._name;\n }\n cmd._noHelp = !!opts.noHelp;\n this.commands.push(cmd);\n cmd.parseExpectedArgs(args);\n cmd.parent = this;\n\n if (desc) return this;\n return cmd;\n};\n\n/**\n * Define argument syntax for the top-level command.\n *\n * @api public\n */\n\nCommand.prototype.arguments = function(desc) {\n return this.parseExpectedArgs(desc.split(/ +/));\n};\n\n/**\n * Add an implicit `help [cmd]` subcommand\n * which invokes `--help` for the given command.\n *\n * @api private\n */\n\nCommand.prototype.addImplicitHelpCommand = function() {\n this.command('help [cmd]', 'display help for [cmd]');\n};\n\n/**\n * Parse expected `args`.\n *\n * For example `[\"[type]\"]` becomes `[{ required: false, name: 'type' }]`.\n *\n * @param {Array} args\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.parseExpectedArgs = function(args) {\n if (!args.length) return;\n var self = this;\n args.forEach(function(arg) {\n var argDetails = {\n required: false,\n name: '',\n variadic: false\n };\n\n switch (arg[0]) {\n case '<':\n argDetails.required = true;\n argDetails.name = arg.slice(1, -1);\n break;\n case '[':\n argDetails.name = arg.slice(1, -1);\n break;\n }\n\n if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {\n argDetails.variadic = true;\n argDetails.name = argDetails.name.slice(0, -3);\n }\n if (argDetails.name) {\n self._args.push(argDetails);\n }\n });\n return this;\n};\n\n/**\n * Register callback `fn` for the command.\n *\n * Examples:\n *\n * program\n * .command('help')\n * .description('display verbose help')\n * .action(function() {\n * // output help here\n * });\n *\n * @param {Function} fn\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.action = function(fn) {\n var self = this;\n var listener = function(args, unknown) {\n // Parse any so-far unknown options\n args = args || [];\n unknown = unknown || [];\n\n var parsed = self.parseOptions(unknown);\n\n // Output help if necessary\n outputHelpIfNecessary(self, parsed.unknown);\n\n // If there are still any unknown options, then we simply\n // die, unless someone asked for help, in which case we give it\n // to them, and then we die.\n if (parsed.unknown.length > 0) {\n self.unknownOption(parsed.unknown[0]);\n }\n\n // Leftover arguments need to be pushed back. Fixes issue #56\n if (parsed.args.length) args = parsed.args.concat(args);\n\n self._args.forEach(function(arg, i) {\n if (arg.required && args[i] == null) {\n self.missingArgument(arg.name);\n } else if (arg.variadic) {\n if (i !== self._args.length - 1) {\n self.variadicArgNotLast(arg.name);\n }\n\n args[i] = args.splice(i);\n }\n });\n\n // Always append ourselves to the end of the arguments,\n // to make sure we match the number of arguments the user\n // expects\n if (self._args.length) {\n args[self._args.length] = self;\n } else {\n args.push(self);\n }\n\n fn.apply(self, args);\n };\n var parent = this.parent || this;\n var name = parent === this ? '*' : this._name;\n parent.on('command:' + name, listener);\n if (this._alias) parent.on('command:' + this._alias, listener);\n return this;\n};\n\n/**\n * Define option with `flags`, `description` and optional\n * coercion `fn`.\n *\n * The `flags` string should contain both the short and long flags,\n * separated by comma, a pipe or space. The following are all valid\n * all will output this way when `--help` is used.\n *\n * \"-p, --pepper\"\n * \"-p|--pepper\"\n * \"-p --pepper\"\n *\n * Examples:\n *\n * // simple boolean defaulting to false\n * program.option('-p, --pepper', 'add pepper');\n *\n * --pepper\n * program.pepper\n * // => Boolean\n *\n * // simple boolean defaulting to true\n * program.option('-C, --no-cheese', 'remove cheese');\n *\n * program.cheese\n * // => true\n *\n * --no-cheese\n * program.cheese\n * // => false\n *\n * // required argument\n * program.option('-C, --chdir <path>', 'change the working directory');\n *\n * --chdir /tmp\n * program.chdir\n * // => \"/tmp\"\n *\n * // optional argument\n * program.option('-c, --cheese [type]', 'add cheese [marble]');\n *\n * @param {String} flags\n * @param {String} description\n * @param {Function|*} [fn] or default\n * @param {*} [defaultValue]\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.option = function(flags, description, fn, defaultValue) {\n var self = this,\n option = new Option(flags, description),\n oname = option.name(),\n name = option.attributeName();\n\n // default as 3rd arg\n if (typeof fn !== 'function') {\n if (fn instanceof RegExp) {\n var regex = fn;\n fn = function(val, def) {\n var m = regex.exec(val);\n return m ? m[0] : def;\n };\n } else {\n defaultValue = fn;\n fn = null;\n }\n }\n\n // preassign default value only for --no-*, [optional], or <required>\n if (!option.bool || option.optional || option.required) {\n // when --no-* we make sure default is true\n if (!option.bool) defaultValue = true;\n // preassign only if we have a default\n if (defaultValue !== undefined) {\n self[name] = defaultValue;\n option.defaultValue = defaultValue;\n }\n }\n\n // register the option\n this.options.push(option);\n\n // when it's passed assign the value\n // and conditionally invoke the callback\n this.on('option:' + oname, function(val) {\n // coercion\n if (val !== null && fn) {\n val = fn(val, self[name] === undefined ? defaultValue : self[name]);\n }\n\n // unassigned or bool\n if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {\n // if no value, bool true, and we have a default, then use it!\n if (val == null) {\n self[name] = option.bool\n ? defaultValue || true\n : false;\n } else {\n self[name] = val;\n }\n } else if (val !== null) {\n // reassign\n self[name] = val;\n }\n });\n\n return this;\n};\n\n/**\n * Allow unknown options on the command line.\n *\n * @param {Boolean} arg if `true` or omitted, no error will be thrown\n * for unknown options.\n * @api public\n */\nCommand.prototype.allowUnknownOption = function(arg) {\n this._allowUnknownOption = arguments.length === 0 || arg;\n return this;\n};\n\n/**\n * Parse `argv`, settings options and invoking commands when defined.\n *\n * @param {Array} argv\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.parse = function(argv) {\n // implicit help\n if (this.executables) this.addImplicitHelpCommand();\n\n // store raw args\n this.rawArgs = argv;\n\n // guess name\n this._name = this._name || basename(argv[1], '.js');\n\n // github-style sub-commands with no sub-command\n if (this.executables && argv.length < 3 && !this.defaultExecutable) {\n // this user needs help\n argv.push('--help');\n }\n\n // process argv\n var parsed = this.parseOptions(this.normalize(argv.slice(2)));\n var args = this.args = parsed.args;\n\n var result = this.parseArgs(this.args, parsed.unknown);\n\n // executable sub-commands\n var name = result.args[0];\n\n var aliasCommand = null;\n // check alias of sub commands\n if (name) {\n aliasCommand = this.commands.filter(function(command) {\n return command.alias() === name;\n })[0];\n }\n\n if (this._execs[name] === true) {\n return this.executeSubCommand(argv, args, parsed.unknown);\n } else if (aliasCommand) {\n // is alias of a subCommand\n args[0] = aliasCommand._name;\n return this.executeSubCommand(argv, args, parsed.unknown);\n } else if (this.defaultExecutable) {\n // use the default subcommand\n args.unshift(this.defaultExecutable);\n return this.executeSubCommand(argv, args, parsed.unknown);\n }\n\n return result;\n};\n\n/**\n * Execute a sub-command executable.\n *\n * @param {Array} argv\n * @param {Array} args\n * @param {Array} unknown\n * @api private\n */\n\nCommand.prototype.executeSubCommand = function(argv, args, unknown) {\n args = args.concat(unknown);\n\n if (!args.length) this.help();\n if (args[0] === 'help' && args.length === 1) this.help();\n\n // <cmd> --help\n if (args[0] === 'help') {\n args[0] = args[1];\n args[1] = '--help';\n }\n\n // executable\n var f = argv[1];\n // name of the subcommand, link `pm-install`\n var bin = basename(f, path.extname(f)) + '-' + args[0];\n\n // In case of globally installed, get the base dir where executable\n // subcommand file should be located at\n var baseDir;\n\n var resolvedLink = fs.realpathSync(f);\n\n baseDir = dirname(resolvedLink);\n\n // prefer local `./<bin>` to bin in the $PATH\n var localBin = path.join(baseDir, bin);\n\n // whether bin file is a js script with explicit `.js` or `.ts` extension\n var isExplicitJS = false;\n if (exists(localBin + '.js')) {\n bin = localBin + '.js';\n isExplicitJS = true;\n } else if (exists(localBin + '.ts')) {\n bin = localBin + '.ts';\n isExplicitJS = true;\n } else if (exists(localBin)) {\n bin = localBin;\n }\n\n args = args.slice(1);\n\n var proc;\n if (process.platform !== 'win32') {\n if (isExplicitJS) {\n args.unshift(bin);\n // add executable arguments to spawn\n args = (process.execArgv || []).concat(args);\n\n proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });\n } else {\n proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });\n }\n } else {\n args.unshift(bin);\n proc = spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach(function(signal) {\n process.on(signal, function() {\n if (proc.killed === false && proc.exitCode === null) {\n proc.kill(signal);\n }\n });\n });\n proc.on('close', process.exit.bind(process));\n proc.on('error', function(err) {\n if (err.code === 'ENOENT') {\n console.error('error: %s(1) does not exist, try --help', bin);\n } else if (err.code === 'EACCES') {\n console.error('error: %s(1) not executable. try chmod or run with root', bin);\n }\n process.exit(1);\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n};\n\n/**\n * Normalize `args`, splitting joined short flags. For example\n * the arg \"-abc\" is equivalent to \"-a -b -c\".\n * This also normalizes equal sign and splits \"--abc=def\" into \"--abc def\".\n *\n * @param {Array} args\n * @return {Array}\n * @api private\n */\n\nCommand.prototype.normalize = function(args) {\n var ret = [],\n arg,\n lastOpt,\n index;\n\n for (var i = 0, len = args.length; i < len; ++i) {\n arg = args[i];\n if (i > 0) {\n lastOpt = this.optionFor(args[i - 1]);\n }\n\n if (arg === '--') {\n // Honor option terminator\n ret = ret.concat(args.slice(i));\n break;\n } else if (lastOpt && lastOpt.required) {\n ret.push(arg);\n } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {\n arg.slice(1).split('').forEach(function(c) {\n ret.push('-' + c);\n });\n } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {\n ret.push(arg.slice(0, index), arg.slice(index + 1));\n } else {\n ret.push(arg);\n }\n }\n\n return ret;\n};\n\n/**\n * Parse command `args`.\n *\n * When listener(s) are available those\n * callbacks are invoked, otherwise the \"*\"\n * event is emitted and those actions are invoked.\n *\n * @param {Array} args\n * @return {Command} for chaining\n * @api private\n */\n\nCommand.prototype.parseArgs = function(args, unknown) {\n var name;\n\n if (args.length) {\n name = args[0];\n if (this.listeners('command:' + name).length) {\n this.emit('command:' + args.shift(), args, unknown);\n } else {\n this.emit('command:*', args);\n }\n } else {\n outputHelpIfNecessary(this, unknown);\n\n // If there were no args and we have unknown options,\n // then they are extraneous and we need to error.\n if (unknown.length > 0) {\n this.unknownOption(unknown[0]);\n }\n if (this.commands.length === 0 &&\n this._args.filter(function(a) { return a.required; }).length === 0) {\n this.emit('command:*');\n }\n }\n\n return this;\n};\n\n/**\n * Return an option matching `arg` if any.\n *\n * @param {String} arg\n * @return {Option}\n * @api private\n */\n\nCommand.prototype.optionFor = function(arg) {\n for (var i = 0, len = this.options.length; i < len; ++i) {\n if (this.options[i].is(arg)) {\n return this.options[i];\n }\n }\n};\n\n/**\n * Parse options from `argv` returning `argv`\n * void of these options.\n *\n * @param {Array} argv\n * @return {Array}\n * @api public\n */\n\nCommand.prototype.parseOptions = function(argv) {\n var args = [],\n len = argv.length,\n literal,\n option,\n arg;\n\n var unknownOptions = [];\n\n // parse options\n for (var i = 0; i < len; ++i) {\n arg = argv[i];\n\n // literal args after --\n if (literal) {\n args.push(arg);\n continue;\n }\n\n if (arg === '--') {\n literal = true;\n continue;\n }\n\n // find matching Option\n option = this.optionFor(arg);\n\n // option is defined\n if (option) {\n // requires arg\n if (option.required) {\n arg = argv[++i];\n if (arg == null) return this.optionMissingArgument(option);\n this.emit('option:' + option.name(), arg);\n // optional arg\n } else if (option.optional) {\n arg = argv[i + 1];\n if (arg == null || (arg[0] === '-' && arg !== '-')) {\n arg = null;\n } else {\n ++i;\n }\n this.emit('option:' + option.name(), arg);\n // bool\n } else {\n this.emit('option:' + option.name());\n }\n continue;\n }\n\n // looks like an option\n if (arg.length > 1 && arg[0] === '-') {\n unknownOptions.push(arg);\n\n // If the next argument looks like it might be\n // an argument for this option, we pass it on.\n // If it isn't, then it'll simply be ignored\n if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {\n unknownOptions.push(argv[++i]);\n }\n continue;\n }\n\n // arg\n args.push(arg);\n }\n\n return { args: args, unknown: unknownOptions };\n};\n\n/**\n * Return an object containing options as key-value pairs\n *\n * @return {Object}\n * @api public\n */\nCommand.prototype.opts = function() {\n var result = {},\n len = this.options.length;\n\n for (var i = 0; i < len; i++) {\n var key = this.options[i].attributeName();\n result[key] = key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n};\n\n/**\n * Argument `name` is missing.\n *\n * @param {String} name\n * @api private\n */\n\nCommand.prototype.missingArgument = function(name) {\n console.error(\"error: missing required argument `%s'\", name);\n process.exit(1);\n};\n\n/**\n * `Option` is missing an argument, but received `flag` or nothing.\n *\n * @param {String} option\n * @param {String} flag\n * @api private\n */\n\nCommand.prototype.optionMissingArgument = function(option, flag) {\n if (flag) {\n console.error(\"error: option `%s' argument missing, got `%s'\", option.flags, flag);\n } else {\n console.error(\"error: option `%s' argument missing\", option.flags);\n }\n process.exit(1);\n};\n\n/**\n * Unknown option `flag`.\n *\n * @param {String} flag\n * @api private\n */\n\nCommand.prototype.unknownOption = function(flag) {\n if (this._allowUnknownOption) return;\n console.error(\"error: unknown option `%s'\", flag);\n process.exit(1);\n};\n\n/**\n * Variadic argument with `name` is not the last argument as required.\n *\n * @param {String} name\n * @api private\n */\n\nCommand.prototype.variadicArgNotLast = function(name) {\n console.error(\"error: variadic arguments must be last `%s'\", name);\n process.exit(1);\n};\n\n/**\n * Set the program version to `str`.\n *\n * This method auto-registers the \"-V, --version\" flag\n * which will print the version number when passed.\n *\n * @param {String} str\n * @param {String} [flags]\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.version = function(str, flags) {\n if (arguments.length === 0) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n var versionOption = new Option(flags, 'output the version number');\n this._versionOptionName = versionOption.long.substr(2) || 'version';\n this.options.push(versionOption);\n this.on('option:' + this._versionOptionName, function() {\n process.stdout.write(str + '\\n');\n process.exit(0);\n });\n return this;\n};\n\n/**\n * Set the description to `str`.\n *\n * @param {String} str\n * @param {Object} argsDescription\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.description = function(str, argsDescription) {\n if (arguments.length === 0) return this._description;\n this._description = str;\n this._argsDescription = argsDescription;\n return this;\n};\n\n/**\n * Set an alias for the command\n *\n * @param {String} alias\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.alias = function(alias) {\n var command = this;\n if (this.commands.length !== 0) {\n command = this.commands[this.commands.length - 1];\n }\n\n if (arguments.length === 0) return command._alias;\n\n if (alias === command._name) throw new Error('Command alias can\\'t be the same as its name');\n\n command._alias = alias;\n return this;\n};\n\n/**\n * Set / get the command usage `str`.\n *\n * @param {String} str\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.usage = function(str) {\n var args = this._args.map(function(arg) {\n return humanReadableArgName(arg);\n });\n\n var usage = '[options]' +\n (this.commands.length ? ' [command]' : '') +\n (this._args.length ? ' ' + args.join(' ') : '');\n\n if (arguments.length === 0) return this._usage || usage;\n this._usage = str;\n\n return this;\n};\n\n/**\n * Get or set the name of the command\n *\n * @param {String} str\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.name = function(str) {\n if (arguments.length === 0) return this._name;\n this._name = str;\n return this;\n};\n\n/**\n * Return prepared commands.\n *\n * @return {Array}\n * @api private\n */\n\nCommand.prototype.prepareCommands = function() {\n return this.commands.filter(function(cmd) {\n return !cmd._noHelp;\n }).map(function(cmd) {\n var args = cmd._args.map(function(arg) {\n return humanReadableArgName(arg);\n }).join(' ');\n\n return [\n cmd._name +\n (cmd._alias ? '|' + cmd._alias : '') +\n (cmd.options.length ? ' [options]' : '') +\n (args ? ' ' + args : ''),\n cmd._description\n ];\n });\n};\n\n/**\n * Return the largest command length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestCommandLength = function() {\n var commands = this.prepareCommands();\n return commands.reduce(function(max, command) {\n return Math.max(max, command[0].length);\n }, 0);\n};\n\n/**\n * Return the largest option length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestOptionLength = function() {\n var options = [].slice.call(this.options);\n options.push({\n flags: '-h, --help'\n });\n return options.reduce(function(max, option) {\n return Math.max(max, option.flags.length);\n }, 0);\n};\n\n/**\n * Return the largest arg length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestArgLength = function() {\n return this._args.reduce(function(max, arg) {\n return Math.max(max, arg.name.length);\n }, 0);\n};\n\n/**\n * Return the pad width.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.padWidth = function() {\n var width = this.largestOptionLength();\n if (this._argsDescription && this._args.length) {\n if (this.largestArgLength() > width) {\n width = this.largestArgLength();\n }\n }\n\n if (this.commands && this.commands.length) {\n if (this.largestCommandLength() > width) {\n width = this.largestCommandLength();\n }\n }\n\n return width;\n};\n\n/**\n * Return help for options.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.optionHelp = function() {\n var width = this.padWidth();\n\n // Append the help information\n return this.options.map(function(option) {\n return pad(option.flags, width) + ' ' + option.description +\n ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');\n }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])\n .join('\\n');\n};\n\n/**\n * Return command help documentation.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.commandHelp = function() {\n if (!this.commands.length) return '';\n\n var commands = this.prepareCommands();\n var width = this.padWidth();\n\n return [\n 'Commands:',\n commands.map(function(cmd) {\n var desc = cmd[1] ? ' ' + cmd[1] : '';\n return (desc ? pad(cmd[0], width) : cmd[0]) + desc;\n }).join('\\n').replace(/^/gm, ' '),\n ''\n ].join('\\n');\n};\n\n/**\n * Return program help documentation.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.helpInformation = function() {\n var desc = [];\n if (this._description) {\n desc = [\n this._description,\n ''\n ];\n\n var argsDescription = this._argsDescription;\n if (argsDescription && this._args.length) {\n var width = this.padWidth();\n desc.push('Arguments:');\n desc.push('');\n this._args.forEach(function(arg) {\n desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);\n });\n desc.push('');\n }\n }\n\n var cmdName = this._name;\n if (this._alias) {\n cmdName = cmdName + '|' + this._alias;\n }\n var usage = [\n 'Usage: ' + cmdName + ' ' + this.usage(),\n ''\n ];\n\n var cmds = [];\n var commandHelp = this.commandHelp();\n if (commandHelp) cmds = [commandHelp];\n\n var options = [\n 'Options:',\n '' + this.optionHelp().replace(/^/gm, ' '),\n ''\n ];\n\n return usage\n .concat(desc)\n .concat(options)\n .concat(cmds)\n .join('\\n');\n};\n\n/**\n * Output help information for this command\n *\n * @api public\n */\n\nCommand.prototype.outputHelp = function(cb) {\n if (!cb) {\n cb = function(passthru) {\n return passthru;\n };\n }\n process.stdout.write(cb(this.helpInformation()));\n this.emit('--help');\n};\n\n/**\n * Output help information and exit.\n *\n * @api public\n */\n\nCommand.prototype.help = function(cb) {\n this.outputHelp(cb);\n process.exit();\n};\n\n/**\n * Camel-case the given `flag`\n *\n * @param {String} flag\n * @return {String}\n * @api private\n */\n\nfunction camelcase(flag) {\n return flag.split('-').reduce(function(str, word) {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Pad `str` to `width`.\n *\n * @param {String} str\n * @param {Number} width\n * @return {String}\n * @api private\n */\n\nfunction pad(str, width) {\n var len = Math.max(0, width - str.length);\n return str + Array(len + 1).join(' ');\n}\n\n/**\n * Output help information if necessary\n *\n * @param {Command} command to output help for\n * @param {Array} array of options to search for -h or --help\n * @api private\n */\n\nfunction outputHelpIfNecessary(cmd, options) {\n options = options || [];\n for (var i = 0; i < options.length; i++) {\n if (options[i] === '--help' || options[i] === '-h') {\n cmd.outputHelp();\n process.exit(0);\n }\n }\n}\n\n/**\n * Takes an argument an returns its human readable equivalent for help usage.\n *\n * @param {Object} arg\n * @return {String}\n * @api private\n */\n\nfunction humanReadableArgName(arg) {\n var nameOutput = arg.name + (arg.variadic === true ? '...' : '');\n\n return arg.required\n ? '<' + nameOutput + '>'\n : '[' + nameOutput + ']';\n}\n\n// for versions before node v0.8 when there weren't `fs.existsSync`\nfunction exists(file) {\n try {\n if (fs.statSync(file).isFile()) {\n return true;\n }\n } catch (e) {\n return false;\n }\n}\n", "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\n/* global global, define, System, Reflect, Promise */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __createBinding;\r\n(function (factory) {\r\n var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n if (typeof define === \"function\" && define.amd) {\r\n define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n }\r\n else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n factory(createExporter(root, createExporter(module.exports)));\r\n }\r\n else {\r\n factory(createExporter(root));\r\n }\r\n function createExporter(exports, previous) {\r\n if (exports !== root) {\r\n if (typeof Object.create === \"function\") {\r\n Object.defineProperty(exports, \"__esModule\", { value: true });\r\n }\r\n else {\r\n exports.__esModule = true;\r\n }\r\n }\r\n return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n }\r\n})\r\n(function (exporter) {\r\n var extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\n __extends = function (d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n\r\n __assign = Object.assign || function (t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n\r\n __rest = function (s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n };\r\n\r\n __decorate = function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n };\r\n\r\n __param = function (paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n };\r\n\r\n __metadata = function (metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n };\r\n\r\n __awaiter = function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n };\r\n\r\n __generator = function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n };\r\n\r\n __createBinding = function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n };\r\n\r\n __exportStar = function (m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n };\r\n\r\n __values = function (o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n };\r\n\r\n __read = function (o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n };\r\n\r\n __spread = function () {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n };\r\n\r\n __spreadArrays = function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n };\r\n\r\n __await = function (v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n };\r\n\r\n __asyncGenerator = function (thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n };\r\n\r\n __asyncDelegator = function (o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n };\r\n\r\n __asyncValues = function (o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n };\r\n\r\n __makeTemplateObject = function (cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n };\r\n\r\n __importStar = function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result[\"default\"] = mod;\r\n return result;\r\n };\r\n\r\n __importDefault = function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n };\r\n\r\n __classPrivateFieldGet = function (receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n };\r\n\r\n __classPrivateFieldSet = function (receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n };\r\n\r\n exporter(\"__extends\", __extends);\r\n exporter(\"__assign\", __assign);\r\n exporter(\"__rest\", __rest);\r\n exporter(\"__decorate\", __decorate);\r\n exporter(\"__param\", __param);\r\n exporter(\"__metadata\", __metadata);\r\n exporter(\"__awaiter\", __awaiter);\r\n exporter(\"__generator\", __generator);\r\n exporter(\"__exportStar\", __exportStar);\r\n exporter(\"__createBinding\", __createBinding);\r\n exporter(\"__values\", __values);\r\n exporter(\"__read\", __read);\r\n exporter(\"__spread\", __spread);\r\n exporter(\"__spreadArrays\", __spreadArrays);\r\n exporter(\"__await\", __await);\r\n exporter(\"__asyncGenerator\", __asyncGenerator);\r\n exporter(\"__asyncDelegator\", __asyncDelegator);\r\n exporter(\"__asyncValues\", __asyncValues);\r\n exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n exporter(\"__importStar\", __importStar);\r\n exporter(\"__importDefault\", __importDefault);\r\n exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n});\r\n", "/** Console logging verbosity for the SDK. */\nexport enum LogLevel {\n /** No logs will be generated. */\n None = 0,\n /** Only SDK internal errors will be logged. */\n Error = 1,\n /** Information useful for debugging the SDK will be logged. */\n Debug = 2,\n /** All SDK actions will be logged. */\n Verbose = 3,\n}\n", "import { User } from './user';\n\n/**\n * @inheritdoc\n */\nexport interface Session extends SessionContext {\n /** JSDoc */\n update(context?: SessionContext): void;\n\n /** JSDoc */\n close(status?: SessionStatus): void;\n\n /** JSDoc */\n toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n };\n}\n\nexport interface RequestSession {\n status?: RequestSessionStatus;\n}\n\n/**\n * Session Context\n */\nexport interface SessionContext {\n sid?: string;\n did?: string;\n init?: boolean;\n // seconds since the UNIX epoch\n timestamp?: number;\n // seconds since the UNIX epoch\n started?: number;\n duration?: number;\n status?: SessionStatus;\n release?: string;\n environment?: string;\n userAgent?: string;\n ipAddress?: string;\n errors?: number;\n user?: User | null;\n ignoreDuration?: boolean;\n}\n\n/**\n * Session Status\n */\nexport enum SessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Exited = 'exited',\n /** JSDoc */\n Crashed = 'crashed',\n /** JSDoc */\n Abnormal = 'abnormal',\n}\n\nexport enum RequestSessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Errored = 'errored',\n /** JSDoc */\n Crashed = 'crashed',\n}\n\n/** JSDoc */\nexport interface SessionAggregates {\n attrs?: {\n environment?: string;\n release?: string;\n };\n aggregates: Array<AggregationCounts>;\n}\n\nexport interface SessionFlusherLike {\n /**\n * Increments the Session Status bucket in SessionAggregates Object corresponding to the status of the session\n * captured\n */\n incrementSessionStatusCount(): void;\n\n /** Submits the aggregates request mode sessions to Sentry */\n sendSessionAggregates(sessionAggregates: SessionAggregates): void;\n\n /** Empties Aggregate Buckets and Sends them to Transport Buffer */\n flush(): void;\n\n /** Clears setInterval and calls flush */\n close(): void;\n}\n\nexport interface AggregationCounts {\n started: string;\n errored?: number;\n exited?: number;\n crashed?: number;\n}\n", "/** JSDoc */\n// eslint-disable-next-line import/export\nexport enum Severity {\n /** JSDoc */\n Fatal = 'fatal',\n /** JSDoc */\n Error = 'error',\n /** JSDoc */\n Warning = 'warning',\n /** JSDoc */\n Log = 'log',\n /** JSDoc */\n Info = 'info',\n /** JSDoc */\n Debug = 'debug',\n /** JSDoc */\n Critical = 'critical',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Severity {\n /**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\n export function fromString(level: string): Severity {\n switch (level) {\n case 'debug':\n return Severity.Debug;\n case 'info':\n return Severity.Info;\n case 'warn':\n case 'warning':\n return Severity.Warning;\n case 'error':\n return Severity.Error;\n case 'fatal':\n return Severity.Fatal;\n case 'critical':\n return Severity.Critical;\n case 'log':\n default:\n return Severity.Log;\n }\n }\n}\n", "/** The status of an event. */\n// eslint-disable-next-line import/export\nexport enum Status {\n /** The status could not be determined. */\n Unknown = 'unknown',\n /** The event was skipped due to configuration or callbacks. */\n Skipped = 'skipped',\n /** The event was sent to Sentry successfully. */\n Success = 'success',\n /** The client is currently rate limited and will try again later. */\n RateLimit = 'rate_limit',\n /** The event could not be processed. */\n Invalid = 'invalid',\n /** A server-side error occurred during submission. */\n Failed = 'failed',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Status {\n /**\n * Converts a HTTP status code into a {@link Status}.\n *\n * @param code The HTTP response status code.\n * @returns The send status or {@link Status.Unknown}.\n */\n export function fromHttpCode(code: number): Status {\n if (code >= 200 && code < 300) {\n return Status.Success;\n }\n\n if (code === 429) {\n return Status.RateLimit;\n }\n\n if (code >= 400 && code < 500) {\n return Status.Invalid;\n }\n\n if (code >= 500) {\n return Status.Failed;\n }\n\n return Status.Unknown;\n }\n}\n", "import { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';\nimport { Span, SpanContext } from './span';\n\n/**\n * Interface holding Transaction-specific properties\n */\nexport interface TransactionContext extends SpanContext {\n /**\n * Human-readable identifier for the transaction\n */\n name: string;\n\n /**\n * If true, sets the end timestamp of the transaction to the highest timestamp of child spans, trimming\n * the duration of the transaction. This is useful to discard extra time in the transaction that is not\n * accounted for in child spans, like what happens in the idle transaction Tracing integration, where we finish the\n * transaction after a given \"idle time\" and we don't want this \"idle time\" to be part of the transaction.\n */\n trimEnd?: boolean;\n\n /**\n * If this transaction has a parent, the parent's sampling decision\n */\n parentSampled?: boolean;\n\n /**\n * Metadata associated with the transaction, for internal SDK use.\n */\n metadata?: TransactionMetadata;\n}\n\n/**\n * Data pulled from a `sentry-trace` header\n */\nexport type TraceparentData = Pick<TransactionContext, 'traceId' | 'parentSpanId' | 'parentSampled'>;\n\n/**\n * Transaction \"Class\", inherits Span only has `setName`\n */\nexport interface Transaction extends TransactionContext, Span {\n /**\n * @inheritDoc\n */\n spanId: string;\n\n /**\n * @inheritDoc\n */\n traceId: string;\n\n /**\n * @inheritDoc\n */\n startTimestamp: number;\n\n /**\n * @inheritDoc\n */\n tags: { [key: string]: Primitive };\n\n /**\n * @inheritDoc\n */\n data: { [key: string]: any };\n\n /**\n * Metadata about the transaction\n */\n metadata: TransactionMetadata;\n\n /**\n * Set the name of the transaction\n */\n setName(name: string): void;\n\n /** Returns the current transaction properties as a `TransactionContext` */\n toContext(): TransactionContext;\n\n /** Updates the current transaction with a new `TransactionContext` */\n updateWithContext(transactionContext: TransactionContext): this;\n}\n\n/**\n * Context data passed by the user when starting a transaction, to be used by the tracesSampler method.\n */\nexport interface CustomSamplingContext {\n [key: string]: any;\n}\n\n/**\n * Data passed to the `tracesSampler` function, which forms the basis for whatever decisions it might make.\n *\n * Adds default data to data provided by the user. See {@link Hub.startTransaction}\n */\nexport interface SamplingContext extends CustomSamplingContext {\n /**\n * Context data with which transaction being sampled was created\n */\n transactionContext: TransactionContext;\n\n /**\n * Sampling decision from the parent transaction, if any.\n */\n parentSampled?: boolean;\n\n /**\n * Object representing the URL of the current page or worker script. Passed by default when using the `BrowserTracing`\n * integration.\n */\n location?: WorkerLocation;\n\n /**\n * Object representing the incoming request to a node server. Passed by default when using the TracingHandler.\n */\n request?: ExtractedNodeRequestData;\n}\n\nexport type Measurements = Record<string, { value: number }>;\n\nexport enum TransactionSamplingMethod {\n Explicit = 'explicitly_set',\n Sampler = 'client_sampler',\n Rate = 'client_rate',\n Inheritance = 'inheritance',\n}\n\nexport interface TransactionMetadata {\n transactionSampling?: { rate?: number; method?: string };\n\n /** The two halves (sentry and third-party) of a transaction's tracestate header, used for dynamic sampling */\n tracestate?: {\n sentry?: string;\n thirdparty?: string;\n };\n\n /** For transactions tracing server-side request handling, the path of the request being tracked. */\n requestPath?: string;\n}\n", "import { DsnLike } from './dsn';\nimport { Event } from './event';\nimport { SentryRequestType } from './request';\nimport { Response } from './response';\nimport { SdkMetadata } from './sdkmetadata';\nimport { Session, SessionAggregates } from './session';\n\nexport enum Outcome {\n BeforeSend = 'before_send',\n EventProcessor = 'event_processor',\n NetworkError = 'network_error',\n QueueOverflow = 'queue_overflow',\n RateLimitBackoff = 'ratelimit_backoff',\n SampleRate = 'sample_rate',\n}\n\n/** Transport used sending data to Sentry */\nexport interface Transport {\n /**\n * Sends the event to the Store endpoint in Sentry.\n *\n * @param event Event that should be sent to Sentry.\n */\n sendEvent(event: Event): PromiseLike<Response>;\n\n /**\n * Sends the session to the Envelope endpoint in Sentry.\n *\n * @param session Session that should be sent to Sentry | Session Aggregates that should be sent to Sentry.\n */\n sendSession?(session: Session | SessionAggregates): PromiseLike<Response>;\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the transport should wait for events to be flushed. Omitting this parameter will\n * cause the transport to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n close(timeout?: number): PromiseLike<boolean>;\n\n /**\n * Increment the counter for the specific client outcome\n */\n recordLostEvent?(type: Outcome, category: SentryRequestType): void;\n}\n\n/** JSDoc */\nexport type TransportClass<T extends Transport> = new (options: TransportOptions) => T;\n\n/** JSDoc */\nexport interface TransportOptions {\n /** Sentry DSN */\n dsn: DsnLike;\n /** Define custom headers */\n headers?: { [key: string]: string };\n /** Set a HTTP proxy that should be used for outbound requests. */\n httpProxy?: string;\n /** Set a HTTPS proxy that should be used for outbound requests. */\n httpsProxy?: string;\n /** HTTPS proxy certificates path */\n caCerts?: string;\n /** Fetch API init parameters */\n fetchParameters?: { [key: string]: string };\n /** The envelope tunnel to use. */\n tunnel?: string;\n /** Send SDK Client Reports. Enabled by default. */\n sendClientReports?: boolean;\n /**\n * Set of metadata about the SDK that can be internally used to enhance envelopes and events,\n * and provide additional data about every request.\n * */\n _metadata?: SdkMetadata;\n}\n", "export { Breadcrumb, BreadcrumbHint } from './breadcrumb';\nexport { Client } from './client';\nexport { Context, Contexts } from './context';\nexport { Dsn, DsnComponents, DsnLike, DsnProtocol } from './dsn';\nexport { DebugImage, DebugImageType, DebugMeta } from './debugMeta';\nexport { ExtendedError } from './error';\nexport { Event, EventHint } from './event';\nexport { EventProcessor } from './eventprocessor';\nexport { Exception } from './exception';\nexport { Extra, Extras } from './extra';\nexport { Hub } from './hub';\nexport { Integration, IntegrationClass } from './integration';\nexport { LogLevel } from './loglevel';\nexport { Mechanism } from './mechanism';\nexport { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';\nexport { Options } from './options';\nexport { Package } from './package';\nexport { QueryParams, Request, SentryRequest, SentryRequestType } from './request';\nexport { Response } from './response';\nexport { Runtime } from './runtime';\nexport { CaptureContext, Scope, ScopeContext } from './scope';\nexport { SdkInfo } from './sdkinfo';\nexport { SdkMetadata } from './sdkmetadata';\nexport {\n SessionAggregates,\n AggregationCounts,\n Session,\n SessionContext,\n SessionStatus,\n RequestSession,\n RequestSessionStatus,\n SessionFlusherLike,\n} from './session';\nexport { Severity } from './severity';\nexport { Span, SpanContext } from './span';\nexport { StackFrame } from './stackframe';\nexport { Stacktrace } from './stacktrace';\nexport { Status } from './status';\nexport {\n CustomSamplingContext,\n Measurements,\n SamplingContext,\n TraceparentData,\n Transaction,\n TransactionContext,\n TransactionMetadata,\n TransactionSamplingMethod,\n} from './transaction';\nexport { Thread } from './thread';\nexport { Outcome, Transport, TransportOptions, TransportClass } from './transport';\nexport { User } from './user';\nexport { WrappedFunction } from './wrappedfunction';\n", "/**\n * Consumes the promise and logs the error when it rejects.\n * @param promise A promise to forget.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function forget(promise: PromiseLike<any>): void {\n void promise.then(null, e => {\n // TODO: Use a better logging mechanism\n // eslint-disable-next-line no-console\n console.error(e);\n });\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule<T>(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { Integration } from '@sentry/types';\n\nimport { isNodeEnv } from './node';\n\n/** Internal */\ninterface SentryGlobal {\n Sentry?: {\n Integrations?: Integration[];\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n };\n}\n\nconst fallbackGlobalObject = {};\n\n/**\n * Safely get global scope object\n *\n * @returns Global scope object\n */\nexport function getGlobalObject<T>(): T & SentryGlobal {\n return (isNodeEnv()\n ? global\n : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals\n ? window // eslint-disable-line no-restricted-globals\n : typeof self !== 'undefined'\n ? self\n : fallbackGlobalObject) as T & SentryGlobal;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport { Primitive } from '@sentry/types';\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: any): boolean {\n switch (Object.prototype.toString.call(wat)) {\n case '[object Error]':\n return true;\n case '[object Exception]':\n return true;\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object ErrorEvent]';\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object DOMError]';\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object DOMException]';\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object String]';\n}\n\n/**\n * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: any): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object Object]';\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: any): boolean {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: any): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object RegExp]';\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: any): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n", "import { getGlobalObject } from './global';\nimport { isString } from './is';\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(elem: unknown, keyAttrs?: string[]): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const MAX_OUTPUT_LEN = 80;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n\n // eslint-disable-next-line no-plusplus\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds MAX_OUTPUT_LEN\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '<unknown>';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs?.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n const global = getGlobalObject<Window>();\n try {\n return global.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n", "export const setPrototypeOf =\n Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);\n\n/**\n * setPrototypeOf polyfill using __proto__\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction setProtoOf<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n // @ts-ignore __proto__ does not exist on obj\n obj.__proto__ = proto;\n return obj as TTarget & TProto;\n}\n\n/**\n * setPrototypeOf polyfill using mixin\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction mixinProperties<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n for (const prop in proto) {\n if (!Object.prototype.hasOwnProperty.call(obj, prop)) {\n // @ts-ignore typescript complains about indexing so we remove\n obj[prop] = proto[prop];\n }\n }\n\n return obj as TTarget & TProto;\n}\n", "import { setPrototypeOf } from './polyfill';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public constructor(public message: string) {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { SentryError } from './error';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\n/** Error message */\nconst ERROR_MESSAGE = 'Invalid Dsn';\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nexport class Dsn implements DsnComponents {\n /** Protocol used to connect to Sentry. */\n public protocol!: DsnProtocol;\n /** Public authorization key (deprecated, renamed to publicKey). */\n public user!: string;\n /** Public authorization key. */\n public publicKey!: string;\n /** Private authorization key (deprecated, optional). */\n public pass!: string;\n /** Hostname of the Sentry instance. */\n public host!: string;\n /** Port of the Sentry instance. */\n public port!: string;\n /** Path */\n public path!: string;\n /** Project ID */\n public projectId!: string;\n\n /** Creates a new Dsn component */\n public constructor(from: DsnLike) {\n if (typeof from === 'string') {\n this._fromString(from);\n } else {\n this._fromComponents(from);\n }\n\n this._validate();\n }\n\n /**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\n public toString(withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = this;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n }\n\n /** Parses a string into this Dsn. */\n private _fromString(str: string): void {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(ERROR_MESSAGE);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n this._fromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n }\n\n /** Maps Dsn components into this instance. */\n private _fromComponents(components: DsnComponents): void {\n // TODO this is for backwards compatibility, and can be removed in a future version\n if ('user' in components && !('publicKey' in components)) {\n components.publicKey = components.user;\n }\n this.user = components.publicKey || '';\n\n this.protocol = components.protocol;\n this.publicKey = components.publicKey || '';\n this.pass = components.pass || '';\n this.host = components.host;\n this.port = components.port || '';\n this.path = components.path || '';\n this.projectId = components.projectId;\n }\n\n /** Validates this Dsn and throws on error. */\n private _validate(): void {\n ['protocol', 'publicKey', 'host', 'projectId'].forEach(component => {\n if (!this[component as keyof DsnComponents]) {\n throw new SentryError(`${ERROR_MESSAGE}: ${component} missing`);\n }\n });\n\n if (!this.projectId.match(/^\\d+$/)) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid projectId ${this.projectId}`);\n }\n\n if (this.protocol !== 'http' && this.protocol !== 'https') {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid protocol ${this.protocol}`);\n }\n\n if (this.port && isNaN(parseInt(this.port, 10))) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid port ${this.port}`);\n }\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\n\n// TODO: Implement different loggers for different environments\nconst global = getGlobalObject<Window | NodeJS.Global>();\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** JSDoc */\ninterface ExtensibleConsole extends Console {\n [key: string]: any;\n}\n\n/**\n * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods.\n * Restores wrapping after the callback completes.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => any): any {\n const global = getGlobalObject<Window>();\n const levels = ['debug', 'info', 'warn', 'error', 'log', 'assert'];\n\n if (!('console' in global)) {\n return callback();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const originalConsole = (global as any).console as ExtensibleConsole;\n const wrappedLevels: { [key: string]: any } = {};\n\n // Restore all wrapped console methods\n levels.forEach(level => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (level in (global as any).console && (originalConsole[level] as WrappedFunction).__sentry_original__) {\n wrappedLevels[level] = originalConsole[level] as WrappedFunction;\n originalConsole[level] = (originalConsole[level] as WrappedFunction).__sentry_original__;\n }\n });\n\n // Perform callback manipulations\n const result = callback();\n\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level];\n });\n\n return result;\n}\n\n/** JSDoc */\nclass Logger {\n /** JSDoc */\n private _enabled: boolean;\n\n /** JSDoc */\n public constructor() {\n this._enabled = false;\n }\n\n /** JSDoc */\n public disable(): void {\n this._enabled = false;\n }\n\n /** JSDoc */\n public enable(): void {\n this._enabled = true;\n }\n\n /** JSDoc */\n public log(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.log(`${PREFIX}[Log]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public warn(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.warn(`${PREFIX}[Warn]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public error(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.error(`${PREFIX}[Error]: ${args.join(' ')}`);\n });\n }\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nglobal.__SENTRY__ = global.__SENTRY__ || {};\nconst logger = (global.__SENTRY__.logger as Logger) || (global.__SENTRY__.logger = new Logger());\n\nexport { logger };\n", "/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/**\n * Memo class used for decycle json objects. Uses WeakSet if available otherwise array.\n */\nexport class Memo {\n /** Determines if WeakSet is available */\n private readonly _hasWeakSet: boolean;\n /** Either WeakSet or Array */\n private readonly _inner: any;\n\n public constructor() {\n this._hasWeakSet = typeof WeakSet === 'function';\n this._inner = this._hasWeakSet ? new WeakSet() : [];\n }\n\n /**\n * Sets obj to remember.\n * @param obj Object to remember\n */\n public memoize(obj: any): boolean {\n if (this._hasWeakSet) {\n if (this._inner.has(obj)) {\n return true;\n }\n this._inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < this._inner.length; i++) {\n const value = this._inner[i];\n if (value === obj) {\n return true;\n }\n }\n this._inner.push(obj);\n return false;\n }\n\n /**\n * Removes object from internal storage.\n * @param obj Object to forget\n */\n public unmemoize(obj: any): void {\n if (this._hasWeakSet) {\n this._inner.delete(obj);\n } else {\n for (let i = 0; i < this._inner.length; i++) {\n if (this._inner[i] === obj) {\n this._inner.splice(i, 1);\n break;\n }\n }\n }\n }\n}\n", "const defaultFunctionName = '<anonymous>';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n", "import { isRegExp, isString } from './is';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.substr(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const ll = newLine.length;\n if (ll <= 150) {\n return newLine;\n }\n if (colno > ll) {\n // eslint-disable-next-line no-param-reassign\n colno = ll;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, ll);\n if (end > ll - 5) {\n end = ll;\n }\n if (end === ll) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < ll) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the value matches a regex or includes the string\n * @param value The string value to be checked against\n * @param pattern Either a regex or a string that must be contained in value\n */\nexport function isMatchingPattern(value: string, pattern: RegExp | string): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return (pattern as RegExp).test(value);\n }\n if (typeof pattern === 'string') {\n return value.indexOf(pattern) !== -1;\n }\n return false;\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ExtendedError, WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive, isSyntheticEvent } from './is';\nimport { Memo } from './memo';\nimport { getFunctionName } from './stacktrace';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other\n * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __sentry_original__: {\n enumerable: false,\n value: original,\n },\n });\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any object into an object literal with all its attributes\n * attached to it.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n */\nfunction getWalkSource(\n value: any,\n): {\n [key: string]: any;\n} {\n if (isError(value)) {\n const error = value as ExtendedError;\n const err: {\n [key: string]: any;\n stack: string | undefined;\n message: string;\n name: string;\n } = {\n message: error.message,\n name: error.name,\n stack: error.stack,\n };\n\n for (const i in error) {\n if (Object.prototype.hasOwnProperty.call(error, i)) {\n err[i] = error[i];\n }\n }\n\n return err;\n }\n\n if (isEvent(value)) {\n /**\n * Event-like interface that's usable in browser and node\n */\n interface SimpleEvent {\n [key: string]: unknown;\n type: string;\n target?: unknown;\n currentTarget?: unknown;\n }\n\n const event = value as SimpleEvent;\n\n const source: {\n [key: string]: any;\n } = {};\n\n // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and\n // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a\n // try-catch in at least two years and no one's complained, so that's likely not an issue anymore\n source.type = event.type;\n\n try {\n source.target = isElement(event.target)\n ? htmlTreeAsString(event.target)\n : Object.prototype.toString.call(event.target);\n } catch (_oO) {\n source.target = '<unknown>';\n }\n\n try {\n source.currentTarget = isElement(event.currentTarget)\n ? htmlTreeAsString(event.currentTarget)\n : Object.prototype.toString.call(event.currentTarget);\n } catch (_oO) {\n source.currentTarget = '<unknown>';\n }\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n source.detail = event.detail;\n }\n\n for (const attr in event) {\n if (Object.prototype.hasOwnProperty.call(event, attr)) {\n source[attr] = event[attr];\n }\n }\n\n return source;\n }\n\n return value as {\n [key: string]: any;\n };\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/** JSDoc */\nexport function normalizeToSize<T>(\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const serialized = normalize(object, depth);\n\n if (jsonSize(serialized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return serialized as T;\n}\n\n/**\n * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers,\n * booleans, null, and undefined.\n *\n * @param value The value to stringify\n * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or\n * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value,\n * unchanged.\n */\nfunction serializeValue(value: any): any {\n const type = Object.prototype.toString.call(value);\n\n // Node.js REPL notation\n if (typeof value === 'string') {\n return value;\n }\n if (type === '[object Object]') {\n return '[Object]';\n }\n if (type === '[object Array]') {\n return '[Array]';\n }\n\n const normalized = normalizeValue(value);\n return isPrimitive(normalized) ? normalized : type;\n}\n\n/**\n * normalizeValue()\n *\n * Takes unserializable input and make it serializable friendly\n *\n * - translates undefined/NaN values to \"[undefined]\"/\"[NaN]\" respectively,\n * - serializes Error objects\n * - filter global objects\n */\nfunction normalizeValue<T>(value: T, key?: any): T | string {\n if (key === 'domain' && value && typeof value === 'object' && ((value as unknown) as { _events: any })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n if (typeof (global as any) !== 'undefined' && (value as unknown) === global) {\n return '[Global]';\n }\n\n // It's safe to use `window` and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (window as any) !== 'undefined' && (value as unknown) === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (document as any) !== 'undefined' && (value as unknown) === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n return value;\n}\n\n/**\n * Walks an object to perform a normalization on it\n *\n * @param key of object that's walked in current iteration\n * @param value object to be walked\n * @param depth Optional number indicating how deep should walking be performed\n * @param memo Optional Memo class handling decycling\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function walk(key: string, value: any, depth: number = +Infinity, memo: Memo = new Memo()): any {\n // If we reach the maximum depth, serialize whatever has left\n if (depth === 0) {\n return serializeValue(value);\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // If value implements `toJSON` method, call it and return early\n if (value !== null && value !== undefined && typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further\n const normalized = normalizeValue(value, key);\n if (isPrimitive(normalized)) {\n return normalized;\n }\n\n // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself\n const source = getWalkSource(value);\n\n // Create an accumulator that will act as a parent for all future itterations of that branch\n const acc = Array.isArray(value) ? [] : {};\n\n // If we already walked that branch, bail out, as it's circular reference\n if (memo.memoize(value)) {\n return '[Circular ~]';\n }\n\n // Walk all keys of the source\n for (const innerKey in source) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(source, innerKey)) {\n continue;\n }\n // Recursively walk through all the child nodes\n (acc as { [key: string]: any })[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);\n }\n\n // Once walked through all the branches, remove the parent from memo storage\n memo.unmemoize(value);\n\n // Return accumulated values\n return acc;\n}\n\n/**\n * normalize()\n *\n * - Creates a copy to prevent original input mutation\n * - Skip non-enumerablers\n * - Calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format\n * - Translates known global objects/Classes to a string representations\n * - Takes care of Error objects serialization\n * - Optionally limit depth of final output\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function normalize(input: any, depth?: number): any {\n try {\n return JSON.parse(JSON.stringify(input, (key: string, value: any) => walk(key, value, depth)));\n } catch (_oO) {\n return '**non-serializable**';\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function extractExceptionKeysForMessage(exception: any, maxLength: number = 40): string {\n const keys = Object.keys(getWalkSource(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return the new object with removed keys that value was `undefined`.\n * Works recursively on objects and arrays.\n */\nexport function dropUndefinedKeys<T>(val: T): T {\n if (isPlainObject(val)) {\n const obj = val as { [key: string]: any };\n const rv: { [key: string]: any } = {};\n for (const key of Object.keys(obj)) {\n if (typeof obj[key] !== 'undefined') {\n rv[key] = dropUndefinedKeys(obj[key]);\n }\n }\n return rv as T;\n }\n\n if (Array.isArray(val)) {\n return (val as any[]).map(dropUndefinedKeys) as any;\n }\n\n return val;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n", "import { getGlobalObject } from './global';\nimport { logger } from './logger';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in getGlobalObject<Window>())) {\n return false;\n }\n\n try {\n new Headers();\n new Request('');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n const global = getGlobalObject<Window>();\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(global.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = global.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === `function`) {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in getGlobalObject();\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default\n // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n const global = getGlobalObject<Window>();\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (global as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { isInstanceOf, isString } from './is';\nimport { logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\n\nconst global = getGlobalObject<Window>();\n\n/** Object describing handler that will be triggered for a given `type` of instrumentation */\ninterface InstrumentHandler {\n type: InstrumentHandlerType;\n callback: InstrumentHandlerCallback;\n}\ntype InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\ntype InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n logger.warn('unknown instrumentation type:', type);\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(handler: InstrumentHandler): void {\n if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {\n return;\n }\n handlers[handler.type] = handlers[handler.type] || [];\n (handlers[handler.type] as InstrumentHandlerCallback[]).push(handler.callback);\n instrument(handler.type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(\n handler,\n )}\\nError: ${e}`,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in global)) {\n return;\n }\n\n ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function(level: string): void {\n if (!(level in global.console)) {\n return;\n }\n\n fill(global.console, level, function(originalConsoleLevel: () => any): Function {\n return function(...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, global.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(global, 'fetch', function(originalFetch: () => void): () => void {\n return function(...args: any[]): void {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(global, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\ntype XHRSendInput = null | Blob | BufferSource | FormData | URLSearchParams | string;\n\n/** JSDoc */\ninterface SentryWrappedXMLHttpRequest extends XMLHttpRequest {\n [key: string]: any;\n __sentry_xhr__?: {\n method?: string;\n url?: string;\n status_code?: number;\n body?: XHRSendInput;\n };\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs: any[] = []): string {\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs: any[] = []): string {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in global)) {\n return;\n }\n\n // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.\n const requestKeys: XMLHttpRequest[] = [];\n const requestValues: Array<any>[] = [];\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function(originalOpen: () => void): () => void {\n return function(this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function(): void {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n if (xhr.__sentry_xhr__) {\n xhr.__sentry_xhr__.status_code = xhr.status;\n }\n } catch (e) {\n /* do nothing */\n }\n\n try {\n const requestPos = requestKeys.indexOf(xhr);\n if (requestPos !== -1) {\n // Make sure to pop both key and value to keep it in sync.\n requestKeys.splice(requestPos);\n const args = requestValues.splice(requestPos)[0];\n if (xhr.__sentry_xhr__ && args[0] !== undefined) {\n xhr.__sentry_xhr__.body = args[0] as XHRSendInput;\n }\n }\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function(original: WrappedFunction): Function {\n return function(...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n fill(xhrproto, 'send', function(originalSend: () => void): () => void {\n return function(this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n requestKeys.push(this);\n requestValues.push(args);\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = global.onpopstate;\n global.onpopstate = function(this: WindowEventHandlers, ...args: any[]): any {\n const to = global.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function(this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(global.history, 'pushState', historyReplacementFunction);\n fill(global.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = global.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in global)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n global.document.addEventListener('click', globalDOMEventHandler, false);\n global.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (global as any)[target] && (global as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function(originalAddEventListener: AddEventListener): AddEventListener {\n return function(\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount += 1;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(proto, 'removeEventListener', function(originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function(\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount -= 1;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n });\n });\n}\n\nlet _oldOnErrorHandler: OnErrorEventHandler = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = global.onerror;\n\n global.onerror = function(msg: any, url: any, line: any, column: any, error: any): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler: ((e: any) => void) | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = global.onunhandledrejection;\n\n global.onunhandledrejection = function(e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Event, Mechanism, StackFrame } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { snipLine } from './string';\n\n/**\n * Extended Window interface that allows for Crypto API usage in IE browsers\n */\ninterface MsCryptoWindow extends Window {\n msCrypto?: Crypto;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const global = getGlobalObject() as MsCryptoWindow;\n const crypto = global.crypto || global.msCrypto;\n\n if (!(crypto === void 0) && crypto.getRandomValues) {\n // Use window.crypto API if available\n const arr = new Uint16Array(8);\n crypto.getRandomValues(arr);\n\n // set 4 in byte 7\n // eslint-disable-next-line no-bitwise\n arr[3] = (arr[3] & 0xfff) | 0x4000;\n // set 2 most significant bits of byte 9 to '10'\n // eslint-disable-next-line no-bitwise\n arr[4] = (arr[4] & 0x3fff) | 0x8000;\n\n const pad = (num: number): string => {\n let v = num.toString(16);\n while (v.length < 4) {\n v = `0${v}`;\n }\n return v;\n };\n\n return (\n pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])\n );\n }\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {\n // eslint-disable-next-line no-bitwise\n const r = (Math.random() * 16) | 0;\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not <a/> href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(\n url: string,\n): {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n} {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n if (event.message) {\n return event.message;\n }\n if (event.exception && event.exception.values && event.exception.values[0]) {\n const exception = event.exception.values[0];\n\n if (exception.type && exception.value) {\n return `${exception.type}: ${exception.value}`;\n }\n return exception.type || exception.value || event.event_id || '<unknown>';\n }\n return event.event_id || '<unknown>';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].value = event.exception.values[0].value || value || '';\n event.exception.values[0].type = event.exception.values[0].type || type || 'Error';\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial<Mechanism>): void {\n if (!event.exception || !event.exception.values) {\n return;\n }\n const exceptionValue0 = event.exception.values[0];\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = exceptionValue0.mechanism;\n exceptionValue0.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n exceptionValue0.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst 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-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\nconst defaultRetryAfter = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param now current unix timestamp\n * @param header string representation of 'Retry-After' header\n */\nexport function parseRetryAfterHeader(now: number, header?: string | number | null): number {\n if (!header) {\n return defaultRetryAfter;\n }\n\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return defaultRetryAfter;\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n const lineno = frame.lineno || 0;\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if ((exception as any)?.__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n Object.defineProperty(exception, '__sentry_captured__', {\n value: true,\n });\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n", "// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js\n\n/** JSDoc */\nfunction normalizeArray(parts: string[], allowAboveRoot?: boolean): string[] {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n // eslint-disable-next-line no-plusplus\n up++;\n } else if (up) {\n parts.splice(i, 1);\n // eslint-disable-next-line no-plusplus\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n // eslint-disable-next-line no-plusplus\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^/]+?|)(\\.[^./]*|))(?:[/]*)$/;\n/** JSDoc */\nfunction splitPath(filename: string): string[] {\n const parts = splitPathRe.exec(filename);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nexport function resolve(...args: string[]): string {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr: string[]): string[] {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nexport function relative(from: string, to: string): string {\n /* eslint-disable no-param-reassign */\n from = resolve(from).substr(1);\n to = resolve(to).substr(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nexport function normalizePath(path: string): string {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.substr(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nexport function isAbsolute(path: string): boolean {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nexport function join(...args: string[]): string {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nexport function dirname(path: string): string {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nexport function basename(path: string, ext?: string): string {\n let f = splitPath(path)[2];\n if (ext && f.substr(ext.length * -1) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n}\n", "/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 'PENDING',\n /** Resolved / OK */\n RESOLVED = 'RESOLVED',\n /** Rejected / Error */\n REJECTED = 'REJECTED',\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise<T> implements PromiseLike<T> {\n private _state: States = States.PENDING;\n private _handlers: Array<{\n done: boolean;\n onfulfilled?: ((value: T) => T | PromiseLike<T>) | null;\n onrejected?: ((reason: any) => any) | null;\n }> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike<T> | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public static resolve<T>(value: T | PromiseLike<T>): PromiseLike<T> {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n }\n\n /** JSDoc */\n public static reject<T = never>(reason?: any): PromiseLike<T> {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n }\n\n /** JSDoc */\n public static all<U = any>(collection: Array<U | PromiseLike<U>>): PromiseLike<U[]> {\n return new SyncPromise<U[]>((resolve, reject) => {\n if (!Array.isArray(collection)) {\n reject(new TypeError(`Promise.all requires an array as input.`));\n return;\n }\n\n if (collection.length === 0) {\n resolve([]);\n return;\n }\n\n let counter = collection.length;\n const resolvedCollection: U[] = [];\n\n collection.forEach((item, index) => {\n void SyncPromise.resolve(item)\n .then(value => {\n resolvedCollection[index] = value;\n counter -= 1;\n\n if (counter !== 0) {\n return;\n }\n resolve(resolvedCollection);\n })\n .then(null, reject);\n });\n });\n }\n\n /** JSDoc */\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\n return new SyncPromise((resolve, reject) => {\n this._attachHandler({\n done: false,\n onfulfilled: result => {\n if (!onfulfilled) {\n // TODO: \u00AF\\_(\u30C4)_/\u00AF\n // TODO: FIXME\n resolve(result as any);\n return;\n }\n try {\n resolve(onfulfilled(result));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n onrejected: reason => {\n if (!onrejected) {\n reject(reason);\n return;\n }\n try {\n resolve(onrejected(reason));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n });\n });\n }\n\n /** JSDoc */\n public catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): PromiseLike<T | TResult> {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally<TResult>(onfinally?: (() => void) | null): PromiseLike<TResult> {\n return new SyncPromise<TResult>((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve((val as unknown) as any);\n });\n });\n }\n\n /** JSDoc */\n public toString(): string {\n return '[object SyncPromise]';\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike<T> | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike<T> | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike<T>).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n // TODO: FIXME\n /** JSDoc */\n private readonly _attachHandler = (handler: {\n /** JSDoc */\n done: boolean;\n /** JSDoc */\n onfulfilled?(value: T): any;\n /** JSDoc */\n onrejected?(reason: any): any;\n }) => {\n this._handlers = this._handlers.concat(handler);\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler.done) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n if (handler.onfulfilled) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler.onfulfilled((this._value as unknown) as any);\n }\n }\n\n if (this._state === States.REJECTED) {\n if (handler.onrejected) {\n handler.onrejected(this._value);\n }\n }\n\n handler.done = true;\n });\n };\n}\n\nexport { SyncPromise };\n", "import { SentryError } from './error';\nimport { SyncPromise } from './syncpromise';\n\n/** A simple queue that holds promises. */\nexport class PromiseBuffer<T> {\n /** Internal set of queued Promises */\n private readonly _buffer: Array<PromiseLike<T>> = [];\n\n public constructor(protected _limit?: number) {}\n\n /**\n * Says if the buffer is ready to take more requests\n */\n public isReady(): boolean {\n return this._limit === undefined || this.length() < this._limit;\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:\n * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n public add(taskProducer: () => PromiseLike<T>): PromiseLike<T> {\n if (!this.isReady()) {\n return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (this._buffer.indexOf(task) === -1) {\n this._buffer.push(task);\n }\n void task\n .then(() => this.remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n this.remove(task).then(null, () => {\n // We have to add another catch here because `this.remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike<T>\n * @returns Removed promise.\n */\n public remove(task: PromiseLike<T>): PromiseLike<T> {\n const removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];\n return removedTask;\n }\n\n /**\n * This function returns the number of unresolved promises in the queue.\n */\n public length(): number {\n return this._buffer.length;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise<boolean>(resolve => {\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n void SyncPromise.all(this._buffer)\n .then(() => {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n })\n .then(null, () => {\n resolve(true);\n });\n });\n }\n}\n", "import { getGlobalObject } from './global';\nimport { dynamicRequire, isNodeEnv } from './node';\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = getGlobalObject<Window>();\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = getGlobalObject<Window>();\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n", "export * from './async';\nexport * from './browser';\nexport * from './dsn';\nexport * from './error';\nexport * from './global';\nexport * from './instrument';\nexport * from './is';\nexport * from './logger';\nexport * from './memo';\nexport * from './misc';\nexport * from './node';\nexport * from './object';\nexport * from './path';\nexport * from './promisebuffer';\nexport * from './stacktrace';\nexport * from './string';\nexport * from './supports';\nexport * from './syncpromise';\nexport * from './time';\n", "/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Severity,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, getGlobalObject, isPlainObject, isThenable, SyncPromise } from '@sentry/utils';\n\nimport { Session } from './session';\n\n/**\n * Absolute maximum number of breadcrumbs added to an event.\n * The `maxBreadcrumbs` option cannot be higher than this value.\n */\nconst MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean = false;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void> = [];\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[] = [];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[] = [];\n\n /** User */\n protected _user: User = {};\n\n /** Tags */\n protected _tags: { [key: string]: Primitive } = {};\n\n /** Extra */\n protected _extra: Extras = {};\n\n /** Contexts */\n protected _contexts: Contexts = {};\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: Severity;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n this._session.update({ user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(level: Severity): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Can be removed in major version.\n * @deprecated in favor of {@link this.setTransactionName}\n */\n public setTransaction(name?: string): this {\n return this.setTransactionName(name);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts = { ...this._contexts, [key]: context };\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // often, this span will be a transaction, but it's not guaranteed to be\n const span = this.getSpan() as undefined | (Span & { spanRecorder: { spans: Span[] } });\n\n // try it the new way first\n if (span?.transaction) {\n return span?.transaction;\n }\n\n // fallback to the old way (known bug: this only finds transactions with sampled = true)\n if (span?.spanRecorder?.spans[0]) {\n return span.spanRecorder.spans[0] as Transaction;\n }\n\n // neither way found a transaction\n return undefined;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as <T>(scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Applies the current context and fingerprint to the event.\n * Note that breadcrumbs will be added by the client.\n * Also if the event has already breadcrumbs on it, we do not merge them.\n * @param event Event\n * @param hint May contain additional information about the original exception.\n * @hidden\n */\n public applyToEvent(event: Event, hint?: EventHint): PromiseLike<Event | null> {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction?.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint?: EventHint,\n index: number = 0,\n ): PromiseLike<Event | null> {\n return new SyncPromise<Event | null>((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n if (isThenable(result)) {\n void (result as PromiseLike<Event | null>)\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n const global = getGlobalObject<any>();\n global.__SENTRY__ = global.__SENTRY__ || {};\n global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || [];\n return global.__SENTRY__.globalEventProcessors;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n", "import { Session as SessionInterface, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * @inheritdoc\n */\nexport class Session implements SessionInterface {\n public userAgent?: string;\n public errors: number = 0;\n public release?: string;\n public sid: string = uuid4();\n public did?: string;\n public timestamp: number;\n public started: number;\n public duration?: number = 0;\n public status: SessionStatus = SessionStatus.Ok;\n public environment?: string;\n public ipAddress?: string;\n public init: boolean = true;\n public ignoreDuration: boolean = false;\n\n public constructor(context?: Omit<SessionContext, 'started' | 'status'>) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n this.timestamp = startingTime;\n this.started = startingTime;\n if (context) {\n this.update(context);\n }\n }\n\n /** JSDoc */\n // eslint-disable-next-line complexity\n public update(context: SessionContext = {}): void {\n if (context.user) {\n if (!this.ipAddress && context.user.ip_address) {\n this.ipAddress = context.user.ip_address;\n }\n\n if (!this.did && !context.did) {\n this.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n this.timestamp = context.timestamp || timestampInSeconds();\n if (context.ignoreDuration) {\n this.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. \u2014 Kamil\n this.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n this.init = context.init;\n }\n if (!this.did && context.did) {\n this.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n this.started = context.started;\n }\n if (this.ignoreDuration) {\n this.duration = undefined;\n } else if (typeof context.duration === 'number') {\n this.duration = context.duration;\n } else {\n const duration = this.timestamp - this.started;\n this.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n this.release = context.release;\n }\n if (context.environment) {\n this.environment = context.environment;\n }\n if (!this.ipAddress && context.ipAddress) {\n this.ipAddress = context.ipAddress;\n }\n if (!this.userAgent && context.userAgent) {\n this.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n this.errors = context.errors;\n }\n if (context.status) {\n this.status = context.status;\n }\n }\n\n /** JSDoc */\n public close(status?: Exclude<SessionStatus, SessionStatus.Ok>): void {\n if (status) {\n this.update({ status });\n } else if (this.status === SessionStatus.Ok) {\n this.update({ status: SessionStatus.Exited });\n } else {\n this.update();\n }\n }\n\n /** JSDoc */\n public toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n } {\n return dropUndefinedKeys({\n sid: `${this.sid}`,\n init: this.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(this.started * 1000).toISOString(),\n timestamp: new Date(this.timestamp * 1000).toISOString(),\n status: this.status,\n errors: this.errors,\n did: typeof this.did === 'number' || typeof this.did === 'string' ? `${this.did}` : undefined,\n duration: this.duration,\n attrs: dropUndefinedKeys({\n release: this.release,\n environment: this.environment,\n ip_address: this.ipAddress,\n user_agent: this.userAgent,\n }),\n });\n }\n}\n", "/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n SessionContext,\n SessionStatus,\n Severity,\n Span,\n SpanContext,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils';\n\nimport { Scope } from './scope';\nimport { Session } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope?: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Hack to prevent bundlers from breaking our usage of the domain package in the cross-platform Hub package */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n domain?: { [key: string]: any };\n } & {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @hidden\n * @deprecated Can be removed once `Hub.getActiveDomain` is removed.\n */\nexport interface DomainAsCarrier extends Carrier {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: { [key: string]: any }[];\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[] = [{}];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient<C extends Client>(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope | undefined {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint): string {\n const eventId = (this._lastEventId = uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: exception,\n syntheticException,\n };\n }\n\n this._invokeClient('captureException', exception, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint): string {\n const eventId = (this._lastEventId = uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: message,\n syntheticException,\n };\n }\n\n this._invokeClient('captureMessage', message, level, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = uuid4();\n if (event.type !== 'transaction') {\n this._lastEventId = eventId;\n }\n\n this._invokeClient('captureEvent', event, {\n ...hint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSpan(context: SpanContext): Span {\n return this._callExtensionMethod('startSpan', context);\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n this.getStackTop()\n ?.scope?.getSession()\n ?.close();\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n this.getStackTop()?.scope?.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const global = getGlobalObject<{ navigator?: { userAgent?: string } }>();\n const { userAgent } = global.navigator || {};\n\n const session = new Session({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === SessionStatus.Ok) {\n currentSession.update({ status: SessionStatus.Exited });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n\n return session;\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession && scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _invokeClient<M extends keyof Client>(method: M, ...args: any[]): void {\n const { scope, client } = this.getStackTop();\n if (client && client[method]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (client as any)[method](...args, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod<T>(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n const carrier = getGlobalObject();\n carrier.__SENTRY__ = carrier.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return carrier;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Returns the active domain, if one exists\n * @deprecated No longer used; remove in v7\n * @returns The domain, or undefined if there is no active domain\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveDomain(): DomainAsCarrier | undefined {\n logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');\n\n const sentry = getMainCarrier().__SENTRY__;\n\n return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry: Carrier): Hub {\n try {\n const activeDomain = getMainCarrier().__SENTRY__?.extensions?.domain?.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) return carrier.__SENTRY__.hub;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = new Hub();\n return carrier.__SENTRY__.hub;\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = hub;\n return true;\n}\n", "import {\n AggregationCounts,\n RequestSessionStatus,\n SessionAggregates,\n SessionFlusherLike,\n Transport,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\n\ntype ReleaseHealthAttributes = {\n environment?: string;\n release: string;\n};\n\n/**\n * @inheritdoc\n */\nexport class SessionFlusher implements SessionFlusherLike {\n public readonly flushTimeout: number = 60;\n private _pendingAggregates: Record<number, AggregationCounts> = {};\n private _sessionAttrs: ReleaseHealthAttributes;\n private _intervalId: ReturnType<typeof setInterval>;\n private _isEnabled: boolean = true;\n private _transport: Transport;\n\n public constructor(transport: Transport, attrs: ReleaseHealthAttributes) {\n this._transport = transport;\n // Call to setInterval, so that flush is called every 60 seconds\n this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);\n this._sessionAttrs = attrs;\n }\n\n /** Sends session aggregates to Transport */\n public sendSessionAggregates(sessionAggregates: SessionAggregates): void {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n void this._transport.sendSession(sessionAggregates).then(null, reason => {\n logger.error(`Error while sending session: ${reason}`);\n });\n }\n\n /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */\n public flush(): void {\n const sessionAggregates = this.getSessionAggregates();\n if (sessionAggregates.aggregates.length === 0) {\n return;\n }\n this._pendingAggregates = {};\n this.sendSessionAggregates(sessionAggregates);\n }\n\n /** Massages the entries in `pendingAggregates` and returns aggregated sessions */\n public getSessionAggregates(): SessionAggregates {\n const aggregates: AggregationCounts[] = Object.keys(this._pendingAggregates).map((key: string) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates: SessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return dropUndefinedKeys(sessionAggregates);\n }\n\n /** JSDoc */\n public close(): void {\n clearInterval(this._intervalId);\n this._isEnabled = false;\n this.flush();\n }\n\n /**\n * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then\n * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to\n * `_incrementSessionStatusCount` along with the start date\n */\n public incrementSessionStatusCount(): void {\n if (!this._isEnabled) {\n return;\n }\n const scope = getCurrentHub().getScope();\n const requestSession = scope?.getRequestSession();\n\n if (requestSession && requestSession.status) {\n this._incrementSessionStatusCount(requestSession.status, new Date());\n // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in\n // case captureRequestSession is called more than once to prevent double count\n scope?.setRequestSession(undefined);\n\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n }\n }\n\n /**\n * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of\n * the session received\n */\n private _incrementSessionStatusCount(status: RequestSessionStatus, date: Date): number {\n // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys\n const sessionStartedTrunc = new Date(date).setSeconds(0, 0);\n this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};\n\n // corresponds to aggregated sessions in one specific minute bucket\n // for example, {\"started\":\"2021-03-16T08:00:00.000Z\",\"exited\":4, \"errored\": 1}\n const aggregationCounts: AggregationCounts = this._pendingAggregates[sessionStartedTrunc];\n if (!aggregationCounts.started) {\n aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();\n }\n\n switch (status) {\n case RequestSessionStatus.Errored:\n aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;\n return aggregationCounts.errored;\n case RequestSessionStatus.Ok:\n aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;\n return aggregationCounts.exited;\n case RequestSessionStatus.Crashed:\n aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;\n return aggregationCounts.crashed;\n }\n }\n}\n", "export { addGlobalEventProcessor, Scope } from './scope';\nexport { Session } from './session';\nexport { SessionFlusher } from './sessionflusher';\nexport {\n // eslint-disable-next-line deprecation/deprecation\n getActiveDomain,\n getCurrentHub,\n getHubFromCarrier,\n getMainCarrier,\n Hub,\n makeMain,\n setHubOnCarrier,\n Carrier,\n // eslint-disable-next-line deprecation/deprecation\n DomainAsCarrier,\n Layer,\n} from './hub';\n", "import { getCurrentHub, Hub, Scope } from '@sentry/hub';\nimport {\n Breadcrumb,\n CaptureContext,\n CustomSamplingContext,\n Event,\n Extra,\n Extras,\n Primitive,\n Severity,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\n\n/**\n * This calls a function on the current hub.\n * @param method function to call on hub.\n * @param args to pass to function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction callOnHub<T>(method: string, ...args: any[]): T {\n const hub = getCurrentHub();\n if (hub && hub[method as keyof Hub]) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (hub[method as keyof Hub] as any)(...args);\n }\n throw new Error(`No hub defined or ${method} was not found on the hub, please open a bug report.`);\n}\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): string {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n return callOnHub('captureException', exception, {\n captureContext,\n originalException: exception,\n syntheticException,\n });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param level Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | Severity): string {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n\n return callOnHub('captureMessage', message, level, {\n originalException: message,\n syntheticException,\n ...context,\n });\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event): string {\n return callOnHub('captureEvent', event);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('configureScope', callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): void {\n callOnHub<void>('addBreadcrumb', breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): void {\n callOnHub<void>('setContext', name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): void {\n callOnHub<void>('setExtras', extras);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n callOnHub<void>('setTags', tags);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): void {\n callOnHub<void>('setExtra', key, extra);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): void {\n callOnHub<void>('setTag', key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): void {\n callOnHub<void>('setUser', user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('withScope', callback);\n}\n\n/**\n * Calls a function on the latest client. Use this with caution, it's meant as\n * in \"internal\" helper so we don't need to expose every possible function in\n * the shim. It is not guaranteed that the client actually implements the\n * function.\n *\n * @param method The method to call on the client/client.\n * @param args Arguments to pass to the client/fontend.\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _callOnClient(method: string, ...args: any[]): void {\n callOnHub<void>('_invokeClient', method, ...args);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n return callOnHub('startTransaction', { ...context }, customSamplingContext);\n}\n", "import { DsnLike, SdkMetadata } from '@sentry/types';\nimport { Dsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/**\n * Helper class to provide urls, headers and metadata that can be used to form\n * different types of requests to Sentry endpoints.\n * Supports both envelopes and regular event requests.\n **/\nexport class API {\n /** The DSN as passed to Sentry.init() */\n public dsn: DsnLike;\n\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n public metadata: SdkMetadata;\n\n /** The internally used Dsn object. */\n private readonly _dsnObject: Dsn;\n\n /** The envelope tunnel to use. */\n private readonly _tunnel?: string;\n\n /** Create a new instance of API */\n public constructor(dsn: DsnLike, metadata: SdkMetadata = {}, tunnel?: string) {\n this.dsn = dsn;\n this._dsnObject = new Dsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n\n /** Returns the Dsn object. */\n public getDsn(): Dsn {\n return this._dsnObject;\n }\n\n /** Does this transport force envelopes? */\n public forceEnvelope(): boolean {\n return !!this._tunnel;\n }\n\n /** Returns the prefix to construct Sentry ingestion API endpoints. */\n public getBaseApiEndpoint(): string {\n const dsn = this.getDsn();\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n }\n\n /** Returns the store endpoint URL. */\n public getStoreEndpoint(): string {\n return this._getIngestEndpoint('store');\n }\n\n /**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getStoreEndpointWithUrlEncodedAuth(): string {\n return `${this.getStoreEndpoint()}?${this._encodedAuth()}`;\n }\n\n /**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getEnvelopeEndpointWithUrlEncodedAuth(): string {\n if (this.forceEnvelope()) {\n return this._tunnel as string;\n }\n\n return `${this._getEnvelopeEndpoint()}?${this._encodedAuth()}`;\n }\n\n /** Returns only the path component for the store endpoint. */\n public getStoreEndpointPath(): string {\n const dsn = this.getDsn();\n return `${dsn.path ? `/${dsn.path}` : ''}/api/${dsn.projectId}/store/`;\n }\n\n /**\n * Returns an object that can be used in request headers.\n * This is needed for node and the old /store endpoint in sentry\n */\n public getRequestHeaders(clientName: string, clientVersion: string): { [key: string]: string } {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n const dsn = this.getDsn();\n const header = [`Sentry sentry_version=${SENTRY_API_VERSION}`];\n header.push(`sentry_client=${clientName}/${clientVersion}`);\n header.push(`sentry_key=${dsn.publicKey}`);\n if (dsn.pass) {\n header.push(`sentry_secret=${dsn.pass}`);\n }\n return {\n 'Content-Type': 'application/json',\n 'X-Sentry-Auth': header.join(', '),\n };\n }\n\n /** Returns the url to the report dialog endpoint. */\n public getReportDialogEndpoint(\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n } = {},\n ): string {\n const dsn = this.getDsn();\n const endpoint = `${this.getBaseApiEndpoint()}embed/error-page/`;\n\n const encodedOptions = [];\n encodedOptions.push(`dsn=${dsn.toString()}`);\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n if (!dialogOptions.user) {\n continue;\n }\n if (dialogOptions.user.name) {\n encodedOptions.push(`name=${encodeURIComponent(dialogOptions.user.name)}`);\n }\n if (dialogOptions.user.email) {\n encodedOptions.push(`email=${encodeURIComponent(dialogOptions.user.email)}`);\n }\n } else {\n encodedOptions.push(`${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`);\n }\n }\n if (encodedOptions.length) {\n return `${endpoint}?${encodedOptions.join('&')}`;\n }\n\n return endpoint;\n }\n\n /** Returns the envelope endpoint URL. */\n private _getEnvelopeEndpoint(): string {\n return this._getIngestEndpoint('envelope');\n }\n\n /** Returns the ingest API endpoint for target. */\n private _getIngestEndpoint(target: 'store' | 'envelope'): string {\n if (this._tunnel) {\n return this._tunnel;\n }\n const base = this.getBaseApiEndpoint();\n const dsn = this.getDsn();\n return `${base}${dsn.projectId}/${target}/`;\n }\n\n /** Returns a URL-encoded string with auth config suitable for a query string. */\n private _encodedAuth(): string {\n const dsn = this.getDsn();\n const auth = {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n };\n return urlEncode(auth);\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Integration, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n} & { initialized?: boolean };\n\n/**\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n return integrations.reduce((acc, integrations) => {\n if (acc.every(accIntegration => integrations.name !== accIntegration.name)) {\n acc.push(integrations);\n }\n return acc;\n }, [] as Integration[]);\n}\n\n/** Gets integration to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = (options.defaultIntegrations && [...options.defaultIntegrations]) || [];\n const userIntegrations = options.integrations;\n\n let integrations: Integration[] = [...filterDuplicates(defaultIntegrations)];\n\n if (Array.isArray(userIntegrations)) {\n // Filter out integrations that are also included in user options\n integrations = [\n ...integrations.filter(integrations =>\n userIntegrations.every(userIntegration => userIntegration.name !== integrations.name),\n ),\n // And filter out duplicated user options integrations\n ...filterDuplicates(userIntegrations),\n ];\n } else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(integrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n\n // Make sure that if present, `Debug` integration will always run last\n const integrationsNames = integrations.map(i => i.name);\n const alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push(...integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1));\n }\n\n return integrations;\n}\n\n/** Setup given integration */\nexport function setupIntegration(integration: Integration): void {\n if (installedIntegrations.indexOf(integration.name) !== -1) {\n return;\n }\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n logger.log(`Integration installed: ${integration.name}`);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations<O extends Options>(options: O): IntegrationIndex {\n const integrations: IntegrationIndex = {};\n getIntegrationsToSetup(options).forEach(integration => {\n integrations[integration.name] = integration;\n setupIntegration(integration);\n });\n // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`\n // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be\n // considered a member of the index the way the actual integrations are\n Object.defineProperty(integrations, 'initialized', { value: true });\n return integrations;\n}\n", "/* eslint-disable max-lines */\nimport { Scope, Session } from '@sentry/hub';\nimport {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n Options,\n Outcome,\n SessionStatus,\n Severity,\n Transport,\n} from '@sentry/types';\nimport {\n checkOrSetAlreadyCaught,\n dateTimestampInSeconds,\n Dsn,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n normalize,\n SentryError,\n SyncPromise,\n truncate,\n uuid4,\n} from '@sentry/utils';\n\nimport { Backend, BackendClass } from './basebackend';\nimport { IntegrationIndex, setupIntegrations } from './integration';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding backend constructor and options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}. Also, the Backend instance is available via\n * {@link Client.getBackend}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event via the backend, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient<NodeBackend, NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(NodeBackend, options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient<B extends Backend, O extends Options> implements Client<O> {\n /**\n * The backend used to physically interact in the environment. Usually, this\n * will correspond to the client. When composing SDKs, however, the Backend\n * from the root SDK will be used.\n */\n protected readonly _backend: B;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: Dsn;\n\n /** Array of used integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /**\n * Initializes this client instance.\n *\n * @param backendClass A constructor function to create the backend.\n * @param options Options for the client.\n */\n protected constructor(backendClass: BackendClass<B, O>, options: O) {\n this._backend = new backendClass(options);\n this._options = options;\n\n if (options.dsn) {\n this._dsn = new Dsn(options.dsn);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._getBackend()\n .eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this._getBackend().eventFromMessage(String(message), level, hint)\n : this._getBackend().eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n logger.warn('Discarded session because of missing or non-string release');\n } else {\n this._sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n session.update({ init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): Dsn | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._getBackend().getTransport();\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike<boolean> {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return this.getTransport()\n .close(timeout)\n .then(transportFlushed => clientFinished && transportFlushed);\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrations.initialized) {\n this._integrations = setupIntegrations(this._options);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === SessionStatus.Ok;\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.update({\n ...(crashed && { status: SessionStatus.Crashed }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /** Deliver captured session to Sentry */\n protected _sendSession(session: Session): void {\n this._getBackend().sendSession(session);\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Returns the current backend. */\n protected _getBackend(): B {\n return this._backend;\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n const { normalizeDepth = 3 } = this.getOptions();\n const prepared: Event = {\n ...event,\n event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n\n this._applyClientOptions(prepared);\n this._applyIntegrationsMetadata(prepared);\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint && hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = SyncPromise.resolve<Event | null>(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n if (finalScope) {\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return this._normalizeEvent(evt, normalizeDepth);\n }\n return evt;\n });\n }\n\n /**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\n protected _normalizeEvent(event: Event | null, depth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth),\n }),\n };\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n normalized.contexts.trace = event.contexts.trace;\n }\n\n const { _experiments = {} } = this.getOptions();\n if (_experiments.ensureNoCircularStructures) {\n return normalize(normalized);\n }\n\n return normalized;\n }\n\n /**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\n protected _applyClientOptions(event: Event): void {\n const options = this.getOptions();\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n }\n\n /**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\n protected _applyIntegrationsMetadata(event: Event): void {\n const integrationsArray = Object.keys(this._integrations);\n if (integrationsArray.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray];\n }\n }\n\n /**\n * Tells the backend to send this event\n * @param event The Sentry event to send\n */\n protected _sendEvent(event: Event): void {\n this._getBackend().sendEvent(event);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<string | undefined> {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n logger.error(reason);\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<Event> {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeSend, sampleRate } = this.getOptions();\n const transport = this.getTransport();\n\n if (!this._isEnabled()) {\n return SyncPromise.reject(new SentryError('SDK not enabled, will not capture event.'));\n }\n\n const isTransaction = event.type === 'transaction';\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n transport.recordLostEvent?.(Outcome.SampleRate, 'event');\n return SyncPromise.reject(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n return this._prepareEvent(event, scope, hint)\n .then(prepared => {\n if (prepared === null) {\n transport.recordLostEvent?.(Outcome.EventProcessor, event.type || 'event');\n throw new SentryError('An event processor returned null, will not send event.');\n }\n\n const isInternalException = hint && hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException || isTransaction || !beforeSend) {\n return prepared;\n }\n\n const beforeSendResult = beforeSend(prepared, hint);\n return this._ensureBeforeSendRv(beforeSendResult);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n transport.recordLostEvent?.(Outcome.BeforeSend, event.type || 'event');\n throw new SentryError('`beforeSend` returned `null`, will not send event.');\n }\n\n const session = scope && scope.getSession && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n this._sendEvent(processedEvent);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason as Error,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process<T>(promise: PromiseLike<T>): void {\n this._numProcessing += 1;\n void promise.then(\n value => {\n this._numProcessing -= 1;\n return value;\n },\n reason => {\n this._numProcessing -= 1;\n return reason;\n },\n );\n }\n\n /**\n * Verifies that return value of configured `beforeSend` is of expected type.\n */\n protected _ensureBeforeSendRv(\n rv: PromiseLike<Event | null> | Event | null,\n ): PromiseLike<Event | null> | Event | null {\n const nullErr = '`beforeSend` method has to return `null` or a valid event.';\n if (isThenable(rv)) {\n return (rv as PromiseLike<Event | null>).then(\n event => {\n if (!(isPlainObject(event) || event === null)) {\n throw new SentryError(nullErr);\n }\n return event;\n },\n e => {\n throw new SentryError(`beforeSend rejected with ${e}`);\n },\n );\n } else if (!(isPlainObject(rv) || rv === null)) {\n throw new SentryError(nullErr);\n }\n return rv;\n }\n}\n", "import { Event, Response, Status, Transport } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\n/** Noop transport */\nexport class NoopTransport implements Transport {\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike<Response> {\n return SyncPromise.resolve({\n reason: `NoopTransport: Event has been skipped because no Dsn is configured.`,\n status: Status.Skipped,\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(_?: number): PromiseLike<boolean> {\n return SyncPromise.resolve(true);\n }\n}\n", "import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';\nimport { logger, SentryError } from '@sentry/utils';\n\nimport { NoopTransport } from './transports/noop';\n\n/**\n * Internal platform-dependent Sentry SDK Backend.\n *\n * While {@link Client} contains business logic specific to an SDK, the\n * Backend offers platform specific implementations for low-level operations.\n * These are persisting and loading information, sending events, and hooking\n * into the environment.\n *\n * Backends receive a handle to the Client in their constructor. When a\n * Backend automatically generates events, it must pass them to\n * the Client for validation and processing first.\n *\n * Usually, the Client will be of corresponding type, e.g. NodeBackend\n * receives NodeClient. However, higher-level SDKs can choose to instantiate\n * multiple Backends and delegate tasks between them. In this case, an event\n * generated by one backend might very well be sent by another one.\n *\n * The client also provides access to options via {@link Client.getOptions}.\n * @hidden\n */\nexport interface Backend {\n /** Creates a {@link Event} from an exception. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventFromException(exception: any, hint?: EventHint): PromiseLike<Event>;\n\n /** Creates a {@link Event} from a plain message. */\n eventFromMessage(message: string, level?: Severity, hint?: EventHint): PromiseLike<Event>;\n\n /** Submits the event to Sentry */\n sendEvent(event: Event): void;\n\n /** Submits the session to Sentry */\n sendSession(session: Session): void;\n\n /**\n * Returns the transport that is used by the backend.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n *\n * @returns The transport.\n */\n getTransport(): Transport;\n}\n\n/**\n * A class object that can instantiate Backend objects.\n * @hidden\n */\nexport type BackendClass<B extends Backend, O extends Options> = new (options: O) => B;\n\n/**\n * This is the base implemention of a Backend.\n * @hidden\n */\nexport abstract class BaseBackend<O extends Options> implements Backend {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** Cached transport used internally. */\n protected _transport: Transport;\n\n /** Creates a new backend instance. */\n public constructor(options: O) {\n this._options = options;\n if (!this._options.dsn) {\n logger.warn('No DSN provided, backend will not do anything.');\n }\n this._transport = this._setupTransport();\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromException` method');\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(_message: string, _level?: Severity, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromMessage` method');\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): void {\n void this._transport.sendEvent(event).then(null, reason => {\n logger.error(`Error while sending event: ${reason}`);\n });\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): void {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n\n void this._transport.sendSession(session).then(null, reason => {\n logger.error(`Error while sending session: ${reason}`);\n });\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._transport;\n }\n\n /**\n * Sets up the transport so it can be used later to send requests.\n */\n protected _setupTransport(): Transport {\n return new NoopTransport();\n }\n}\n", "import { Event, SdkInfo, SentryRequest, SentryRequestType, Session, SessionAggregates } from '@sentry/types';\n\nimport { API } from './api';\n\n/** Extract sdk info from from the API metadata */\nfunction getSdkMetadataForEnvelopeHeader(api: API): SdkInfo | undefined {\n if (!api.metadata || !api.metadata.sdk) {\n return;\n }\n const { name, version } = api.metadata.sdk;\n return { name, version };\n}\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates a SentryRequest from a Session. */\nexport function sessionToSentryRequest(session: Session | SessionAggregates, api: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const envelopeHeaders = JSON.stringify({\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(api.forceEnvelope() && { dsn: api.getDsn().toString() }),\n });\n // I know this is hacky but we don't want to add `session` to request type since it's never rate limited\n const type: SentryRequestType = 'aggregates' in session ? ('sessions' as SentryRequestType) : 'session';\n const itemHeaders = JSON.stringify({\n type,\n });\n\n return {\n body: `${envelopeHeaders}\\n${itemHeaders}\\n${JSON.stringify(session)}`,\n type,\n url: api.getEnvelopeEndpointWithUrlEncodedAuth(),\n };\n}\n\n/** Creates a SentryRequest from an event. */\nexport function eventToSentryRequest(event: Event, api: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n const useEnvelope = eventType === 'transaction' || api.forceEnvelope();\n\n const { transactionSampling, ...metadata } = event.debug_meta || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n if (Object.keys(metadata).length === 0) {\n delete event.debug_meta;\n } else {\n event.debug_meta = metadata;\n }\n\n const req: SentryRequest = {\n body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n type: eventType,\n url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),\n };\n\n // https://develop.sentry.dev/sdk/envelopes/\n\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n if (useEnvelope) {\n const envelopeHeaders = JSON.stringify({\n event_id: event.event_id,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(api.forceEnvelope() && { dsn: api.getDsn().toString() }),\n });\n const itemHeaders = JSON.stringify({\n type: eventType,\n\n // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and\n // explicitly-set sampling decisions). Are we good with that?\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n\n // The content-type is assumed to be 'application/json' and not part of\n // the current spec for transaction items, so we don't bloat the request\n // body with it.\n //\n // content_type: 'application/json',\n //\n // The length is optional. It must be the number of bytes in req.Body\n // encoded as UTF-8. Since the server can figure this out and would\n // otherwise refuse events that report the length incorrectly, we decided\n // not to send the length to avoid problems related to reporting the wrong\n // size and to reduce request body size.\n //\n // length: new TextEncoder().encode(req.body).length,\n });\n // The trailing newline is optional. We intentionally don't send it to avoid\n // sending unnecessary bytes.\n //\n // const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}\\n`;\n const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}`;\n req.body = envelope;\n }\n\n return req;\n}\n", "import { getCurrentHub } from '@sentry/hub';\nimport { Client, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass<F extends Client, O extends Options> = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind<F extends Client, O extends Options>(clientClass: ClientClass<F, O>, options: O): void {\n if (options.debug === true) {\n logger.enable();\n }\n const hub = getCurrentHub();\n hub.getScope()?.update(options.initialScope);\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n", "export const SDK_VERSION = '6.16.1';\n", "import { Integration, WrappedFunction } from '@sentry/types';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function(this: WrappedFunction, ...args: any[]): string {\n const context = this.__sentry_original__ || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Event, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, isMatchingPattern, logger } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** JSDoc */\ninterface InboundFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreInternal: boolean;\n\n /** @deprecated use {@link InboundFiltersOptions.allowUrls} instead. */\n whitelistUrls: Array<string | RegExp>;\n /** @deprecated use {@link InboundFiltersOptions.denyUrls} instead. */\n blacklistUrls: Array<string | RegExp>;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial<InboundFiltersOptions> = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n const hub = getCurrentHub();\n if (!hub) {\n return event;\n }\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n // This checks prevents most of the occurrences of the bug linked below:\n // https://github.com/getsentry/sentry-javascript/issues/2622\n // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code.\n // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config),\n // as we cannot force people using multiple instances in their apps to sync SDK versions.\n const options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {};\n if (typeof self._shouldDropEvent !== 'function') {\n return event;\n }\n return self._shouldDropEvent(event, options) ? null : event;\n }\n return event;\n });\n }\n\n /** JSDoc */\n private _shouldDropEvent(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (this._isSentryError(event, options)) {\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (this._isIgnoredError(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (this._isDeniedUrl(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!this._isAllowedUrl(event, options)) {\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n }\n\n /** JSDoc */\n private _isSentryError(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (!options.ignoreInternal) {\n return false;\n }\n\n try {\n return (\n (event &&\n event.exception &&\n event.exception.values &&\n event.exception.values[0] &&\n event.exception.values[0].type === 'SentryError') ||\n false\n );\n } catch (_oO) {\n return false;\n }\n }\n\n /** JSDoc */\n private _isIgnoredError(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (!options.ignoreErrors || !options.ignoreErrors.length) {\n return false;\n }\n\n return this._getPossibleEventMessages(event).some(message =>\n // Not sure why TypeScript complains here...\n (options.ignoreErrors as Array<RegExp | string>).some(pattern => isMatchingPattern(message, pattern)),\n );\n }\n\n /** JSDoc */\n private _isDeniedUrl(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n // TODO: Use Glob instead?\n if (!options.denyUrls || !options.denyUrls.length) {\n return false;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? false : options.denyUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _isAllowedUrl(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n // TODO: Use Glob instead?\n if (!options.allowUrls || !options.allowUrls.length) {\n return true;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? true : options.allowUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _mergeOptions(clientOptions: Partial<InboundFiltersOptions> = {}): Partial<InboundFiltersOptions> {\n return {\n allowUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.whitelistUrls || []),\n ...(this._options.allowUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.whitelistUrls || []),\n ...(clientOptions.allowUrls || []),\n ],\n denyUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.blacklistUrls || []),\n ...(this._options.denyUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.blacklistUrls || []),\n ...(clientOptions.denyUrls || []),\n ],\n ignoreErrors: [\n ...(this._options.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true,\n };\n }\n\n /** JSDoc */\n private _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n }\n\n /** JSDoc */\n private _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame?.filename !== '<anonymous>' && frame?.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n }\n\n /** JSDoc */\n private _getEventFilterUrl(event: Event): string | null {\n try {\n if (event.stacktrace) {\n const frames = event.stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n if (event.exception) {\n const frames =\n event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n return null;\n } catch (oO) {\n logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n }\n}\n", "export { FunctionToString } from './functiontostring';\nexport { InboundFilters } from './inboundfilters';\n", "export {\n addBreadcrumb,\n captureException,\n captureEvent,\n captureMessage,\n configureScope,\n startTransaction,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n} from '@sentry/minimal';\nexport { addGlobalEventProcessor, getCurrentHub, getHubFromCarrier, Hub, makeMain, Scope } from '@sentry/hub';\nexport { API } from './api';\nexport { BaseClient } from './baseclient';\nexport { BackendClass, BaseBackend } from './basebackend';\nexport { eventToSentryRequest, sessionToSentryRequest } from './request';\nexport { initAndBind, ClientClass } from './sdk';\nexport { NoopTransport } from './transports/noop';\nexport { SDK_VERSION } from './version';\n\nimport * as Integrations from './integrations';\n\nexport { Integrations };\n", "/**\n * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most\n * recently used items while discarding least recently used items when its limit\n * is reached.\n *\n * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>\n * See README.md for details.\n *\n * Illustration of the design:\n *\n * entry entry entry entry\n * ______ ______ ______ ______\n * | head |.newer => | |.newer => | |.newer => | tail |\n * | A | | B | | C | | D |\n * |______| <= older.|______| <= older.|______| <= older.|______|\n *\n * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added\n */\n(function(g,f){\n const e = typeof exports == 'object' ? exports : typeof g == 'object' ? g : {};\n f(e);\n if (typeof define == 'function' && define.amd) { define('lru', e); }\n})(this, function(exports) {\n\nconst NEWER = Symbol('newer');\nconst OLDER = Symbol('older');\n\nfunction LRUMap(limit, entries) {\n if (typeof limit !== 'number') {\n // called as (entries)\n entries = limit;\n limit = 0;\n }\n\n this.size = 0;\n this.limit = limit;\n this.oldest = this.newest = undefined;\n this._keymap = new Map();\n\n if (entries) {\n this.assign(entries);\n if (limit < 1) {\n this.limit = this.size;\n }\n }\n}\n\nexports.LRUMap = LRUMap;\n\nfunction Entry(key, value) {\n this.key = key;\n this.value = value;\n this[NEWER] = undefined;\n this[OLDER] = undefined;\n}\n\n\nLRUMap.prototype._markEntryAsUsed = function(entry) {\n if (entry === this.newest) {\n // Already the most recenlty used entry, so no need to update the list\n return;\n }\n // HEAD--------------TAIL\n // <.older .newer>\n // <--- add direction --\n // A B C <D> E\n if (entry[NEWER]) {\n if (entry === this.oldest) {\n this.oldest = entry[NEWER];\n }\n entry[NEWER][OLDER] = entry[OLDER]; // C <-- E.\n }\n if (entry[OLDER]) {\n entry[OLDER][NEWER] = entry[NEWER]; // C. --> E\n }\n entry[NEWER] = undefined; // D --x\n entry[OLDER] = this.newest; // D. --> E\n if (this.newest) {\n this.newest[NEWER] = entry; // E. <-- D\n }\n this.newest = entry;\n};\n\nLRUMap.prototype.assign = function(entries) {\n let entry, limit = this.limit || Number.MAX_VALUE;\n this._keymap.clear();\n let it = entries[Symbol.iterator]();\n for (let itv = it.next(); !itv.done; itv = it.next()) {\n let e = new Entry(itv.value[0], itv.value[1]);\n this._keymap.set(e.key, e);\n if (!entry) {\n this.oldest = e;\n } else {\n entry[NEWER] = e;\n e[OLDER] = entry;\n }\n entry = e;\n if (limit-- == 0) {\n throw new Error('overflow');\n }\n }\n this.newest = entry;\n this.size = this._keymap.size;\n};\n\nLRUMap.prototype.get = function(key) {\n // First, find our cache entry\n var entry = this._keymap.get(key);\n if (!entry) return; // Not cached. Sorry.\n // As <key> was found in the cache, register it as being requested recently\n this._markEntryAsUsed(entry);\n return entry.value;\n};\n\nLRUMap.prototype.set = function(key, value) {\n var entry = this._keymap.get(key);\n\n if (entry) {\n // update existing\n entry.value = value;\n this._markEntryAsUsed(entry);\n return this;\n }\n\n // new entry\n this._keymap.set(key, (entry = new Entry(key, value)));\n\n if (this.newest) {\n // link previous tail to the new tail (entry)\n this.newest[NEWER] = entry;\n entry[OLDER] = this.newest;\n } else {\n // we're first in -- yay\n this.oldest = entry;\n }\n\n // add new entry to the end of the linked list -- it's now the freshest entry.\n this.newest = entry;\n ++this.size;\n if (this.size > this.limit) {\n // we hit the limit -- remove the head\n this.shift();\n }\n\n return this;\n};\n\nLRUMap.prototype.shift = function() {\n // todo: handle special case when limit == 1\n var entry = this.oldest;\n if (entry) {\n if (this.oldest[NEWER]) {\n // advance the list\n this.oldest = this.oldest[NEWER];\n this.oldest[OLDER] = undefined;\n } else {\n // the cache is exhausted\n this.oldest = undefined;\n this.newest = undefined;\n }\n // Remove last strong reference to <entry> and remove links from the purged\n // entry being returned:\n entry[NEWER] = entry[OLDER] = undefined;\n this._keymap.delete(entry.key);\n --this.size;\n return [entry.key, entry.value];\n }\n};\n\n// ----------------------------------------------------------------------------\n// Following code is optional and can be removed without breaking the core\n// functionality.\n\nLRUMap.prototype.find = function(key) {\n let e = this._keymap.get(key);\n return e ? e.value : undefined;\n};\n\nLRUMap.prototype.has = function(key) {\n return this._keymap.has(key);\n};\n\nLRUMap.prototype['delete'] = function(key) {\n var entry = this._keymap.get(key);\n if (!entry) return;\n this._keymap.delete(entry.key);\n if (entry[NEWER] && entry[OLDER]) {\n // relink the older entry with the newer entry\n entry[OLDER][NEWER] = entry[NEWER];\n entry[NEWER][OLDER] = entry[OLDER];\n } else if (entry[NEWER]) {\n // remove the link to us\n entry[NEWER][OLDER] = undefined;\n // link the newer entry to head\n this.oldest = entry[NEWER];\n } else if (entry[OLDER]) {\n // remove the link to us\n entry[OLDER][NEWER] = undefined;\n // link the newer entry to head\n this.newest = entry[OLDER];\n } else {// if(entry[OLDER] === undefined && entry.newer === undefined) {\n this.oldest = this.newest = undefined;\n }\n\n this.size--;\n return entry.value;\n};\n\nLRUMap.prototype.clear = function() {\n // Not clearing links should be safe, as we don't expose live links to user\n this.oldest = this.newest = undefined;\n this.size = 0;\n this._keymap.clear();\n};\n\n\nfunction EntryIterator(oldestEntry) { this.entry = oldestEntry; }\nEntryIterator.prototype[Symbol.iterator] = function() { return this; }\nEntryIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: [ent.key, ent.value] };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nfunction KeyIterator(oldestEntry) { this.entry = oldestEntry; }\nKeyIterator.prototype[Symbol.iterator] = function() { return this; }\nKeyIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.key };\n } else {\n return { done: true, value: undefined };\n }\n};\n\nfunction ValueIterator(oldestEntry) { this.entry = oldestEntry; }\nValueIterator.prototype[Symbol.iterator] = function() { return this; }\nValueIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.value };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nLRUMap.prototype.keys = function() {\n return new KeyIterator(this.oldest);\n};\n\nLRUMap.prototype.values = function() {\n return new ValueIterator(this.oldest);\n};\n\nLRUMap.prototype.entries = function() {\n return this;\n};\n\nLRUMap.prototype[Symbol.iterator] = function() {\n return new EntryIterator(this.oldest);\n};\n\nLRUMap.prototype.forEach = function(fun, thisObj) {\n if (typeof thisObj !== 'object') {\n thisObj = this;\n }\n let entry = this.oldest;\n while (entry) {\n fun.call(thisObj, entry.value, entry.key, this);\n entry = entry[NEWER];\n }\n};\n\n/** Returns a JSON (array) representation */\nLRUMap.prototype.toJSON = function() {\n var s = new Array(this.size), i = 0, entry = this.oldest;\n while (entry) {\n s[i++] = { key: entry.key, value: entry.value };\n entry = entry[NEWER];\n }\n return s;\n};\n\n/** Returns a String representation */\nLRUMap.prototype.toString = function() {\n var s = '', entry = this.oldest;\n while (entry) {\n s += String(entry.key)+':'+entry.value;\n entry = entry[NEWER];\n if (entry) {\n s += ' < ';\n }\n }\n return s;\n};\n\n});\n", "/**\n * stack-trace - Parses node.js stack traces\n *\n * This was originally forked to fix this issue:\n * https://github.com/felixge/node-stack-trace/issues/31\n *\n * Mar 19,2019 - #4fd379e\n *\n * https://github.com/felixge/node-stack-trace/\n * @license MIT\n */\n\n/** Decoded StackFrame */\nexport interface StackFrame {\n fileName: string;\n lineNumber: number;\n functionName: string;\n typeName: string;\n methodName: string;\n native: boolean;\n columnNumber: number;\n}\n\n/** Extracts StackFrames from the Error */\nexport function parse(err: Error): StackFrame[] {\n if (!err.stack) {\n return [];\n }\n\n const lines = err.stack.split('\\n').slice(1);\n\n return lines\n .map(line => {\n if (line.match(/^\\s*[-]{4,}$/)) {\n return {\n columnNumber: null,\n fileName: line,\n functionName: null,\n lineNumber: null,\n methodName: null,\n native: null,\n typeName: null,\n };\n }\n\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\n if (!lineMatch) {\n return undefined;\n }\n\n let object = null;\n let method = null;\n let functionName = null;\n let typeName = null;\n let methodName = null;\n const isNative = lineMatch[5] === 'native';\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n // eslint-disable-next-line no-plusplus\n methodStart--;\n }\n if (methodStart > 0) {\n object = functionName.substr(0, methodStart);\n method = functionName.substr(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.substr(objectEnd + 1);\n object = object.substr(0, objectEnd);\n }\n }\n typeName = null;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '<anonymous>') {\n methodName = null;\n functionName = null;\n }\n\n const properties = {\n columnNumber: parseInt(lineMatch[4], 10) || null,\n fileName: lineMatch[2] || null,\n functionName,\n lineNumber: parseInt(lineMatch[3], 10) || null,\n methodName,\n native: isNative,\n typeName,\n };\n\n return properties;\n })\n .filter(callSite => !!callSite) as StackFrame[];\n}\n", "import { Event, Exception, ExtendedError, StackFrame } from '@sentry/types';\nimport { addContextToFrame, basename, dirname, SyncPromise } from '@sentry/utils';\nimport { readFile } from 'fs';\nimport { LRUMap } from 'lru_map';\n\nimport * as stacktrace from './stacktrace';\nimport { NodeOptions } from './types';\n\nconst DEFAULT_LINES_OF_CONTEXT: number = 7;\nconst FILE_CONTENT_CACHE = new LRUMap<string, string | null>(100);\n\n/**\n * Resets the file cache. Exists for testing purposes.\n * @hidden\n */\nexport function resetFileContentCache(): void {\n FILE_CONTENT_CACHE.clear();\n}\n\n/** JSDoc */\nfunction getFunction(frame: stacktrace.StackFrame): string {\n try {\n return frame.functionName || `${frame.typeName}.${frame.methodName || '<anonymous>'}`;\n } catch (e) {\n // This seems to happen sometimes when using 'use strict',\n // stemming from `getTypeName`.\n // [TypeError: Cannot read property 'constructor' of undefined]\n return '<anonymous>';\n }\n}\n\nconst mainModule: string = `${(require.main && require.main.filename && dirname(require.main.filename)) ||\n global.process.cwd()}/`;\n\n/** JSDoc */\nfunction getModule(filename: string, base?: string): string {\n if (!base) {\n // eslint-disable-next-line no-param-reassign\n base = mainModule;\n }\n\n // It's specifically a module\n const file = basename(filename, '.js');\n // eslint-disable-next-line no-param-reassign\n filename = dirname(filename);\n let n = filename.lastIndexOf('/node_modules/');\n if (n > -1) {\n // /node_modules/ is 14 chars\n return `${filename.substr(n + 14).replace(/\\//g, '.')}:${file}`;\n }\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n n = `${filename}/`.lastIndexOf(base, 0);\n if (n === 0) {\n let moduleName = filename.substr(base.length).replace(/\\//g, '.');\n if (moduleName) {\n moduleName += ':';\n }\n moduleName += file;\n return moduleName;\n }\n return file;\n}\n\n/**\n * This function reads file contents and caches them in a global LRU cache.\n * Returns a Promise filepath => content array for all files that we were able to read.\n *\n * @param filenames Array of filepaths to read content from.\n */\nfunction readSourceFiles(filenames: string[]): PromiseLike<{ [key: string]: string | null }> {\n // we're relying on filenames being de-duped already\n if (filenames.length === 0) {\n return SyncPromise.resolve({});\n }\n\n return new SyncPromise<{\n [key: string]: string | null;\n }>(resolve => {\n const sourceFiles: {\n [key: string]: string | null;\n } = {};\n\n let count = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < filenames.length; i++) {\n const filename = filenames[i];\n\n const cache = FILE_CONTENT_CACHE.get(filename);\n // We have a cache hit\n if (cache !== undefined) {\n // If it's not null (which means we found a file and have a content)\n // we set the content and return it later.\n if (cache !== null) {\n sourceFiles[filename] = cache;\n }\n // eslint-disable-next-line no-plusplus\n count++;\n // In any case we want to skip here then since we have a content already or we couldn't\n // read the file and don't want to try again.\n if (count === filenames.length) {\n resolve(sourceFiles);\n }\n continue;\n }\n\n readFile(filename, (err: Error | null, data: Buffer) => {\n const content = err ? null : data.toString();\n sourceFiles[filename] = content;\n\n // We always want to set the cache, even to null which means there was an error reading the file.\n // We do not want to try to read the file again.\n FILE_CONTENT_CACHE.set(filename, content);\n // eslint-disable-next-line no-plusplus\n count++;\n if (count === filenames.length) {\n resolve(sourceFiles);\n }\n });\n }\n });\n}\n\n/**\n * @hidden\n */\nexport function extractStackFromError(error: Error): stacktrace.StackFrame[] {\n const stack = stacktrace.parse(error);\n if (!stack) {\n return [];\n }\n return stack;\n}\n\n/**\n * @hidden\n */\nexport function parseStack(stack: stacktrace.StackFrame[], options?: NodeOptions): PromiseLike<StackFrame[]> {\n const filesToRead: string[] = [];\n\n const linesOfContext =\n options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n const frames: StackFrame[] = stack.map(frame => {\n const parsedFrame: StackFrame = {\n colno: frame.columnNumber,\n filename: frame.fileName?.startsWith('file://') ? frame.fileName.substr(7) : frame.fileName || '',\n function: getFunction(frame),\n lineno: frame.lineNumber,\n };\n\n const isInternal =\n frame.native ||\n (parsedFrame.filename &&\n !parsedFrame.filename.startsWith('/') &&\n !parsedFrame.filename.startsWith('.') &&\n parsedFrame.filename.indexOf(':\\\\') !== 1);\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n parsedFrame.in_app =\n !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1;\n\n // Extract a module name based on the filename\n if (parsedFrame.filename) {\n parsedFrame.module = getModule(parsedFrame.filename);\n\n if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) {\n filesToRead.push(parsedFrame.filename);\n }\n }\n\n return parsedFrame;\n });\n\n // We do an early return if we do not want to fetch context liens\n if (linesOfContext <= 0) {\n return SyncPromise.resolve(frames);\n }\n\n try {\n return addPrePostContext(filesToRead, frames, linesOfContext);\n } catch (_) {\n // This happens in electron for example where we are not able to read files from asar.\n // So it's fine, we recover be just returning all frames without pre/post context.\n return SyncPromise.resolve(frames);\n }\n}\n\n/**\n * This function tries to read the source files + adding pre and post context (source code)\n * to a frame.\n * @param filesToRead string[] of filepaths\n * @param frames StackFrame[] containg all frames\n */\nfunction addPrePostContext(\n filesToRead: string[],\n frames: StackFrame[],\n linesOfContext: number,\n): PromiseLike<StackFrame[]> {\n return new SyncPromise<StackFrame[]>(resolve =>\n readSourceFiles(filesToRead).then(sourceFiles => {\n const result = frames.map(frame => {\n if (frame.filename && sourceFiles[frame.filename]) {\n try {\n const lines = (sourceFiles[frame.filename] as string).split('\\n');\n\n addContextToFrame(lines, frame, linesOfContext);\n } catch (e) {\n // anomaly, being defensive in case\n // unlikely to ever happen in practice but can definitely happen in theory\n }\n }\n return frame;\n });\n\n resolve(result);\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function getExceptionFromError(error: Error, options?: NodeOptions): PromiseLike<Exception> {\n const name = error.name || error.constructor.name;\n const stack = extractStackFromError(error);\n return new SyncPromise<Exception>(resolve =>\n parseStack(stack, options).then(frames => {\n const result = {\n stacktrace: {\n frames: prepareFramesForEvent(frames),\n },\n type: name,\n value: error.message,\n };\n resolve(result);\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function parseError(error: ExtendedError, options?: NodeOptions): PromiseLike<Event> {\n return new SyncPromise<Event>(resolve =>\n getExceptionFromError(error, options).then((exception: Exception) => {\n resolve({\n exception: {\n values: [exception],\n },\n });\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function prepareFramesForEvent(stack: StackFrame[]): StackFrame[] {\n if (!stack || !stack.length) {\n return [];\n }\n\n let localStack = stack;\n const firstFrameFunction = localStack[0].function || '';\n\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack.reverse();\n}\n", "// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata\nexport const SDK_NAME = 'sentry.javascript.node';\n", "import { API, SDK_VERSION } from '@sentry/core';\nimport {\n DsnProtocol,\n Event,\n Response,\n SentryRequest,\n SentryRequestType,\n Session,\n SessionAggregates,\n Status,\n Transport,\n TransportOptions,\n} from '@sentry/types';\nimport { logger, parseRetryAfterHeader, PromiseBuffer, SentryError } from '@sentry/utils';\nimport * as fs from 'fs';\nimport * as http from 'http';\nimport * as https from 'https';\nimport { URL } from 'url';\n\nimport { SDK_NAME } from '../../version';\nimport { HTTPModule } from './http-module';\n\nexport type URLParts = Pick<URL, 'hostname' | 'pathname' | 'port' | 'protocol'>;\nexport type UrlParser = (url: string) => URLParts;\n\nconst CATEGORY_MAPPING: {\n [key in SentryRequestType]: string;\n} = {\n event: 'error',\n transaction: 'transaction',\n session: 'session',\n attachment: 'attachment',\n};\n\n/** Base Transport class implementation */\nexport abstract class BaseTransport implements Transport {\n /** The Agent used for corresponding transport */\n public module?: HTTPModule;\n\n /** The Agent used for corresponding transport */\n public client?: http.Agent | https.Agent;\n\n /** API object */\n protected _api: API;\n\n /** A simple buffer holding all requests. */\n protected readonly _buffer: PromiseBuffer<Response> = new PromiseBuffer(30);\n\n /** Locks transport after receiving rate limits in a response */\n protected readonly _rateLimits: Record<string, Date> = {};\n\n /** Create instance and set this.dsn */\n public constructor(public options: TransportOptions) {\n this._api = new API(options.dsn, options._metadata, options.tunnel);\n }\n\n /** Default function used to parse URLs */\n public urlParser: UrlParser = url => new URL(url);\n\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike<Response> {\n throw new SentryError('Transport Class has to implement `sendEvent` method.');\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this._buffer.drain(timeout);\n }\n\n /**\n * Extracts proxy settings from client options and env variables.\n *\n * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion.\n *\n * An order of priority for available protocols is:\n * `http` => `options.httpProxy` | `process.env.http_proxy`\n * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy`\n */\n protected _getProxy(protocol: DsnProtocol): string | undefined {\n const { no_proxy, http_proxy, https_proxy } = process.env;\n const { httpProxy, httpsProxy } = this.options;\n const proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy;\n\n if (!no_proxy) {\n return proxy;\n }\n\n const { host, port } = this._api.getDsn();\n for (const np of no_proxy.split(',')) {\n if (host.endsWith(np) || `${host}:${port}`.endsWith(np)) {\n return;\n }\n }\n\n return proxy;\n }\n\n /** Returns a build request option object used by request */\n protected _getRequestOptions(urlParts: URLParts): http.RequestOptions | https.RequestOptions {\n const headers = {\n ...this._api.getRequestHeaders(SDK_NAME, SDK_VERSION),\n ...this.options.headers,\n };\n const { hostname, pathname, port, protocol } = urlParts;\n // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290\n // We ignore the query string on purpose\n const path = `${pathname}`;\n\n return {\n agent: this.client,\n headers,\n hostname,\n method: 'POST',\n path,\n port,\n protocol,\n ...(this.options.caCerts && {\n ca: fs.readFileSync(this.options.caCerts),\n }),\n };\n }\n\n /**\n * Gets the time that given category is disabled until for rate limiting\n */\n protected _disabledUntil(requestType: SentryRequestType): Date {\n const category = CATEGORY_MAPPING[requestType];\n return this._rateLimits[category] || this._rateLimits.all;\n }\n\n /**\n * Checks if a category is rate limited\n */\n protected _isRateLimited(requestType: SentryRequestType): boolean {\n return this._disabledUntil(requestType) > new Date(Date.now());\n }\n\n /**\n * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.\n */\n protected _handleRateLimit(headers: Record<string, string | null>): boolean {\n const now = Date.now();\n const rlHeader = headers['x-sentry-rate-limits'];\n const raHeader = headers['retry-after'];\n\n if (rlHeader) {\n // rate limit headers are of the form\n // <header>,<header>,..\n // where each <header> is of the form\n // <retry_after>: <categories>: <scope>: <reason_code>\n // where\n // <retry_after> is a delay in ms\n // <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form\n // <category>;<category>;...\n // <scope> is what's being limited (org, project, or key) - ignored by SDK\n // <reason_code> is an arbitrary string like \"org_quota\" - ignored by SDK\n for (const limit of rlHeader.trim().split(',')) {\n const parameters = limit.split(':', 2);\n const headerDelay = parseInt(parameters[0], 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n for (const category of (parameters[1] && parameters[1].split(';')) || ['all']) {\n // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this\n // sdk and any categories that are not supported will not be added redundantly to the rateLimits object\n const categoriesAllowed = [\n ...(Object.keys(CATEGORY_MAPPING) as [SentryRequestType]).map(k => CATEGORY_MAPPING[k]),\n 'all',\n ];\n if (categoriesAllowed.includes(category)) this._rateLimits[category] = new Date(now + delay);\n }\n }\n return true;\n } else if (raHeader) {\n this._rateLimits.all = new Date(now + parseRetryAfterHeader(now, raHeader));\n return true;\n }\n return false;\n }\n\n /** JSDoc */\n protected async _send(\n sentryRequest: SentryRequest,\n originalPayload?: Event | Session | SessionAggregates,\n ): Promise<Response> {\n if (!this.module) {\n throw new SentryError('No module available');\n }\n if (originalPayload && this._isRateLimited(sentryRequest.type)) {\n return Promise.reject({\n payload: originalPayload,\n type: sentryRequest.type,\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n return this._buffer.add(\n () =>\n new Promise<Response>((resolve, reject) => {\n if (!this.module) {\n throw new SentryError('No module available');\n }\n const options = this._getRequestOptions(this.urlParser(sentryRequest.url));\n const req = this.module.request(options, res => {\n const statusCode = res.statusCode || 500;\n const status = Status.fromHttpCode(statusCode);\n\n res.setEncoding('utf8');\n\n /**\n * \"Key-value pairs of header names and values. Header names are lower-cased.\"\n * https://nodejs.org/api/http.html#http_message_headers\n */\n let retryAfterHeader = res.headers ? res.headers['retry-after'] : '';\n retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader) as string;\n\n let rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : '';\n rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader) as string;\n\n const headers = {\n 'x-sentry-rate-limits': rlHeader,\n 'retry-after': retryAfterHeader,\n };\n\n const limited = this._handleRateLimit(headers);\n if (limited)\n logger.warn(\n `Too many ${sentryRequest.type} requests, backing off until: ${this._disabledUntil(\n sentryRequest.type,\n )}`,\n );\n\n if (status === Status.Success) {\n resolve({ status });\n } else {\n let rejectionMessage = `HTTP Error (${statusCode})`;\n if (res.headers && res.headers['x-sentry-error']) {\n rejectionMessage += `: ${res.headers['x-sentry-error']}`;\n }\n reject(new SentryError(rejectionMessage));\n }\n\n // Force the socket to drain\n res.on('data', () => {\n // Drain\n });\n res.on('end', () => {\n // Drain\n });\n });\n req.on('error', reject);\n req.end(sentryRequest.body);\n }),\n );\n }\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n 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(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n", "'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", null, null, null, null, null, "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Response, Session, SessionAggregates, TransportOptions } from '@sentry/types';\nimport * as http from 'http';\n\nimport { BaseTransport } from './base';\n\n/** Node http module transport */\nexport class HTTPTransport extends BaseTransport {\n /** Create a new instance and set this.agent */\n public constructor(public options: TransportOptions) {\n super(options);\n const proxy = this._getProxy('http');\n this.module = http;\n this.client = proxy\n ? (new (require('https-proxy-agent'))(proxy) as http.Agent)\n : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): Promise<Response> {\n return this._send(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): PromiseLike<Response> {\n return this._send(sessionToSentryRequest(session, this._api), session);\n }\n}\n", "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Response, Session, SessionAggregates, TransportOptions } from '@sentry/types';\nimport * as https from 'https';\n\nimport { BaseTransport } from './base';\n\n/** Node https module transport */\nexport class HTTPSTransport extends BaseTransport {\n /** Create a new instance and set this.agent */\n public constructor(public options: TransportOptions) {\n super(options);\n const proxy = this._getProxy('https');\n this.module = https;\n this.client = proxy\n ? (new (require('https-proxy-agent'))(proxy) as https.Agent)\n : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): Promise<Response> {\n return this._send(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): PromiseLike<Response> {\n return this._send(sessionToSentryRequest(session, this._api), session);\n }\n}\n", "export { BaseTransport } from './base';\nexport { HTTPTransport } from './http';\nexport { HTTPSTransport } from './https';\n", "import { BaseBackend, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Mechanism, Severity, Transport, TransportOptions } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n Dsn,\n extractExceptionKeysForMessage,\n isError,\n isPlainObject,\n normalizeToSize,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { extractStackFromError, parseError, parseStack, prepareFramesForEvent } from './parsers';\nimport { HTTPSTransport, HTTPTransport } from './transports';\nimport { NodeOptions } from './types';\n\n/**\n * The Sentry Node SDK Backend.\n * @hidden\n */\nexport class NodeBackend extends BaseBackend<NodeOptions> {\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(exception: any, hint?: EventHint): PromiseLike<Event> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ex: any = exception;\n const providedMechanism: Mechanism | undefined =\n hint && hint.data && (hint.data as { mechanism: Mechanism }).mechanism;\n const mechanism: Mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n if (!isError(exception)) {\n if (isPlainObject(exception)) {\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n const message = `Non-Error exception captured with keys: ${extractExceptionKeysForMessage(exception)}`;\n\n getCurrentHub().configureScope(scope => {\n scope.setExtra('__serialized__', normalizeToSize(exception as Record<string, unknown>));\n });\n\n ex = (hint && hint.syntheticException) || new Error(message);\n (ex as Error).message = message;\n } else {\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n ex = (hint && hint.syntheticException) || new Error(exception as string);\n (ex as Error).message = exception;\n }\n mechanism.synthetic = true;\n }\n\n return new SyncPromise<Event>((resolve, reject) =>\n parseError(ex as Error, this._options)\n .then(event => {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n resolve({\n ...event,\n event_id: hint && hint.event_id,\n });\n })\n .then(null, reject),\n );\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike<Event> {\n const event: Event = {\n event_id: hint && hint.event_id,\n level,\n message,\n };\n\n return new SyncPromise<Event>(resolve => {\n if (this._options.attachStacktrace && hint && hint.syntheticException) {\n const stack = hint.syntheticException ? extractStackFromError(hint.syntheticException) : [];\n void parseStack(stack, this._options)\n .then(frames => {\n event.stacktrace = {\n frames: prepareFramesForEvent(frames),\n };\n resolve(event);\n })\n .then(null, () => {\n resolve(event);\n });\n } else {\n resolve(event);\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n protected _setupTransport(): Transport {\n if (!this._options.dsn) {\n // We return the noop transport here in case there is no Dsn.\n return super._setupTransport();\n }\n\n const dsn = new Dsn(this._options.dsn);\n\n const transportOptions: TransportOptions = {\n ...this._options.transportOptions,\n ...(this._options.httpProxy && { httpProxy: this._options.httpProxy }),\n ...(this._options.httpsProxy && { httpsProxy: this._options.httpsProxy }),\n ...(this._options.caCerts && { caCerts: this._options.caCerts }),\n dsn: this._options.dsn,\n tunnel: this._options.tunnel,\n _metadata: this._options._metadata,\n };\n\n if (this._options.transport) {\n return new this._options.transport(transportOptions);\n }\n if (dsn.protocol === 'http') {\n return new HTTPTransport(transportOptions);\n }\n return new HTTPSTransport(transportOptions);\n }\n}\n", "import { BaseClient, Scope, SDK_VERSION } from '@sentry/core';\nimport { SessionFlusher } from '@sentry/hub';\nimport { Event, EventHint, RequestSessionStatus } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { NodeBackend } from './backend';\nimport { NodeOptions } from './types';\n\n/**\n * The Sentry Node SDK Client.\n *\n * @see NodeOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class NodeClient extends BaseClient<NodeBackend, NodeOptions> {\n protected _sessionFlusher: SessionFlusher | undefined;\n\n /**\n * Creates a new Node SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: NodeOptions) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.node',\n packages: [\n {\n name: 'npm:@sentry/node',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(NodeBackend, options);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const requestSession = scope.getRequestSession();\n\n // Necessary checks to ensure this is code block is executed only within a request\n // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage\n if (requestSession && requestSession.status === RequestSessionStatus.Ok) {\n requestSession.status = RequestSessionStatus.Errored;\n }\n }\n\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const eventType = event.type || 'exception';\n const isException =\n eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;\n\n // If the event is of type Exception, then a request session should be captured\n if (isException) {\n const requestSession = scope.getRequestSession();\n\n // Ensure that this is happening within the bounds of a request, and make sure not to override\n // Session Status if Errored / Crashed\n if (requestSession && requestSession.status === RequestSessionStatus.Ok) {\n requestSession.status = RequestSessionStatus.Errored;\n }\n }\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n *\n * @inheritdoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n this._sessionFlusher?.close();\n return super.close(timeout);\n }\n\n /** Method that initialises an instance of SessionFlusher on Client */\n public initSessionFlusher(): void {\n const { release, environment } = this._options;\n if (!release) {\n logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');\n } else {\n this._sessionFlusher = new SessionFlusher(this.getTransport(), {\n release,\n environment,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n event.platform = event.platform || 'node';\n if (this.getOptions().serverName) {\n event.server_name = this.getOptions().serverName;\n }\n return super._prepareEvent(event, scope, hint);\n }\n\n /**\n * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment\n * appropriate session aggregates bucket\n */\n protected _captureRequestSession(): void {\n if (!this._sessionFlusher) {\n logger.warn('Discarded request mode session because autoSessionTracking option was disabled');\n } else {\n this._sessionFlusher.incrementSessionStatusCount();\n }\n }\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { Integration, Severity } from '@sentry/types';\nimport { fill } from '@sentry/utils';\nimport * as util from 'util';\n\n/** Console module integration */\nexport class Console implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Console';\n\n /**\n * @inheritDoc\n */\n public name: string = Console.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n for (const level of ['debug', 'info', 'warn', 'error', 'log']) {\n fill(console, level, createConsoleWrapper(level));\n }\n }\n}\n\n/**\n * Wrapper function that'll be used for every console level\n */\nfunction createConsoleWrapper(level: string): (originalConsoleMethod: () => void) => void {\n return function consoleWrapper(originalConsoleMethod: () => void): () => void {\n let sentryLevel: Severity;\n\n switch (level) {\n case 'debug':\n sentryLevel = Severity.Debug;\n break;\n case 'error':\n sentryLevel = Severity.Error;\n break;\n case 'info':\n sentryLevel = Severity.Info;\n break;\n case 'warn':\n sentryLevel = Severity.Warning;\n break;\n default:\n sentryLevel = Severity.Log;\n }\n\n /* eslint-disable prefer-rest-params */\n return function(this: typeof console): void {\n if (getCurrentHub().getIntegration(Console)) {\n getCurrentHub().addBreadcrumb(\n {\n category: 'console',\n level: sentryLevel,\n message: util.format.apply(undefined, arguments),\n },\n {\n input: [...arguments],\n level,\n },\n );\n }\n\n originalConsoleMethod.apply(this, arguments);\n };\n /* eslint-enable prefer-rest-params */\n };\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { parseSemver } from '@sentry/utils';\nimport * as http from 'http';\nimport * as https from 'https';\nimport { URL } from 'url';\n\nconst NODE_VERSION = parseSemver(process.versions.node);\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n */\nexport function isSentryRequest(url: string): boolean {\n const dsn = getCurrentHub()\n .getClient()\n ?.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n\n/**\n * Assemble a URL to be used for breadcrumbs and spans.\n *\n * @param requestOptions RequestOptions object containing the component parts for a URL\n * @returns Fully-formed URL\n */\nexport function extractUrl(requestOptions: RequestOptions): string {\n const protocol = requestOptions.protocol || '';\n const hostname = requestOptions.hostname || requestOptions.host || '';\n // Don't log standard :80 (http) and :443 (https) ports to reduce the noise\n const port =\n !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`;\n const path = requestOptions.path ? requestOptions.path : '/';\n\n return `${protocol}//${hostname}${port}${path}`;\n}\n\n/**\n * Handle various edge cases in the span description (for spans representing http(s) requests).\n *\n * @param description current `description` property of the span representing the request\n * @param requestOptions Configuration data for the request\n * @param Request Request object\n *\n * @returns The cleaned description\n */\nexport function cleanSpanDescription(\n description: string | undefined,\n requestOptions: RequestOptions,\n request: http.ClientRequest,\n): string | undefined {\n // nothing to clean\n if (!description) {\n return description;\n }\n\n // eslint-disable-next-line prefer-const\n let [method, requestUrl] = description.split(' ');\n\n // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing,\n // we're likely dealing with an internal route and this doesn't apply)\n if (requestOptions.host && !requestOptions.protocol) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n requestOptions.protocol = (request as any)?.agent?.protocol; // worst comes to worst, this is undefined and nothing changes\n requestUrl = extractUrl(requestOptions);\n }\n\n // internal routes can end up starting with a triple slash rather than a single one\n if (requestUrl?.startsWith('///')) {\n requestUrl = requestUrl.slice(2);\n }\n\n return `${method} ${requestUrl}`;\n}\n\n// the node types are missing a few properties which node's `urlToOptions` function spits out\nexport type RequestOptions = http.RequestOptions & { hash?: string; search?: string; pathname?: string; href?: string };\ntype RequestCallback = (response: http.IncomingMessage) => void;\nexport type RequestMethodArgs =\n | [RequestOptions | string | URL, RequestCallback?]\n | [string | URL, RequestOptions, RequestCallback?];\nexport type RequestMethod = (...args: RequestMethodArgs) => http.ClientRequest;\n\n/**\n * Convert a URL object into a RequestOptions object.\n *\n * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the\n * RequestOptions type above.\n *\n * See https://github.com/nodejs/node/blob/master/lib/internal/url.js.\n */\nexport function urlToOptions(url: URL): RequestOptions {\n const options: RequestOptions = {\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `${url.pathname || ''}${url.search || ''}`,\n href: url.href,\n };\n if (url.port !== '') {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`;\n }\n return options;\n}\n\n/**\n * Normalize inputs to `http(s).request()` and `http(s).get()`.\n *\n * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms:\n * [ RequestOptions | string | URL ],\n * [ RequestOptions | string | URL, RequestCallback ],\n * [ string | URL, RequestOptions ], and\n * [ string | URL, RequestOptions, RequestCallback ].\n *\n * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is\n * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact\n * with the args in a standard way.\n *\n * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array.\n *\n * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ].\n */\nexport function normalizeRequestArgs(\n httpModule: typeof http | typeof https,\n requestArgs: RequestMethodArgs,\n): [RequestOptions] | [RequestOptions, RequestCallback] {\n let callback, requestOptions;\n\n // pop off the callback, if there is one\n if (typeof requestArgs[requestArgs.length - 1] === 'function') {\n callback = requestArgs.pop() as RequestCallback;\n }\n\n // create a RequestOptions object of whatever's at index 0\n if (typeof requestArgs[0] === 'string') {\n requestOptions = urlToOptions(new URL(requestArgs[0]));\n } else if (requestArgs[0] instanceof URL) {\n requestOptions = urlToOptions(requestArgs[0]);\n } else {\n requestOptions = requestArgs[0];\n }\n\n // if the options were given separately from the URL, fold them in\n if (requestArgs.length === 2) {\n requestOptions = { ...requestOptions, ...requestArgs[1] };\n }\n\n // Figure out the protocol if it's currently missing\n if (requestOptions.protocol === undefined) {\n // Worst case we end up populating protocol with undefined, which it already is\n /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // Because of that, we cannot rely on `httpModule` to provide us with valid protocol,\n // as it will always return `http`, even when using `https` module.\n //\n // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n requestOptions.protocol =\n (httpModule?.globalAgent as any)?.protocol ||\n (requestOptions.agent as any)?.protocol ||\n (requestOptions._defaultAgent as any)?.protocol;\n } else {\n requestOptions.protocol =\n (requestOptions.agent as any)?.protocol ||\n (requestOptions._defaultAgent as any)?.protocol ||\n (httpModule?.globalAgent as any)?.protocol;\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n }\n\n // return args in standardized form\n if (callback) {\n return [requestOptions, callback];\n } else {\n return [requestOptions];\n }\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { Integration, Span } from '@sentry/types';\nimport { fill, logger, parseSemver } from '@sentry/utils';\nimport * as http from 'http';\nimport * as https from 'https';\n\nimport {\n cleanSpanDescription,\n extractUrl,\n isSentryRequest,\n normalizeRequestArgs,\n RequestMethod,\n RequestMethodArgs,\n} from './utils/http';\n\nconst NODE_VERSION = parseSemver(process.versions.node);\n\n/** http module integration */\nexport class Http implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Http';\n\n /**\n * @inheritDoc\n */\n public name: string = Http.id;\n\n /**\n * @inheritDoc\n */\n private readonly _breadcrumbs: boolean;\n\n /**\n * @inheritDoc\n */\n private readonly _tracing: boolean;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { breadcrumbs?: boolean; tracing?: boolean } = {}) {\n this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;\n this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // No need to instrument if we don't want to track anything\n if (!this._breadcrumbs && !this._tracing) {\n return;\n }\n\n const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpModule = require('http');\n fill(httpModule, 'get', wrappedHandlerMaker);\n fill(httpModule, 'request', wrappedHandlerMaker);\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // If we do, we'd get double breadcrumbs and double spans for `https` calls.\n // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpsModule = require('https');\n fill(httpsModule, 'get', wrappedHandlerMaker);\n fill(httpsModule, 'request', wrappedHandlerMaker);\n }\n }\n}\n\n// for ease of reading below\ntype OriginalRequestMethod = RequestMethod;\ntype WrappedRequestMethod = RequestMethod;\ntype WrappedRequestMethodFactory = (original: OriginalRequestMethod) => WrappedRequestMethod;\n\n/**\n * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http`\n * and `https` modules. (NB: Not a typo - this is a creator^2!)\n *\n * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs\n * @param tracingEnabled Whether or not to record outgoing requests as tracing spans\n *\n * @returns A function which accepts the exiting handler and returns a wrapped handler\n */\nfunction _createWrappedRequestMethodFactory(\n breadcrumbsEnabled: boolean,\n tracingEnabled: boolean,\n): WrappedRequestMethodFactory {\n return function wrappedRequestMethodFactory(originalRequestMethod: OriginalRequestMethod): WrappedRequestMethod {\n return function wrappedMethod(this: typeof http | typeof https, ...args: RequestMethodArgs): http.ClientRequest {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const httpModule = this;\n\n const requestArgs = normalizeRequestArgs(this, args);\n const requestOptions = requestArgs[0];\n const requestUrl = extractUrl(requestOptions);\n\n // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method\n if (isSentryRequest(requestUrl)) {\n return originalRequestMethod.apply(httpModule, requestArgs);\n }\n\n let span: Span | undefined;\n let parentSpan: Span | undefined;\n\n const scope = getCurrentHub().getScope();\n if (scope && tracingEnabled) {\n parentSpan = scope.getSpan();\n if (parentSpan) {\n span = parentSpan.startChild({\n description: `${requestOptions.method || 'GET'} ${requestUrl}`,\n op: 'http.client',\n });\n\n const sentryTraceHeader = span.toTraceparent();\n logger.log(\n `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to ${requestUrl}: `,\n );\n requestOptions.headers = { ...requestOptions.headers, 'sentry-trace': sentryTraceHeader };\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalRequestMethod\n .apply(httpModule, requestArgs)\n .once('response', function(this: http.ClientRequest, res: http.IncomingMessage): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('response', requestUrl, req, res);\n }\n if (tracingEnabled && span) {\n if (res.statusCode) {\n span.setHttpStatus(res.statusCode);\n }\n span.description = cleanSpanDescription(span.description, requestOptions, req);\n span.finish();\n }\n })\n .once('error', function(this: http.ClientRequest): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('error', requestUrl, req);\n }\n if (tracingEnabled && span) {\n span.setHttpStatus(500);\n span.description = cleanSpanDescription(span.description, requestOptions, req);\n span.finish();\n }\n });\n };\n };\n}\n\n/**\n * Captures Breadcrumb based on provided request/response pair\n */\nfunction addRequestBreadcrumb(event: string, url: string, req: http.ClientRequest, res?: http.IncomingMessage): void {\n if (!getCurrentHub().getIntegration(Http)) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'http',\n data: {\n method: req.method,\n status_code: res && res.statusCode,\n url,\n },\n type: 'http',\n },\n {\n event,\n request: req,\n response: res,\n },\n );\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { forget, logger } from '@sentry/utils';\n\nimport { NodeClient } from '../../client';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\n/**\n * @hidden\n */\nexport function logAndExitProcess(error: Error): void {\n // eslint-disable-next-line no-console\n console.error(error && error.stack ? error.stack : error);\n\n const client = getCurrentHub().getClient<NodeClient>();\n\n if (client === undefined) {\n logger.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n return;\n }\n\n const options = client.getOptions();\n const timeout =\n (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||\n DEFAULT_SHUTDOWN_TIMEOUT;\n forget(\n client.close(timeout).then((result: boolean) => {\n if (!result) {\n logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n }),\n );\n}\n", "import { getCurrentHub, Scope } from '@sentry/core';\nimport { Integration, Severity } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { NodeClient } from '../client';\nimport { logAndExitProcess } from './utils/errorhandling';\n\ntype OnFatalErrorHandler = (firstError: Error, secondError?: Error) => void;\n\n/** Global Promise Rejection handler */\nexport class OnUncaughtException implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'OnUncaughtException';\n\n /**\n * @inheritDoc\n */\n public name: string = OnUncaughtException.id;\n\n /**\n * @inheritDoc\n */\n public readonly handler: (error: Error) => void = this._makeErrorHandler();\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n /**\n * Default onFatalError handler\n * @param firstError Error that has been thrown\n * @param secondError If this was called multiple times this will be set\n */\n onFatalError?(firstError: Error, secondError?: Error): void;\n } = {},\n ) {}\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n global.process.on('uncaughtException', this.handler.bind(this));\n }\n\n /**\n * @hidden\n */\n private _makeErrorHandler(): (error: Error) => void {\n const timeout = 2000;\n let caughtFirstError: boolean = false;\n let caughtSecondError: boolean = false;\n let calledFatalError: boolean = false;\n let firstError: Error;\n\n return (error: Error): void => {\n let onFatalError: OnFatalErrorHandler = logAndExitProcess;\n const client = getCurrentHub().getClient<NodeClient>();\n\n if (this._options.onFatalError) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n onFatalError = this._options.onFatalError;\n } else if (client && client.getOptions().onFatalError) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n onFatalError = client.getOptions().onFatalError as OnFatalErrorHandler;\n }\n\n if (!caughtFirstError) {\n const hub = getCurrentHub();\n\n // this is the first uncaught error and the ultimate reason for shutting down\n // we want to do absolutely everything possible to ensure it gets captured\n // also we want to make sure we don't go recursion crazy if more errors happen after this one\n firstError = error;\n caughtFirstError = true;\n\n if (hub.getIntegration(OnUncaughtException)) {\n hub.withScope((scope: Scope) => {\n scope.setLevel(Severity.Fatal);\n hub.captureException(error, {\n originalException: error,\n data: { mechanism: { handled: false, type: 'onuncaughtexception' } },\n });\n if (!calledFatalError) {\n calledFatalError = true;\n onFatalError(error);\n }\n });\n } else {\n if (!calledFatalError) {\n calledFatalError = true;\n onFatalError(error);\n }\n }\n } else if (calledFatalError) {\n // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down\n logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown');\n logAndExitProcess(error);\n } else if (!caughtSecondError) {\n // two cases for how we can hit this branch:\n // - capturing of first error blew up and we just caught the exception from that\n // - quit trying to capture, proceed with shutdown\n // - a second independent error happened while waiting for first error to capture\n // - want to avoid causing premature shutdown before first error capture finishes\n // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff\n // so let's instead just delay a bit before we proceed with our action here\n // in case 1, we just wait a bit unnecessarily but ultimately do the same thing\n // in case 2, the delay hopefully made us wait long enough for the capture to finish\n // two potential nonideal outcomes:\n // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError\n // 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\n // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError)\n // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish\n caughtSecondError = true;\n setTimeout(() => {\n if (!calledFatalError) {\n // it was probably case 1, let's treat err as the sendErr and call onFatalError\n calledFatalError = true;\n onFatalError(firstError, error);\n } else {\n // it was probably case 2, our first error finished capturing while we waited, cool, do nothing\n }\n }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc\n }\n };\n }\n}\n", "import { getCurrentHub, Scope } from '@sentry/core';\nimport { Integration } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\n\nimport { logAndExitProcess } from './utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\n/** Global Promise Rejection handler */\nexport class OnUnhandledRejection implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'OnUnhandledRejection';\n\n /**\n * @inheritDoc\n */\n public name: string = OnUnhandledRejection.id;\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n } = { mode: 'warn' },\n ) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this));\n }\n\n /**\n * Send an exception with reason\n * @param reason string\n * @param promise promise\n */\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\n public sendUnhandledPromise(reason: any, promise: any): void {\n const hub = getCurrentHub();\n\n if (!hub.getIntegration(OnUnhandledRejection)) {\n this._handleRejection(reason);\n return;\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n const context = (promise.domain && promise.domain.sentryContext) || {};\n\n hub.withScope((scope: Scope) => {\n scope.setExtra('unhandledPromiseRejection', true);\n\n // Preserve backwards compatibility with raven-node for now\n if (context.user) {\n scope.setUser(context.user);\n }\n if (context.tags) {\n scope.setTags(context.tags);\n }\n if (context.extra) {\n scope.setExtras(context.extra);\n }\n\n hub.captureException(reason, {\n originalException: promise,\n data: { mechanism: { handled: false, type: 'onunhandledrejection' } },\n });\n });\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n this._handleRejection(reason);\n }\n\n /**\n * Handler for `mode` option\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _handleRejection(reason: any): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (this._options.mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.error(reason && reason.stack ? reason.stack : reason);\n });\n } else if (this._options.mode === 'strict') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry/types';\nimport { isInstanceOf, SyncPromise } from '@sentry/utils';\n\nimport { getExceptionFromError } from '../parsers';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: string;\n\n /**\n * @inheritDoc\n */\n private readonly _limit: number;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { key?: string; limit?: number } = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n if (self) {\n const handler = self._handler && self._handler.bind(self);\n return typeof handler === 'function' ? handler(event, hint) : event;\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n private _handler(event: Event, hint?: EventHint): PromiseLike<Event> {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return SyncPromise.resolve(event);\n }\n\n return new SyncPromise<Event>(resolve => {\n void this._walkErrorTree(hint.originalException as Error, this._key)\n .then((linkedErrors: Exception[]) => {\n if (event && event.exception && event.exception.values) {\n event.exception.values = [...linkedErrors, ...event.exception.values];\n }\n resolve(event);\n })\n .then(null, () => {\n resolve(event);\n });\n });\n }\n\n /**\n * @inheritDoc\n */\n private _walkErrorTree(error: ExtendedError, key: string, stack: Exception[] = []): PromiseLike<Exception[]> {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {\n return SyncPromise.resolve(stack);\n }\n return new SyncPromise<Exception[]>((resolve, reject) => {\n void getExceptionFromError(error[key])\n .then((exception: Exception) => {\n void this._walkErrorTree(error[key], key, [exception, ...stack])\n .then(resolve)\n .then(null, () => {\n reject();\n });\n })\n .then(null, () => {\n reject();\n });\n });\n }\n}\n", "import { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { existsSync, readFileSync } from 'fs';\nimport { dirname, join } from 'path';\n\nlet moduleCache: { [key: string]: string };\n\n/** Extract information about paths */\nfunction getPaths(): string[] {\n try {\n return require.cache ? Object.keys(require.cache as Record<string, unknown>) : [];\n } catch (e) {\n return [];\n }\n}\n\n/** Extract information about package.json modules */\nfunction collectModules(): {\n [name: string]: string;\n} {\n const mainPaths = (require.main && require.main.paths) || [];\n const paths = getPaths();\n const infos: {\n [name: string]: string;\n } = {};\n const seen: {\n [path: string]: boolean;\n } = {};\n\n paths.forEach(path => {\n let dir = path;\n\n /** Traverse directories upward in the search of package.json file */\n const updir = (): void | (() => void) => {\n const orig = dir;\n dir = dirname(orig);\n\n if (!dir || orig === dir || seen[orig]) {\n return undefined;\n }\n if (mainPaths.indexOf(dir) < 0) {\n return updir();\n }\n\n const pkgfile = join(orig, 'package.json');\n seen[orig] = true;\n\n if (!existsSync(pkgfile)) {\n return updir();\n }\n\n try {\n const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as {\n name: string;\n version: string;\n };\n infos[info.name] = info.version;\n } catch (_oO) {\n // no-empty\n }\n };\n\n updir();\n });\n\n return infos;\n}\n\n/** Add node modules / packages to the event */\nexport class Modules implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Modules';\n\n /**\n * @inheritDoc\n */\n public name: string = Modules.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n if (!getCurrentHub().getIntegration(Modules)) {\n return event;\n }\n return {\n ...event,\n modules: this._getModules(),\n };\n });\n }\n\n /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */\n private _getModules(): { [key: string]: string } {\n if (!moduleCache) {\n moduleCache = collectModules();\n }\n return moduleCache;\n }\n}\n", "export { Console } from './console';\nexport { Http } from './http';\nexport { OnUncaughtException } from './onuncaughtexception';\nexport { OnUnhandledRejection } from './onunhandledrejection';\nexport { LinkedErrors } from './linkederrors';\nexport { Modules } from './modules';\n", "import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';\nimport { getMainCarrier, setHubOnCarrier } from '@sentry/hub';\nimport { SessionStatus } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\nimport * as domain from 'domain';\n\nimport { NodeClient } from './client';\nimport { Console, Http, LinkedErrors, OnUncaughtException, OnUnhandledRejection } from './integrations';\nimport { NodeOptions } from './types';\n\nexport const defaultIntegrations = [\n // Common\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n // Native Wrappers\n new Console(),\n new Http(),\n // Global Handlers\n new OnUncaughtException(),\n new OnUnhandledRejection(),\n // Misc\n new LinkedErrors(),\n];\n\n/**\n * The Sentry Node SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible in the\n * main entry module. To set context information or send manual events, use the\n * provided methods.\n *\n * @example\n * ```\n *\n * const { init } = require('@sentry/node');\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { configureScope } = require('@sentry/node');\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { addBreadcrumb } = require('@sentry/node');\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const Sentry = require('@sentry/node');\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link NodeOptions} for documentation on configuration options.\n */\nexport function init(options: NodeOptions = {}): void {\n const carrier = getMainCarrier();\n const autoloadedIntegrations = carrier.__SENTRY__?.integrations || [];\n\n options.defaultIntegrations =\n options.defaultIntegrations === false\n ? []\n : [\n ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations),\n ...autoloadedIntegrations,\n ];\n\n if (options.dsn === undefined && process.env.SENTRY_DSN) {\n options.dsn = process.env.SENTRY_DSN;\n }\n\n if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) {\n const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE);\n if (isFinite(tracesSampleRate)) {\n options.tracesSampleRate = tracesSampleRate;\n }\n }\n\n if (options.release === undefined) {\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n options.release = detectedRelease;\n } else {\n // If release is not provided, then we should disable autoSessionTracking\n options.autoSessionTracking = false;\n }\n }\n\n if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) {\n options.environment = process.env.SENTRY_ENVIRONMENT;\n }\n\n if (options.autoSessionTracking === undefined && options.dsn !== undefined) {\n options.autoSessionTracking = true;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if ((domain as any).active) {\n setHubOnCarrier(carrier, getCurrentHub());\n }\n\n initAndBind(NodeClient, options);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise<boolean> {\n const client = getCurrentHub().getClient<NodeClient>();\n if (client) {\n return client.flush(timeout);\n }\n logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise<boolean> {\n const client = getCurrentHub().getClient<NodeClient>();\n if (client) {\n return client.close(timeout);\n }\n logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client\n */\nexport function isAutoSessionTrackingEnabled(client?: NodeClient): boolean {\n if (client === undefined) {\n return false;\n }\n const clientOptions: NodeOptions = client && client.getOptions();\n if (clientOptions && clientOptions.autoSessionTracking !== undefined) {\n return clientOptions.autoSessionTracking;\n }\n return false;\n}\n\n/**\n * Returns a release dynamically from environment variables.\n */\nexport function getSentryRelease(fallback?: string): string | undefined {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n const global = getGlobalObject();\n if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) {\n return global.SENTRY_RELEASE.id;\n }\n\n return (\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env.GITHUB_SHA ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env.COMMIT_REF ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.VERCEL_GITHUB_COMMIT_SHA ||\n process.env.VERCEL_GITLAB_COMMIT_SHA ||\n process.env.VERCEL_BITBUCKET_COMMIT_SHA ||\n // Zeit (now known as Vercel)\n process.env.ZEIT_GITHUB_COMMIT_SHA ||\n process.env.ZEIT_GITLAB_COMMIT_SHA ||\n process.env.ZEIT_BITBUCKET_COMMIT_SHA ||\n fallback\n );\n}\n\n/**\n * Enable automatic Session Tracking for the node process.\n */\nfunction startSessionTracking(): void {\n const hub = getCurrentHub();\n hub.startSession();\n // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because\n // The 'beforeExit' event is not emitted for conditions causing explicit termination,\n // such as calling process.exit() or uncaught exceptions.\n // Ref: https://nodejs.org/api/process.html#process_event_beforeexit\n process.on('beforeExit', () => {\n const session = hub.getScope()?.getSession();\n const terminalStates = [SessionStatus.Exited, SessionStatus.Crashed];\n // Only call endSession, if the Session exists on Scope and SessionStatus is not a\n // Terminal Status i.e. Exited or Crashed because\n // \"When a session is moved away from ok it must not be updated anymore.\"\n // Ref: https://develop.sentry.dev/sdk/sessions/\n if (session && !terminalStates.includes(session.status)) hub.endSession();\n });\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Recursively read the contents of a directory.\n *\n * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this\n * directory.\n * @returns Array holding all relative paths\n */\nexport function deepReadDirSync(targetDir: string): string[] {\n const targetDirAbsPath = path.resolve(targetDir);\n\n if (!fs.existsSync(targetDirAbsPath)) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);\n }\n\n if (!fs.statSync(targetDirAbsPath).isDirectory()) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);\n }\n\n // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it\n // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve\n // the difference between `targetDirAbsPath` and `currentDirAbsPath`.\n const deepReadCurrentDir = (currentDirAbsPath: string): string[] => {\n return fs.readdirSync(currentDirAbsPath).reduce((absPaths: string[], itemName: string) => {\n const itemAbsPath = path.join(currentDirAbsPath, itemName);\n\n if (fs.statSync(itemAbsPath).isDirectory()) {\n return [...absPaths, ...deepReadCurrentDir(itemAbsPath)];\n }\n\n return [...absPaths, itemAbsPath];\n }, []);\n };\n\n return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath));\n}\n", "/** The status of an Span. */\n// eslint-disable-next-line import/export\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace SpanStatus {\n /**\n * Converts a HTTP status code into a {@link SpanStatus}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or {@link SpanStatus.UnknownError}.\n */\n export function fromHttpCode(httpStatus: number): SpanStatus {\n if (httpStatus < 400 && httpStatus >= 100) {\n return SpanStatus.Ok;\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return SpanStatus.Unauthenticated;\n case 403:\n return SpanStatus.PermissionDenied;\n case 404:\n return SpanStatus.NotFound;\n case 409:\n return SpanStatus.AlreadyExists;\n case 413:\n return SpanStatus.FailedPrecondition;\n case 429:\n return SpanStatus.ResourceExhausted;\n default:\n return SpanStatus.InvalidArgument;\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return SpanStatus.Unimplemented;\n case 503:\n return SpanStatus.Unavailable;\n case 504:\n return SpanStatus.DeadlineExceeded;\n default:\n return SpanStatus.InternalError;\n }\n }\n\n return SpanStatus.UnknownError;\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport { Options, TraceparentData, Transaction } from '@sentry/types';\n\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n options: Options | undefined = getCurrentHub()\n .getClient()\n ?.getOptions(),\n): boolean {\n return !!options && ('tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent: string): TraceparentData | undefined {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (matches) {\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n }\n return undefined;\n}\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction<T extends Transaction>(hub: Hub = getCurrentHub()): T | undefined {\n return hub?.getScope()?.getTransaction() as T | undefined;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nexport function msToSec(time: number): number {\n return time / 1000;\n}\n\n/**\n * Converts from seconds to milliseconds\n * @param time time in seconds\n */\nexport function secToMs(time: number): number {\n return time * 1000;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n", "import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'error',\n });\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'unhandledrejection',\n });\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n logger.log(`[Tracing] Transaction: ${SpanStatus.InternalError} -> Global error occured`);\n activeTransaction.setStatus(SpanStatus.InternalError);\n }\n}\n", "// Store finish reasons in tuple to save on bundle size\n// Readonly type should enforce that this is not mutated.\nexport const FINISH_REASON_TAG = 'finishReason';\n\nexport const IDLE_TRANSACTION_FINISH_REASONS = ['heartbeatFailed', 'idleTimeout', 'documentHidden'] as const;\n", "/* eslint-disable max-lines */\nimport { Primitive, Span as SpanInterface, SpanContext, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[] = [];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string = uuid4();\n\n /**\n * @inheritDoc\n */\n public spanId: string = uuid4().substring(16);\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatus | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number = timestampWithMs();\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive } = {};\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any } = {};\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext?: SpanContext) {\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated\n */\n public child(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): Span {\n return this.startChild(spanContext);\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatus): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = SpanStatus.fromHttpCode(httpStatus);\n if (spanStatus !== SpanStatus.UnknownError) {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === SpanStatus.Ok;\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data ?? {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId ?? this.spanId;\n this.startTimestamp = spanContext.startTimestamp ?? this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags ?? {};\n this.traceId = spanContext.traceId ?? this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n status?: string;\n tags?: { [key: string]: Primitive };\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport {\n Event,\n Measurements,\n Outcome,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, isInstanceOf, logger } from '@sentry/utils';\n\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public name: string;\n\n public metadata: TransactionMetadata;\n\n private _measurements: Measurements = {};\n\n /**\n * The reference to the current hub.\n */\n private readonly _hub: Hub = (getCurrentHub() as unknown) as Hub;\n\n private _trimEnd?: boolean;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n\n if (isInstanceOf(hub, Hub)) {\n this._hub = hub as Hub;\n }\n\n this.name = transactionContext.name || '';\n\n this.metadata = transactionContext.metadata || {};\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n }\n\n /**\n * JSDoc\n */\n public setName(name: string): void {\n this.name = name;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Set observed measurements for this transaction.\n * @hidden\n */\n public setMeasurements(measurements: Measurements): void {\n this._measurements = { ...measurements };\n }\n\n /**\n * Set metadata for this transaction.\n * @hidden\n */\n public setMetadata(newMetadata: TransactionMetadata): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');\n this.name = '<unlabeled transaction>';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n this._hub\n .getClient()\n ?.getTransport?.()\n .recordLostEvent?.(Outcome.SampleRate, 'transaction');\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const transaction: Event = {\n contexts: {\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n debug_meta: this.metadata,\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2));\n transaction.measurements = this._measurements;\n }\n\n logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name ?? '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { TransactionContext } from '@sentry/types';\nimport { logger, timestampWithMs } from '@sentry/utils';\n\nimport { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from './constants';\nimport { Span, SpanRecorder } from './span';\nimport { SpanStatus } from './spanstatus';\nimport { Transaction } from './transaction';\n\nexport const DEFAULT_IDLE_TIMEOUT = 1000;\nexport const HEARTBEAT_INTERVAL = 5000;\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string = '',\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record<string, boolean> = {};\n\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number = 0;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean = false;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = [];\n\n /**\n * If a transaction is created and no activities are added, we want to make sure that\n * it times out properly. This is cleared and not used when activities are added.\n */\n private _initTimeout: ReturnType<typeof setTimeout> | undefined;\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub?: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished.\n * @default 1000\n */\n private readonly _idleTimeout: number = DEFAULT_IDLE_TIMEOUT,\n // If an idle transaction should be put itself on and off the scope automatically.\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n if (_idleHub && _onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._initTimeout = setTimeout(() => {\n if (!this._finished) {\n this.finish();\n }\n }, this._idleTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampWithMs()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.spanRecorder) {\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus(SpanStatus.Cancelled);\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n logger.log('[Tracing] flushing IdleTransaction');\n } else {\n logger.log('[Tracing] No active IdleTransaction');\n }\n\n // this._onScope is true if the transaction was previously on the scope.\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n if (this._initTimeout) {\n clearTimeout(this._initTimeout);\n this._initTimeout = undefined;\n }\n logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const timeout = this._idleTimeout;\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n const end = timestampWithMs() + timeout / 1000;\n\n setTimeout(() => {\n if (!this._finished) {\n this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[1]);\n this.finish(end);\n }\n }, timeout);\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter += 1;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n logger.log(`[Tracing] Transaction finished because of no change for 3 heart beats`);\n this.setStatus(SpanStatus.DeadlineExceeded);\n this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]);\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, HEARTBEAT_INTERVAL);\n }\n}\n\n/**\n * Reset active transaction on scope\n */\nfunction clearActiveTransaction(hub?: Hub): void {\n if (hub) {\n const scope = hub.getScope();\n if (scope) {\n const transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n }\n}\n", "import { getMainCarrier, Hub } from '@sentry/hub';\nimport {\n CustomSamplingContext,\n Integration,\n IntegrationClass,\n Options,\n SamplingContext,\n TransactionContext,\n TransactionSamplingMethod,\n} from '@sentry/types';\nimport { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils';\n\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\nimport { hasTracingEnabled } from './utils';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n if (scope) {\n const span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param hub: The hub off of which to read config options\n * @param transaction: The transaction needing a sampling decision\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample<T extends Transaction>(transaction: T, options: Options, samplingContext: SamplingContext): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Explicit },\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Sampler,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Inheritance },\n });\n } else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Rate,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n logger.warn(`[Tracing] Discarding transaction because of invalid sample rate.`);\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const options = this.getClient()?.getOptions() || {};\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout?: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n): IdleTransaction {\n const options = hub.getClient()?.getOptions() || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * @private\n */\nexport function _addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping: Record<string, () => Integration> = {\n mongodb() {\n const integration = dynamicRequire(module, './integrations/node/mongo') as {\n Mongo: IntegrationClass<Integration>;\n };\n return new integration.Mongo();\n },\n mongoose() {\n const integration = dynamicRequire(module, './integrations/node/mongo') as {\n Mongo: IntegrationClass<Integration>;\n };\n return new integration.Mongo({ mongoose: true });\n },\n mysql() {\n const integration = dynamicRequire(module, './integrations/node/mysql') as {\n Mysql: IntegrationClass<Integration>;\n };\n return new integration.Mysql();\n },\n pg() {\n const integration = dynamicRequire(module, './integrations/node/postgres') as {\n Postgres: IntegrationClass<Integration>;\n };\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) as Integration[];\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nexport function addExtensionMethods(): void {\n _addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n\n // If an error happens globally, we should make sure transaction status is set to error.\n registerErrorInstrumentation();\n}\n", "import { Integration, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\ntype Method =\n | 'all'\n | 'get'\n | 'post'\n | 'put'\n | 'delete'\n | 'patch'\n | 'options'\n | 'head'\n | 'checkout'\n | 'copy'\n | 'lock'\n | 'merge'\n | 'mkactivity'\n | 'mkcol'\n | 'move'\n | 'm-search'\n | 'notify'\n | 'purge'\n | 'report'\n | 'search'\n | 'subscribe'\n | 'trace'\n | 'unlock'\n | 'unsubscribe'\n | 'use';\n\ntype Router = {\n [method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\ninterface ExpressResponse {\n once(name: string, callback: () => void): void;\n}\n\n/**\n * Internal helper for `__sentry_transaction`\n * @hidden\n */\ninterface SentryTracingResponse {\n __sentry_transaction?: Transaction;\n}\n\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\nexport class Express implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Express';\n\n /**\n * @inheritDoc\n */\n public name: string = Express.id;\n\n /**\n * Express App instance\n */\n private readonly _router?: Router;\n private readonly _methods?: Method[];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { app?: Router; router?: Router; methods?: Method[] } = {}) {\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n if (!this._router) {\n logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n instrumentMiddlewares(this._router, this._methods);\n }\n}\n\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\nfunction wrap(fn: Function, method: Method): (...args: any[]) => void {\n const arity = fn.length;\n\n switch (arity) {\n case 2: {\n return function(this: NodeJS.Global, req: unknown, res: ExpressResponse & SentryTracingResponse): void {\n const transaction = res.__sentry_transaction;\n if (transaction) {\n const span = transaction.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n res.once('finish', () => {\n span.finish();\n });\n }\n return fn.call(this, req, res);\n };\n }\n case 3: {\n return function(\n this: NodeJS.Global,\n req: unknown,\n res: ExpressResponse & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n const span = transaction?.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n fn.call(this, req, res, function(this: NodeJS.Global, ...args: unknown[]): void {\n span?.finish();\n next.call(this, ...args);\n });\n };\n }\n case 4: {\n return function(\n this: NodeJS.Global,\n err: Error,\n req: Request,\n res: Response & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n const span = transaction?.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n fn.call(this, err, req, res, function(this: NodeJS.Global, ...args: unknown[]): void {\n span?.finish();\n next.call(this, ...args);\n });\n };\n }\n default: {\n throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);\n }\n }\n}\n\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([<path>], <fn>)\n * app.use([<path>], <fn>, ...<fn>)\n * app.use([<path>], ...<fn>[])\n */\nfunction wrapMiddlewareArgs(args: unknown[], method: Method): unknown[] {\n return args.map((arg: unknown) => {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map((a: unknown) => {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n return a;\n });\n }\n\n return arg;\n });\n}\n\n/**\n * Patches original router to utilize our tracing functionality\n */\nfunction patchMiddleware(router: Router, method: Method): Router {\n const originalCallback = router[method];\n\n router[method] = function(...args: unknown[]): void {\n return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));\n };\n\n return router;\n}\n\n/**\n * Patches original router methods\n */\nfunction instrumentMiddlewares(router: Router, methods: Method[] = []): void {\n methods.forEach((method: Method) => patchMiddleware(router, method));\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\ninterface PgClient {\n prototype: {\n query: () => void | Promise<unknown>;\n };\n}\n\ninterface PgOptions {\n usePgNative?: boolean;\n}\n\n/** Tracing integration for node-postgres package */\nexport class Postgres implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Postgres';\n\n /**\n * @inheritDoc\n */\n public name: string = Postgres.id;\n\n private _usePgNative: boolean;\n\n public constructor(options: PgOptions = {}) {\n this._usePgNative = !!options.usePgNative;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const pkg = loadModule<{ Client: PgClient; native: { Client: PgClient } }>('pg');\n\n if (!pkg) {\n logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n if (this._usePgNative && !pkg.native?.Client) {\n logger.error(`Postgres Integration was unable to access 'pg-native' bindings.`);\n return;\n }\n\n const { Client } = this._usePgNative ? pkg.native : pkg;\n\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n fill(Client.prototype, 'query', function(orig: () => void | Promise<unknown>) {\n return function(this: unknown, config: unknown, values: unknown, callback: unknown) {\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n const span = parentSpan?.startChild({\n description: typeof config === 'string' ? config : (config as { text: string }).text,\n op: `db`,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function(err: Error, result: unknown) {\n span?.finish();\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function(err: Error, result: unknown) {\n span?.finish();\n values(err, result);\n });\n }\n\n const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (isThenable(rv)) {\n return (rv as Promise<unknown>).then((res: unknown) => {\n span?.finish();\n return res;\n });\n }\n\n span?.finish();\n return rv;\n };\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration } from '@sentry/types';\nimport { fill, loadModule, logger } from '@sentry/utils';\n\ninterface MysqlConnection {\n createQuery: () => void;\n}\n\n/** Tracing integration for node-mysql package */\nexport class Mysql implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mysql';\n\n /**\n * @inheritDoc\n */\n public name: string = Mysql.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const pkg = loadModule<MysqlConnection>('mysql/lib/Connection.js');\n\n if (!pkg) {\n logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n }\n\n // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n fill(pkg, 'createQuery', function(orig: () => void) {\n return function(this: unknown, options: unknown, values: unknown, callback: unknown) {\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n const span = parentSpan?.startChild({\n description: typeof options === 'string' ? options : (options as { sql: string }).sql,\n op: `db`,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function(err: Error, result: unknown, fields: unknown) {\n span?.finish();\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function(err: Error, result: unknown, fields: unknown) {\n span?.finish();\n values(err, result, fields);\n });\n }\n\n return orig.call(this, options, values, callback);\n };\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration, SpanContext } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\n// This allows us to use the same array for both defaults options and the type itself.\n// (note `as const` at the end to make it a union of string literal types (i.e. \"a\" | \"b\" | ... )\n// and not just a string[])\ntype Operation = typeof OPERATIONS[number];\nconst OPERATIONS = [\n 'aggregate', // aggregate(pipeline, options, callback)\n 'bulkWrite', // bulkWrite(operations, options, callback)\n 'countDocuments', // countDocuments(query, options, callback)\n 'createIndex', // createIndex(fieldOrSpec, options, callback)\n 'createIndexes', // createIndexes(indexSpecs, options, callback)\n 'deleteMany', // deleteMany(filter, options, callback)\n 'deleteOne', // deleteOne(filter, options, callback)\n 'distinct', // distinct(key, query, options, callback)\n 'drop', // drop(options, callback)\n 'dropIndex', // dropIndex(indexName, options, callback)\n 'dropIndexes', // dropIndexes(options, callback)\n 'estimatedDocumentCount', // estimatedDocumentCount(options, callback)\n 'find', // find(query, options, callback)\n 'findOne', // findOne(query, options, callback)\n 'findOneAndDelete', // findOneAndDelete(filter, options, callback)\n 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)\n 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)\n 'indexes', // indexes(options, callback)\n 'indexExists', // indexExists(indexes, options, callback)\n 'indexInformation', // indexInformation(options, callback)\n 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)\n 'insertMany', // insertMany(docs, options, callback)\n 'insertOne', // insertOne(doc, options, callback)\n 'isCapped', // isCapped(options, callback)\n 'mapReduce', // mapReduce(map, reduce, options, callback)\n 'options', // options(options, callback)\n 'parallelCollectionScan', // parallelCollectionScan(options, callback)\n 'rename', // rename(newName, options, callback)\n 'replaceOne', // replaceOne(filter, doc, options, callback)\n 'stats', // stats(options, callback)\n 'updateMany', // updateMany(filter, update, options, callback)\n 'updateOne', // updateOne(filter, update, options, callback)\n] as const;\n\n// All of the operations above take `options` and `callback` as their final parameters, but some of them\n// take additional parameters as well. For those operations, this is a map of\n// { <operation name>: [<names of additional parameters>] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\nconst OPERATION_SIGNATURES: {\n [op in Operation]?: string[];\n} = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update'],\n};\n\ninterface MongoCollection {\n collectionName: string;\n dbName: string;\n namespace: string;\n prototype: {\n [operation in Operation]: (...args: unknown[]) => unknown;\n };\n}\n\ninterface MongoOptions {\n operations?: Operation[];\n describeOperations?: boolean | Operation[];\n useMongoose?: boolean;\n}\n\n/** Tracing integration for mongo package */\nexport class Mongo implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mongo';\n\n /**\n * @inheritDoc\n */\n public name: string = Mongo.id;\n\n private _operations: Operation[];\n private _describeOperations?: boolean | Operation[];\n private _useMongoose: boolean;\n\n /**\n * @inheritDoc\n */\n public constructor(options: MongoOptions = {}) {\n this._operations = Array.isArray(options.operations)\n ? options.operations\n : ((OPERATIONS as unknown) as Operation[]);\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n const pkg = loadModule<{ Collection: MongoCollection }>(moduleName);\n\n if (!pkg) {\n logger.error(`Mongo Integration was unable to require \\`${moduleName}\\` package.`);\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n }\n\n /**\n * Patches original collection methods\n */\n private _instrumentOperations(collection: MongoCollection, operations: Operation[], getCurrentHub: () => Hub): void {\n operations.forEach((operation: Operation) => this._patchOperation(collection, operation, getCurrentHub));\n }\n\n /**\n * Patches original collection to utilize our tracing functionality\n */\n private _patchOperation(collection: MongoCollection, operation: Operation, getCurrentHub: () => Hub): void {\n if (!(operation in collection.prototype)) return;\n\n const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n fill(collection.prototype, operation, function(orig: () => void | Promise<unknown>) {\n return function(this: unknown, ...args: unknown[]) {\n const lastArg = args[args.length - 1];\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n\n // Check if the operation was passed a callback. (mapReduce requires a different check, as\n // its (non-callback) arguments can also be functions.)\n if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {\n const span = parentSpan?.startChild(getSpanContext(this, operation, args));\n const maybePromise = orig.call(this, ...args) as Promise<unknown>;\n\n if (isThenable(maybePromise)) {\n return maybePromise.then((res: unknown) => {\n span?.finish();\n return res;\n });\n } else {\n span?.finish();\n return maybePromise;\n }\n }\n\n const span = parentSpan?.startChild(getSpanContext(this, operation, args.slice(0, -1)));\n return orig.call(this, ...args.slice(0, -1), function(err: Error, result: unknown) {\n span?.finish();\n lastArg(err, result);\n });\n };\n });\n }\n\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n private _getSpanContextFromOperationArguments(\n collection: MongoCollection,\n operation: Operation,\n args: unknown[],\n ): SpanContext {\n const data: { [key: string]: string } = {\n collectionName: collection.collectionName,\n dbName: collection.dbName,\n namespace: collection.namespace,\n };\n const spanContext: SpanContext = {\n op: `db`,\n description: operation,\n data,\n };\n\n // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n const signature = OPERATION_SIGNATURES[operation];\n const shouldDescribe = Array.isArray(this._describeOperations)\n ? this._describeOperations.includes(operation)\n : this._describeOperations;\n\n if (!signature || !shouldDescribe) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n const [map, reduce] = args as { name?: string }[];\n data[signature[0]] = typeof map === 'string' ? map : map.name || '<anonymous>';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '<anonymous>';\n } else {\n for (let i = 0; i < signature.length; i++) {\n data[signature[i]] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {\n // no-empty\n }\n\n return spanContext;\n }\n}\n", "import { getGlobalObject, logger } from '@sentry/utils';\n\nimport { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants';\nimport { IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction } from '../utils';\n\nconst global = getGlobalObject<Window>();\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (global && global.document) {\n global.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (global.document.hidden && activeTransaction) {\n logger.log(\n `[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(SpanStatus.Cancelled);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]);\n activeTransaction.finish();\n }\n });\n } else {\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric, ReportHandler } from '../types';\n\nexport const bindReporter = (\n callback: ReportHandler,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n metric.delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (metric.delta || prevValue === undefined) {\n prevValue = metric.value;\n callback(metric);\n }\n }\n }\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v2-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n return {\n name,\n value: value ?? -1,\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (type: string, callback: PerformanceEntryHandler): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n // More extensive feature detect needed for Firefox due to:\n // https://github.com/GoogleChrome/web-vitals/issues/142\n if (type === 'first-input' && !('PerformanceEventTiming' in self)) {\n return;\n }\n\n const po: PerformanceObserver = new PerformanceObserver(l => l.getEntries().map(callback));\n\n po.observe({ type, buffered: true });\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || getGlobalObject<Window>().document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/layout-instability/#sec-layout-shift\nexport interface LayoutShift extends PerformanceEntry {\n value: number;\n hadRecentInput: boolean;\n sources: Array<LayoutShiftAttribution>;\n toJSON(): Record<string, unknown>;\n}\n\nexport interface LayoutShiftAttribution {\n node?: Node;\n previousRect: DOMRectReadOnly;\n currentRect: DOMRectReadOnly;\n}\n\nexport const getCLS = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType<typeof bindReporter>;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n const entryHandler = (entry: LayoutShift): void => {\n // Only count layout shifts without recent user input.\n // TODO: Figure out why entry can be undefined\n if (entry && !entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n };\n\n const po = observe('layout-shift', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n report(true);\n });\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n return getGlobalObject<Window>().document.visibilityState === 'hidden' ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { PerformanceEventTiming, ReportHandler } from './types';\n\nexport const getFID = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n let report: ReturnType<typeof bindReporter>;\n\n const entryHandler = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (report && entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const po = observe('first-input', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n }, true);\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface\nexport interface LargestContentfulPaint extends PerformanceEntry {\n renderTime: DOMHighResTimeStamp;\n loadTime: DOMHighResTimeStamp;\n size: number;\n id: string;\n url: string;\n element?: Element;\n toJSON(): Record<string, string>;\n}\n\nconst reportedMetricIDs: Record<string, boolean> = {};\n\nexport const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType<typeof bindReporter>;\n\n const entryHandler = (entry: PerformanceEntry): void => {\n // The startTime attribute returns the value of the renderTime if it is not 0,\n // and the value of the loadTime otherwise.\n const value = entry.startTime;\n\n // If the page was hidden prior to paint time of the entry,\n // ignore it and mark the metric as final, otherwise add the entry.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries.push(entry);\n }\n\n if (report) {\n report();\n }\n };\n\n const po = observe('largest-contentful-paint', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n }\n};\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Measurements, SpanContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNodeEnv, logger } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { Transaction } from '../transaction';\nimport { msToSec } from '../utils';\nimport { getCLS, LayoutShift } from './web-vitals/getCLS';\nimport { getFID } from './web-vitals/getFID';\nimport { getLCP, LargestContentfulPaint } from './web-vitals/getLCP';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';\nimport { NavigatorDeviceMemory, NavigatorNetworkInformation } from './web-vitals/types';\n\nconst global = getGlobalObject<Window>();\n\n/** Class tracking metrics */\nexport class MetricsInstrumentation {\n private _measurements: Measurements = {};\n\n private _performanceCursor: number = 0;\n private _lcpEntry: LargestContentfulPaint | undefined;\n private _clsEntry: LayoutShift | undefined;\n\n public constructor(private _reportAllChanges: boolean = false) {\n if (!isNodeEnv() && global?.performance && global?.document) {\n if (global.performance.mark) {\n global.performance.mark('sentry-tracing-init');\n }\n\n this._trackCLS();\n this._trackLCP();\n this._trackFID();\n }\n }\n\n /** Add performance related spans to a transaction */\n public addPerformanceEntries(transaction: Transaction): void {\n if (!global || !global.performance || !global.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n logger.log('[Tracing] Adding & adjusting spans using Performance API');\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n let entryScriptSrc: string | undefined;\n\n if (global.document && global.document.scripts) {\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < global.document.scripts.length; i++) {\n // We go through all scripts on the page and look for 'data-entry'\n // We remember the name and measure the time between this script finished loading and\n // our mark 'sentry-tracing-init'\n if (global.document.scripts[i].dataset.entry === 'true') {\n entryScriptSrc = global.document.scripts[i].src;\n break;\n }\n }\n }\n\n let entryScriptStartTimestamp: number | undefined;\n let tracingInitMarkStartTime: number | undefined;\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n global.performance\n .getEntries()\n .slice(this._performanceCursor)\n .forEach((entry: Record<string, any>) => {\n const startTime = msToSec(entry.startTime as number);\n const duration = msToSec(entry.duration as number);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart as number);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart as number);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n const startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') {\n tracingInitMarkStartTime = startTimestamp;\n }\n\n // capture web vitals\n\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FP');\n this._measurements['fp'] = { value: entry.startTime };\n this._measurements['mark.fp'] = { value: startTimestamp };\n }\n\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FCP');\n this._measurements['fcp'] = { value: entry.startTime };\n this._measurements['mark.fcp'] = { value: startTimestamp };\n }\n\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(global.location.origin, '');\n const endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n // We remember the entry script end time to calculate the difference to the first init mark\n if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) {\n entryScriptStartTimestamp = endTimestamp;\n }\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) {\n _startChild(transaction, {\n description: 'evaluation',\n endTimestamp: tracingInitMarkStartTime,\n op: 'script',\n startTimestamp: entryScriptStartTimestamp,\n });\n }\n\n this._performanceCursor = Math.max(performance.getEntries().length - 1, 0);\n\n this._trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // normalize applicable web vital values to be relative to transaction.startTimestamp\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n logger.log('[Measurements] Adding TTFB');\n this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!this._measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n\n const oldValue = this._measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n\n const delta = normalizedValue - oldValue;\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n\n this._measurements[name].value = normalizedValue;\n });\n\n if (this._measurements['mark.fid'] && this._measurements['fid']) {\n // create span for FID\n\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: this._measurements['mark.fid'].value + msToSec(this._measurements['fid'].value),\n op: 'web.vitals',\n startTimestamp: this._measurements['mark.fid'].value,\n });\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in this._measurements)) {\n delete this._measurements.cls;\n }\n\n transaction.setMeasurements(this._measurements);\n this._tagMetricInfo(transaction);\n\n transaction.setTag('sentry_reportAllChanges', this._reportAllChanges);\n }\n }\n\n /** Add LCP / CLS data to transaction to allow debugging */\n private _tagMetricInfo(transaction: Transaction): void {\n if (this._lcpEntry) {\n logger.log('[Measurements] Adding LCP Data');\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (this._lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(this._lcpEntry.element));\n }\n\n if (this._lcpEntry.id) {\n transaction.setTag('lcp.id', this._lcpEntry.id);\n }\n\n if (this._lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', this._lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (this._clsEntry && this._clsEntry.sources) {\n logger.log('[Measurements] Adding CLS Data');\n this._clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n }\n\n /** Starts tracking the Cumulative Layout Shift on the current page. */\n private _trackCLS(): void {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n getCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n logger.log('[Measurements] Adding CLS');\n this._measurements['cls'] = { value: metric.value };\n this._clsEntry = entry as LayoutShift;\n });\n }\n\n /**\n * Capture the information of the user agent.\n */\n private _trackNavigator(transaction: Transaction): void {\n const navigator = global.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n this._measurements['connection.rtt'] = { value: connection.rtt as number };\n }\n\n if (isMeasurementValue(connection.downlink)) {\n this._measurements['connection.downlink'] = { value: connection.downlink as number };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', String(navigator.deviceMemory));\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n }\n\n /** Starts tracking the Largest Contentful Paint on the current page. */\n private _trackLCP(): void {\n getLCP(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding LCP');\n this._measurements['lcp'] = { value: metric.value };\n this._measurements['mark.lcp'] = { value: timeOrigin + startTime };\n this._lcpEntry = entry as LargestContentfulPaint;\n }, this._reportAllChanges);\n }\n\n /** Starts tracking the First Input Delay on the current page. */\n private _trackFID(): void {\n getFID(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding FID');\n this._measurements['fid'] = { value: metric.value };\n this._measurements['mark.fid'] = { value: timeOrigin + startTime };\n });\n }\n}\n\n/** Instrument navigation entries */\nfunction addNavigationSpans(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n addPerformanceNavigationTiming({ transaction, entry, event: 'unloadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'redirect', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domContentLoadedEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'loadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'connect', timeOrigin });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'secureConnection',\n timeOrigin,\n eventEnd: 'connectEnd',\n description: 'TLS/SSL',\n });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'fetch',\n timeOrigin,\n eventEnd: 'domainLookupStart',\n description: 'cache',\n });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domainLookup', timeOrigin, description: 'DNS' });\n addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create measure related spans */\nfunction addMeasureSpans(\n transaction: Transaction,\n entry: Record<string, any>,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\nexport interface ResourceEntry extends Record<string, unknown> {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n}\n\n/** Create resource-related spans */\nexport function addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number | undefined {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return undefined;\n }\n\n const data: Record<string, any> = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource',\n startTimestamp,\n data,\n });\n\n return endTimestamp;\n}\n\n/** Create performance navigation related spans */\nfunction addPerformanceNavigationTiming(props: {\n transaction: Transaction;\n entry: Record<string, any>;\n event: string;\n timeOrigin: number;\n eventEnd?: string;\n description?: string;\n}): void {\n const { transaction, entry, event, timeOrigin, eventEnd, description } = props;\n\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description ?? event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\nfunction addRequest(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value: any): boolean {\n return typeof value === 'number' && isFinite(value);\n}\n", "import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction, hasTracingEnabled } from '../utils';\n\nexport const DEFAULT_TRACING_ORIGINS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * List of strings / regex where the integration should create Spans out of. Additionally this will be used\n * to define which outgoing requests the `sentry-trace` header will be attached to.\n *\n * Default: ['localhost', /^\\//] {@see DEFAULT_TRACING_ORIGINS}\n */\n tracingOrigins: Array<string | RegExp>;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * By default it uses the `tracingOrigins` options as a url match.\n */\n shouldCreateSpanForRequest?(url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n __sentry_xhr__?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record<string, any>;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n tracingOrigins: DEFAULT_TRACING_ORIGINS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial<RequestInstrumentationOptions>): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest } = {\n ...defaultRequestInstrumentationOptions,\n ..._options,\n };\n\n // We should cache url -> decision so that we don't have to compute\n // regexp everytime we create a request.\n const urlMap: Record<string, boolean> = {};\n\n const defaultShouldCreateSpan = (url: string): boolean => {\n if (urlMap[url]) {\n return urlMap[url];\n }\n const origins = tracingOrigins;\n urlMap[url] =\n origins.some((origin: string | RegExp) => isMatchingPattern(url, origin)) &&\n !isMatchingPattern(url, 'sentry_key');\n return urlMap[url];\n };\n\n // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves\n // That's why we filter out already unwanted Spans from tracingOrigins\n let shouldCreateSpan = defaultShouldCreateSpan;\n if (typeof shouldCreateSpanForRequest === 'function') {\n shouldCreateSpan = (url: string) => {\n return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url);\n };\n }\n\n const spans: Record<string, Span> = {};\n\n if (traceFetch) {\n addInstrumentationHandler({\n callback: (handlerData: FetchData) => {\n fetchCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'fetch',\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler({\n callback: (handlerData: XHRData) => {\n xhrCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'xhr',\n });\n }\n}\n\n/**\n * Create and track fetch request spans\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record<string, Span>,\n): void {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp && handlerData.fetchData.__span) {\n const span = spans[handlerData.fetchData.__span];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus(SpanStatus.InternalError);\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.fetchData.__span];\n }\n return;\n }\n\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = (handlerData.args[0] = handlerData.args[0] as string | Request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {});\n let headers = options.headers;\n if (isInstanceOf(request, Request)) {\n headers = (request as Request).headers;\n }\n if (headers) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (typeof headers.append === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n headers.append('sentry-trace', span.toTraceparent());\n } else if (Array.isArray(headers)) {\n headers = [...headers, ['sentry-trace', span.toTraceparent()]];\n } else {\n headers = { ...headers, 'sentry-trace': span.toTraceparent() };\n }\n } else {\n headers = { 'sentry-trace': span.toTraceparent() };\n }\n options.headers = headers;\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record<string, Span>,\n): void {\n if (\n !hasTracingEnabled() ||\n handlerData.xhr?.__sentry_own_request__ ||\n !(handlerData.xhr?.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))\n ) {\n return;\n }\n\n const xhr = handlerData.xhr.__sentry_xhr__;\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {\n const span = spans[handlerData.xhr.__sentry_xhr_span_id__];\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.xhr.__sentry_xhr_span_id__];\n }\n return;\n }\n\n // if not, create a new span to track it\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...xhr.data,\n type: 'xhr',\n method: xhr.method,\n url: xhr.url,\n },\n description: `${xhr.method} ${xhr.url}`,\n op: 'http.client',\n });\n\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n", "import { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils';\n\nconst global = getGlobalObject<Window>();\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!global || !global.location) {\n logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = global.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'pageload' });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler({\n callback: ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'navigation' });\n }\n },\n type: 'history',\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\nimport { startIdleTransaction } from '../hubextensions';\nimport { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { extractTraceparentData, secToMs } from '../utils';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { MetricsInstrumentation } from './metrics';\nimport {\n defaultRequestInstrumentationOptions,\n instrumentOutgoingRequests,\n RequestInstrumentationOptions,\n} from './request';\nimport { instrumentRoutingWithDefaults } from './router';\n\nexport const DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of\n * the last finished span as the endtime for the transaction.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * The maximum duration of a transaction before it will be marked as \"deadline_exceeded\".\n * If you never want to mark a transaction set it to 0.\n * Time is in seconds.\n *\n * Default: 600\n */\n maxTransactionDuration: number;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{ _reportAllChanges: boolean }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n idleTimeout: DEFAULT_IDLE_TIMEOUT,\n markBackgroundTransactions: true,\n maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'BrowserTracing';\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string = BrowserTracing.id;\n\n private _getCurrentHub?: () => Hub;\n\n private readonly _metrics: MetricsInstrumentation;\n\n private readonly _emitOptionsWarning: boolean = false;\n\n /** Store configured idle timeout so that it can be added as a tag to transactions */\n private _configuredIdleTimeout: BrowserTracingOptions['idleTimeout'] | undefined = undefined;\n\n public constructor(_options?: Partial<BrowserTracingOptions>) {\n let tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;\n // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances\n if (_options) {\n this._configuredIdleTimeout = _options.idleTimeout;\n if (_options.tracingOrigins && Array.isArray(_options.tracingOrigins) && _options.tracingOrigins.length !== 0) {\n tracingOrigins = _options.tracingOrigins;\n } else {\n this._emitOptionsWarning = true;\n }\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n tracingOrigins,\n };\n\n const { _metricOptions } = this.options;\n this._metrics = new MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges);\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n\n if (this._emitOptionsWarning) {\n logger.warn(\n '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.',\n );\n logger.warn(\n `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracingOrigins,\n shouldCreateSpanForRequest,\n } = this.options;\n\n instrumentRouting(\n (context: TransactionContext) => this._createRouteTransaction(context),\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests({ traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;\n\n const parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined;\n\n const expandedContext = {\n ...context,\n ...parentContextFromHeader,\n trimEnd: true,\n };\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n if (finalContext.sampled === false) {\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location };\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n true,\n { location }, // for use in the tracesSampler\n );\n idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {\n this._metrics.addPerformanceEntries(transaction);\n adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);\n });\n\n idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout);\n\n return idleTransaction as Transaction;\n }\n}\n\n/**\n * Gets transaction context from a sentry-trace meta.\n *\n * @returns Transaction context data from the header or undefined if there's no header or the header is malformed\n */\nexport function getHeaderContext(): Partial<TransactionContext> | undefined {\n const header = getMetaContent('sentry-trace');\n if (header) {\n return extractTraceparentData(header);\n }\n\n return undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | null {\n const el = getGlobalObject<Window>().document.querySelector(`meta[name=${metaName}]`);\n return el ? el.getAttribute('content') : null;\n}\n\n/** Adjusts transaction value based on max transaction duration */\nfunction adjustTransactionDuration(maxDuration: number, transaction: IdleTransaction, endTimestamp: number): void {\n const diff = endTimestamp - transaction.startTimestamp;\n const isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0);\n if (isOutdatedTransaction) {\n transaction.setStatus(SpanStatus.DeadlineExceeded);\n transaction.setTag('maxTransactionDurationExceeded', 'true');\n }\n}\n", "export { BrowserTracing } from './browsertracing';\nexport {\n instrumentOutgoingRequests,\n RequestInstrumentationOptions,\n defaultRequestInstrumentationOptions,\n} from './request';\n", "export { Express } from './node/express';\nexport { Postgres } from './node/postgres';\nexport { Mysql } from './node/mysql';\nexport { Mongo } from './node/mongo';\n\n// TODO(v7): Remove this export\n// Please see `src/index.ts` for more details.\nexport { BrowserTracing } from '../browser';\n", "import { addExtensionMethods } from './hubextensions';\nimport * as Integrations from './integrations';\n\nexport { Integrations };\n\n// This is already exported as part of `Integrations` above (and for the moment will remain so for\n// backwards compatibility), but that interferes with treeshaking, so we also export it separately\n// here.\n//\n// Previously we expected users to import tracing integrations like\n//\n// import { Integrations } from '@sentry/tracing';\n// const instance = new Integrations.BrowserTracing();\n//\n// This makes the integrations unable to be treeshaken though. To address this, we now have\n// this individual export. We now expect users to consume BrowserTracing like so:\n//\n// import { BrowserTracing } from '@sentry/tracing';\n// const instance = new BrowserTracing();\n//\n// For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts\nexport { BrowserTracing } from './browser';\n\nexport { Span } from './span';\nexport { Transaction } from './transaction';\nexport {\n // TODO deprecate old name in v7\n instrumentOutgoingRequests as registerRequestInstrumentation,\n RequestInstrumentationOptions,\n defaultRequestInstrumentationOptions,\n} from './browser';\nexport { SpanStatus } from './spanstatus';\nexport { IdleTransaction } from './idletransaction';\nexport { startIdleTransaction } from './hubextensions';\n\n// We are patching the global object with our hub extension methods\naddExtensionMethods();\n\nexport { addExtensionMethods };\n\nexport {\n extractTraceparentData,\n getActiveTransaction,\n hasTracingEnabled,\n stripUrlQueryAndFragment,\n TRACEPARENT_REGEXP,\n} from './utils';\n", "/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar decode = decodeURIComponent;\nvar encode = encodeURIComponent;\nvar pairSplitRegExp = /; */;\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var pairs = str.split(pairSplitRegExp);\n var dec = opt.decode || decode;\n\n for (var i = 0; i < pairs.length; i++) {\n var pair = pairs[i];\n var eq_idx = pair.indexOf('=');\n\n // skip things that don't look like key=value\n if (eq_idx < 0) {\n continue;\n }\n\n var key = pair.substr(0, eq_idx).trim()\n var val = pair.substr(++eq_idx, pair.length).trim();\n\n // quoted values\n if ('\"' == val[0]) {\n val = val.slice(1, -1);\n }\n\n // only assign once\n if (undefined == obj[key]) {\n obj[key] = tryDecode(val, dec);\n }\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n if (typeof opt.expires.toUTCString !== 'function') {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { captureException, getCurrentHub, startTransaction, withScope } from '@sentry/core';\nimport { extractTraceparentData, Span } from '@sentry/tracing';\nimport { Event, ExtractedNodeRequestData, RequestSessionStatus, Transaction } from '@sentry/types';\nimport { isPlainObject, isString, logger, normalize, stripUrlQueryAndFragment } from '@sentry/utils';\nimport * as cookie from 'cookie';\nimport * as domain from 'domain';\nimport * as http from 'http';\nimport * as os from 'os';\nimport * as url from 'url';\n\nimport { NodeClient } from './client';\nimport { flush, isAutoSessionTrackingEnabled } from './sdk';\n\nexport interface ExpressRequest {\n baseUrl?: string;\n connection?: {\n remoteAddress?: string;\n };\n ip?: string;\n method?: string;\n originalUrl?: string;\n route?: {\n path: string;\n stack: [\n {\n name: string;\n },\n ];\n };\n query?: {\n // It can be: undefined | string | string[] | ParsedQs | ParsedQs[] (from `qs` package), but we dont want to pull it.\n [key: string]: unknown;\n };\n url?: string;\n user?: {\n [key: string]: any;\n };\n}\n\n/**\n * Express-compatible tracing handler.\n * @see Exposed as `Handlers.tracingHandler`\n */\nexport function tracingHandler(): (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n) => void {\n return function sentryTracingMiddleware(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n ): void {\n // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)\n let traceparentData;\n if (req.headers && isString(req.headers['sentry-trace'])) {\n traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);\n }\n\n const transaction = startTransaction(\n {\n name: extractExpressTransactionName(req, { path: true, method: true }),\n op: 'http.server',\n ...traceparentData,\n },\n // extra context passed to the tracesSampler\n { request: extractRequestData(req) },\n );\n\n // We put the transaction on the scope so users can attach children to it\n getCurrentHub().configureScope(scope => {\n scope.setSpan(transaction);\n });\n\n // We also set __sentry_transaction on the response so people can grab the transaction there to add\n // spans to it later.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res as any).__sentry_transaction = transaction;\n\n res.once('finish', () => {\n // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction\n // closes\n setImmediate(() => {\n addExpressReqToTransaction(transaction, req);\n transaction.setHttpStatus(res.statusCode);\n transaction.finish();\n });\n });\n\n next();\n };\n}\n\n/**\n * Set parameterized as transaction name e.g.: `GET /users/:id`\n * Also adds more context data on the transaction from the request\n */\nfunction addExpressReqToTransaction(transaction: Transaction | undefined, req: ExpressRequest): void {\n if (!transaction) return;\n transaction.name = extractExpressTransactionName(req, { path: true, method: true });\n transaction.setData('url', req.originalUrl);\n transaction.setData('baseUrl', req.baseUrl);\n transaction.setData('query', req.query);\n}\n\n/**\n * Extracts complete generalized path from the request object and uses it to construct transaction name.\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req The ExpressRequest object\n * @param options What to include in the transaction name (method, path, or both)\n *\n * @returns The fully constructed transaction name\n */\nfunction extractExpressTransactionName(\n req: ExpressRequest,\n options: { path?: boolean; method?: boolean } = {},\n): string {\n const method = req.method?.toUpperCase();\n\n let path = '';\n if (req.route) {\n path = `${req.baseUrl || ''}${req.route.path}`;\n } else if (req.originalUrl || req.url) {\n path = stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let info = '';\n if (options.method && method) {\n info += method;\n }\n if (options.method && options.path) {\n info += ` `;\n }\n if (options.path && path) {\n info += path;\n }\n\n return info;\n}\n\ntype TransactionNamingScheme = 'path' | 'methodPath' | 'handler';\n\n/** JSDoc */\nfunction extractTransaction(req: ExpressRequest, type: boolean | TransactionNamingScheme): string {\n switch (type) {\n case 'path': {\n return extractExpressTransactionName(req, { path: true });\n }\n case 'handler': {\n return req.route?.stack[0].name || '<anonymous>';\n }\n case 'methodPath':\n default: {\n return extractExpressTransactionName(req, { path: true, method: true });\n }\n }\n}\n\n/** Default user keys that'll be used to extract data from the request */\nconst DEFAULT_USER_KEYS = ['id', 'username', 'email'];\n\n/** JSDoc */\nfunction extractUserData(\n user: {\n [key: string]: any;\n },\n keys: boolean | string[],\n): { [key: string]: any } {\n const extractedUser: { [key: string]: any } = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/** Default request keys that'll be used to extract data from the request */\nconst DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\n\n/**\n * Normalizes data from the request object, accounting for framework differences.\n *\n * @param req The request object from which to extract data\n * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not\n * provided.\n * @returns An object containing normalized request data\n */\nexport function extractRequestData(\n req: { [key: string]: any },\n keys: string[] = DEFAULT_REQUEST_KEYS,\n): ExtractedNodeRequestData {\n const requestData: { [key: string]: any } = {};\n\n // headers:\n // node, express, nextjs: req.headers\n // koa: req.header\n const headers = (req.headers || req.header || {}) as {\n host?: string;\n cookie?: string;\n };\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n const host = req.hostname || req.host || headers.host || '<no host>';\n // protocol:\n // node, nextjs: <n/a>\n // express, koa: req.protocol\n const protocol =\n req.protocol === 'https' || req.secure || ((req.socket || {}) as { encrypted?: boolean }).encrypted\n ? 'https'\n : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = (req.originalUrl || req.url || '') as string;\n // absolute url\n const absoluteUrl = `${protocol}://${host}${originalUrl}`;\n\n keys.forEach(key => {\n switch (key) {\n case 'headers':\n requestData.headers = headers;\n break;\n case 'method':\n requestData.method = method;\n break;\n case 'url':\n requestData.url = absoluteUrl;\n break;\n case 'cookies':\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.cookies = req.cookies || cookie.parse(headers.cookie || '');\n break;\n case 'query_string':\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = req.query || url.parse(originalUrl || '', false).query;\n break;\n case 'data':\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));\n }\n break;\n default:\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req as { [key: string]: any })[key];\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n */\nexport interface ParseRequestOptions {\n ip?: boolean;\n request?: boolean | string[];\n serverName?: boolean;\n transaction?: boolean | TransactionNamingScheme;\n user?: boolean | string[];\n version?: boolean;\n}\n\n/**\n * Enriches passed event with request data.\n *\n * @param event Will be mutated and enriched with req data\n * @param req Request object\n * @param options object containing flags to enable functionality\n * @hidden\n */\nexport function parseRequest(event: Event, req: ExpressRequest, options?: ParseRequestOptions): Event {\n // eslint-disable-next-line no-param-reassign\n options = {\n ip: false,\n request: true,\n serverName: true,\n transaction: true,\n user: true,\n version: true,\n ...options,\n };\n\n if (options.version) {\n event.contexts = {\n ...event.contexts,\n runtime: {\n name: 'node',\n version: global.process.version,\n },\n };\n }\n\n if (options.request) {\n // if the option value is `true`, use the default set of keys by not passing anything to `extractRequestData()`\n const extractedRequestData = Array.isArray(options.request)\n ? extractRequestData(req, options.request)\n : extractRequestData(req);\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (options.serverName && !event.server_name) {\n event.server_name = global.process.env.SENTRY_NAME || os.hostname();\n }\n\n if (options.user) {\n const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, options.user) : {};\n\n if (Object.keys(extractedUser)) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.connection.remoteAddress\n // express, koa: req.ip\n if (options.ip) {\n const ip = req.ip || (req.connection && req.connection.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (options.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, options.transaction);\n }\n\n return event;\n}\n\nexport type RequestHandlerOptions = ParseRequestOptions & {\n flushTimeout?: number;\n};\n\n/**\n * Express compatible request handler.\n * @see Exposed as `Handlers.requestHandler`\n */\nexport function requestHandler(\n options?: RequestHandlerOptions,\n): (req: http.IncomingMessage, res: http.ServerResponse, next: (error?: any) => void) => void {\n const currentHub = getCurrentHub();\n const client = currentHub.getClient<NodeClient>();\n // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the\n // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode\n if (client && isAutoSessionTrackingEnabled(client)) {\n client.initSessionFlusher();\n\n // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode\n const scope = currentHub.getScope();\n if (scope && scope.getSession()) {\n scope.setSession();\n }\n }\n return function sentryRequestMiddleware(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n ): void {\n if (options && options.flushTimeout && options.flushTimeout > 0) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _end = res.end;\n res.end = function(chunk?: any | (() => void), encoding?: string | (() => void), cb?: () => void): void {\n void flush(options.flushTimeout)\n .then(() => {\n _end.call(this, chunk, encoding, cb);\n })\n .then(null, e => {\n logger.error(e);\n });\n };\n }\n const local = domain.create();\n local.add(req);\n local.add(res);\n local.on('error', next);\n\n local.run(() => {\n const currentHub = getCurrentHub();\n\n currentHub.configureScope(scope => {\n scope.addEventProcessor((event: Event) => parseRequest(event, req, options));\n const client = currentHub.getClient<NodeClient>();\n if (isAutoSessionTrackingEnabled(client)) {\n const scope = currentHub.getScope();\n if (scope) {\n // Set `status` of `RequestSession` to Ok, at the beginning of the request\n scope.setRequestSession({ status: RequestSessionStatus.Ok });\n }\n }\n });\n\n res.once('finish', () => {\n const client = currentHub.getClient<NodeClient>();\n if (isAutoSessionTrackingEnabled(client)) {\n setImmediate(() => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (client && (client as any)._captureRequestSession) {\n // Calling _captureRequestSession to capture request session at the end of the request by incrementing\n // the correct SessionAggregates bucket i.e. crashed, errored or exited\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (client as any)._captureRequestSession();\n }\n });\n }\n });\n next();\n });\n };\n}\n\n/** JSDoc */\ninterface MiddlewareError extends Error {\n status?: number | string;\n statusCode?: number | string;\n status_code?: number | string;\n output?: {\n statusCode?: number | string;\n };\n}\n\n/** JSDoc */\nfunction getStatusCodeFromResponse(error: MiddlewareError): number {\n const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);\n return statusCode ? parseInt(statusCode as string, 10) : 500;\n}\n\n/** Returns true if response code is internal server error */\nfunction defaultShouldHandleError(error: MiddlewareError): boolean {\n const status = getStatusCodeFromResponse(error);\n return status >= 500;\n}\n\n/**\n * Express compatible error handler.\n * @see Exposed as `Handlers.errorHandler`\n */\nexport function errorHandler(options?: {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(error: MiddlewareError): boolean;\n}): (\n error: MiddlewareError,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n) => void {\n return function sentryErrorMiddleware(\n error: MiddlewareError,\n _req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n ): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;\n\n if (shouldHandleError(error)) {\n withScope(_scope => {\n // For some reason we need to set the transaction on the scope again\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const transaction = (res as any).__sentry_transaction as Span;\n if (transaction && _scope.getSpan() === undefined) {\n _scope.setSpan(transaction);\n }\n\n const client = getCurrentHub().getClient<NodeClient>();\n if (client && isAutoSessionTrackingEnabled(client)) {\n // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the\n // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only\n // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be\n // running in SessionAggregates mode\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const isSessionAggregatesMode = (client as any)._sessionFlusher !== undefined;\n if (isSessionAggregatesMode) {\n const requestSession = _scope.getRequestSession();\n // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a\n // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within\n // the bounds of a request, and if so the status is updated\n if (requestSession && requestSession.status !== undefined)\n requestSession.status = RequestSessionStatus.Crashed;\n }\n }\n\n const eventId = captureException(error);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res as any).sentry = eventId;\n next(error);\n });\n\n return;\n }\n\n next(error);\n };\n}\n", "export {\n Breadcrumb,\n BreadcrumbHint,\n Request,\n SdkInfo,\n Event,\n EventHint,\n Exception,\n Response,\n Severity,\n StackFrame,\n Stacktrace,\n Status,\n Thread,\n User,\n} from '@sentry/types';\n\nexport {\n addGlobalEventProcessor,\n addBreadcrumb,\n captureException,\n captureEvent,\n captureMessage,\n configureScope,\n getHubFromCarrier,\n getCurrentHub,\n Hub,\n makeMain,\n Scope,\n startTransaction,\n SDK_VERSION,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n} from '@sentry/core';\n\nexport { NodeOptions } from './types';\nexport { NodeBackend } from './backend';\nexport { NodeClient } from './client';\nexport { defaultIntegrations, init, lastEventId, flush, close, getSentryRelease } from './sdk';\nexport { deepReadDirSync } from './utils';\nexport { SDK_NAME } from './version';\n\nimport { Integrations as CoreIntegrations } from '@sentry/core';\nimport { getMainCarrier } from '@sentry/hub';\nimport * as domain from 'domain';\n\nimport * as Handlers from './handlers';\nimport * as NodeIntegrations from './integrations';\nimport * as Transports from './transports';\n\nconst INTEGRATIONS = {\n ...CoreIntegrations,\n ...NodeIntegrations,\n};\n\nexport { INTEGRATIONS as Integrations, Transports, Handlers };\n\n// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like\n// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.\nconst carrier = getMainCarrier();\nif (carrier.__SENTRY__) {\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain;\n}\n", "import { Event, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\n// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js\nconst angularPattern = /^\\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\\] (.*?)\\n?(\\S+)$/;\n\n/**\n * AngularJS integration\n *\n * Provides an $exceptionHandler for AngularJS\n */\nexport class Angular implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'AngularJS';\n\n /**\n * moduleName used in Angular's DI resolution algorithm\n */\n public static moduleName: string = 'ngSentry';\n\n /**\n * @inheritDoc\n */\n public name: string = Angular.id;\n\n /**\n * Angular's instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _angular: any;\n\n /**\n * ngSentry module instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _module: any;\n\n /**\n * Returns current hub.\n */\n private _getCurrentHub?: () => Hub;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options: { angular?: any } = {}) {\n logger.log('You are still using the Angular integration, consider moving to @sentry/angular');\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this._angular = options.angular || getGlobalObject<any>().angular;\n\n if (!this._angular) {\n logger.error('AngularIntegration is missing an Angular instance');\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._module = this._angular.module(Angular.moduleName, []);\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._module) {\n return;\n }\n\n this._getCurrentHub = getCurrentHub;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._module.config([\n '$provide',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ($provide: any): void => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n $provide.decorator('$exceptionHandler', ['$delegate', this._$exceptionHandlerDecorator.bind(this)]);\n },\n ]);\n }\n\n /**\n * Angular's exceptionHandler for Sentry integration\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _$exceptionHandlerDecorator($delegate: any): any {\n return (exception: Error, cause?: string): void => {\n const hub = this._getCurrentHub && this._getCurrentHub();\n\n if (hub && hub.getIntegration(Angular)) {\n hub.withScope(scope => {\n if (cause) {\n scope.setExtra('cause', cause);\n }\n\n scope.addEventProcessor((event: Event) => {\n const ex = event.exception && event.exception.values && event.exception.values[0];\n\n if (ex) {\n const matches = angularPattern.exec(ex.value || '');\n\n if (matches) {\n // This type now becomes something like: $rootScope:inprog\n ex.type = matches[1];\n ex.value = matches[2];\n event.message = `${ex.type}: ${ex.value}`;\n // auto set a new tag specifically for the angular error url\n event.extra = {\n ...event.extra,\n angularDocs: matches[3].substr(0, 250),\n };\n }\n }\n\n return event;\n });\n\n hub.captureException(exception);\n });\n }\n $delegate(exception, cause);\n };\n }\n}\n", "import { EventProcessor, Hub, Integration, Severity } from '@sentry/types';\nimport { fill, getGlobalObject, safeJoin } from '@sentry/utils';\n\nconst global = getGlobalObject<Window | NodeJS.Global>();\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: string[] = ['log', 'info', 'warn', 'error', 'debug', 'assert'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in global)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n if (!(level in global.console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(global.console, level, (originalConsoleLevel: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(Severity.fromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, global.console, args);\n }\n });\n });\n }\n}\n", "import { Event, EventHint, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\n\n/** JSDoc */\ninterface DebugOptions {\n stringify?: boolean;\n debugger?: boolean;\n}\n\n/** JSDoc */\nexport class Debug implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Debug';\n\n /**\n * @inheritDoc\n */\n public name: string = Debug.id;\n\n /** JSDoc */\n private readonly _options: DebugOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: DebugOptions) {\n this._options = {\n debugger: false,\n stringify: false,\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(Debug);\n if (self) {\n if (self._options.debugger) {\n // eslint-disable-next-line no-debugger\n debugger;\n }\n\n /* eslint-disable no-console */\n consoleSandbox(() => {\n if (self._options.stringify) {\n console.log(JSON.stringify(event, null, 2));\n if (hint) {\n console.log(JSON.stringify(hint, null, 2));\n }\n } else {\n console.log(event);\n if (hint) {\n console.log(hint);\n }\n }\n });\n /* eslint-enable no-console */\n }\n return event;\n });\n }\n}\n", "import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((currentEvent: Event) => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (self._shouldDropEvent(currentEvent, self._previousEvent)) {\n logger.warn(`Event dropped due to being a duplicate of previously captured event.`);\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n });\n }\n\n /** JSDoc */\n private _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (this._isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (this._isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n }\n\n /** JSDoc */\n private _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n } else if (event.stacktrace) {\n return event.stacktrace.frames;\n }\n return undefined;\n }\n\n /** JSDoc */\n private _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = this._getFramesFromEvent(currentEvent);\n let previousFrames = this._getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /** JSDoc */\n private _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n }\n\n /** JSDoc */\n private _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = this._getExceptionFromEvent(previousEvent);\n const currentException = this._getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n }\n}\n", "import { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, isInstanceOf, logger } from '@sentry/utils';\n\n/** JSDoc */\nexport class Ember implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Ember';\n\n /**\n * @inheritDoc\n */\n public name: string = Ember.id;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n private readonly _Ember: any;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options: { Ember?: any } = {}) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this._Ember = options.Ember || getGlobalObject<any>().Ember;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._Ember) {\n logger.error('EmberIntegration is missing an Ember instance');\n return;\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n const oldOnError = this._Ember.onerror;\n\n this._Ember.onerror = (error: Error): void => {\n if (getCurrentHub().getIntegration(Ember)) {\n getCurrentHub().captureException(error, { originalException: error });\n }\n\n if (typeof oldOnError === 'function') {\n oldOnError.call(this._Ember, error);\n } else if (this._Ember.testing) {\n throw error;\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._Ember.RSVP.on('error', (reason: unknown): void => {\n if (getCurrentHub().getIntegration(Ember)) {\n getCurrentHub().withScope(scope => {\n if (isInstanceOf(reason, Error)) {\n scope.setExtra('context', 'Unhandled Promise error detected');\n getCurrentHub().captureException(reason, { originalException: reason as Error });\n } else {\n scope.setExtra('reason', reason);\n getCurrentHub().captureMessage('Unhandled Promise error detected');\n }\n });\n }\n });\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n", "import { Event, EventHint, EventProcessor, ExtendedError, Hub, Integration } from '@sentry/types';\nimport { isError, isPlainObject, logger, normalize } from '@sentry/utils';\n\n/** JSDoc */\ninterface ExtraErrorDataOptions {\n depth?: number;\n}\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class ExtraErrorData implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'ExtraErrorData';\n\n /**\n * @inheritDoc\n */\n public name: string = ExtraErrorData.id;\n\n /**\n * @inheritDoc\n */\n public constructor(private readonly _options: ExtraErrorDataOptions = { depth: 3 }) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(ExtraErrorData);\n if (!self) {\n return event;\n }\n return self.enhanceEventWithErrorData(event, hint);\n });\n }\n\n /**\n * Attaches extracted information from the Error object to extra field in the Event\n */\n public enhanceEventWithErrorData(event: Event, hint?: EventHint): Event {\n if (!hint || !hint.originalException || !isError(hint.originalException)) {\n return event;\n }\n const name = (hint.originalException as ExtendedError).name || hint.originalException.constructor.name;\n\n const errorData = this._extractErrorData(hint.originalException as ExtendedError);\n\n if (errorData) {\n let contexts = {\n ...event.contexts,\n };\n\n const normalizedErrorData = normalize(errorData, this._options.depth);\n if (isPlainObject(normalizedErrorData)) {\n contexts = {\n ...event.contexts,\n [name]: {\n ...normalizedErrorData,\n },\n };\n }\n\n return {\n ...event,\n contexts,\n };\n }\n\n return event;\n }\n\n /**\n * Extract extra information from the Error object\n */\n private _extractErrorData(error: ExtendedError): Record<string, unknown> | null {\n // We are trying to enhance already existing event, so no harm done if it won't succeed\n try {\n const nativeKeys = [\n 'name',\n 'message',\n 'stack',\n 'line',\n 'column',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'toJSON',\n ];\n\n const extraErrorInfo: Record<string, unknown> = {};\n\n // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n for (const key of Object.keys(error)) {\n if (nativeKeys.indexOf(key) !== -1) {\n continue;\n }\n const value = error[key];\n extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;\n }\n\n // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n if (typeof error.toJSON === 'function') {\n const serializedError = error.toJSON() as Record<string, unknown>;\n\n for (const key of Object.keys(serializedError)) {\n const value = serializedError[key];\n extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;\n }\n }\n\n return extraErrorInfo;\n } catch (oO) {\n logger.error('Unable to extract extra data from the Error object:', oO);\n }\n\n return null;\n }\n}\n", "/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\n{\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { Event, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, logger, normalize, uuid4 } from '@sentry/utils';\nimport localForage from 'localforage';\n\ntype LocalForage = {\n setItem<T>(key: string, value: T, callback?: (err: any, value: T) => void): Promise<T>;\n iterate<T, U>(\n iteratee: (value: T, key: string, iterationNumber: number) => U,\n callback?: (err: any, result: U) => void,\n ): Promise<U>;\n removeItem(key: string, callback?: (err: any) => void): Promise<void>;\n};\n\n/**\n * cache offline errors and send when connected\n */\nexport class Offline implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Offline';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = Offline.id;\n\n /**\n * the global instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public global: any;\n\n /**\n * the current hub instance\n */\n public hub?: Hub;\n\n /**\n * maximum number of events to store while offline\n */\n public maxStoredEvents: number;\n\n /**\n * event cache\n */\n public offlineEventStore: LocalForage;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { maxStoredEvents?: number } = {}) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.global = getGlobalObject<any>();\n this.maxStoredEvents = options.maxStoredEvents || 30; // set a reasonable default\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this.offlineEventStore = localForage.createInstance({\n name: 'sentry/offlineEventStore',\n });\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this.hub = getCurrentHub();\n\n if ('addEventListener' in this.global) {\n this.global.addEventListener('online', () => {\n void this._sendEvents().catch(() => {\n logger.warn('could not send cached events');\n });\n });\n }\n\n addGlobalEventProcessor((event: Event) => {\n if (this.hub && this.hub.getIntegration(Offline)) {\n // cache if we are positively offline\n if ('navigator' in this.global && 'onLine' in this.global.navigator && !this.global.navigator.onLine) {\n void this._cacheEvent(event)\n .then((_event: Event): Promise<void> => this._enforceMaxEvents())\n .catch((_error): void => {\n logger.warn('could not cache event while offline');\n });\n\n // return null on success or failure, because being offline will still result in an error\n return null;\n }\n }\n\n return event;\n });\n\n // if online now, send any events stored in a previous offline session\n if ('navigator' in this.global && 'onLine' in this.global.navigator && this.global.navigator.onLine) {\n void this._sendEvents().catch(() => {\n logger.warn('could not send cached events');\n });\n }\n }\n\n /**\n * cache an event to send later\n * @param event an event\n */\n private async _cacheEvent(event: Event): Promise<Event> {\n return this.offlineEventStore.setItem<Event>(uuid4(), normalize(event));\n }\n\n /**\n * purge excess events if necessary\n */\n private async _enforceMaxEvents(): Promise<void> {\n const events: Array<{ event: Event; cacheKey: string }> = [];\n\n return this.offlineEventStore\n .iterate<Event, void>((event: Event, cacheKey: string, _index: number): void => {\n // aggregate events\n events.push({ cacheKey, event });\n })\n .then(\n (): Promise<void> =>\n // this promise resolves when the iteration is finished\n this._purgeEvents(\n // purge all events past maxStoredEvents in reverse chronological order\n events\n .sort((a, b) => (b.event.timestamp || 0) - (a.event.timestamp || 0))\n .slice(this.maxStoredEvents < events.length ? this.maxStoredEvents : events.length)\n .map(event => event.cacheKey),\n ),\n )\n .catch((_error): void => {\n logger.warn('could not enforce max events');\n });\n }\n\n /**\n * purge event from cache\n */\n private async _purgeEvent(cacheKey: string): Promise<void> {\n return this.offlineEventStore.removeItem(cacheKey);\n }\n\n /**\n * purge events from cache\n */\n private async _purgeEvents(cacheKeys: string[]): Promise<void> {\n // trail with .then to ensure the return type as void and not void|void[]\n return Promise.all(cacheKeys.map(cacheKey => this._purgeEvent(cacheKey))).then();\n }\n\n /**\n * send all events\n */\n private async _sendEvents(): Promise<void> {\n return this.offlineEventStore.iterate<Event, void>((event: Event, cacheKey: string, _index: number): void => {\n if (this.hub) {\n this.hub.captureEvent(event);\n\n void this._purgeEvent(cacheKey).catch((_error): void => {\n logger.warn('could not purge event from cache');\n });\n } else {\n logger.warn('no hub found - could not send cached event');\n }\n });\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, supportsReportingObserver } from '@sentry/utils';\n\n/** JSDoc */\ninterface Report {\n [key: string]: any;\n type: ReportTypes;\n url: string;\n body?: ReportBody;\n}\n\n/** JSDoc */\nconst enum ReportTypes {\n /** JSDoc */\n Crash = 'crash',\n /** JSDoc */\n Deprecation = 'deprecation',\n /** JSDoc */\n Intervention = 'intervention',\n}\n\n/** JSDoc */\ntype ReportBody = CrashReportBody | DeprecationReportBody | InterventionReportBody;\n\n/** JSDoc */\ninterface CrashReportBody {\n [key: string]: any;\n crashId: string;\n reason?: string;\n}\n\n/** JSDoc */\ninterface DeprecationReportBody {\n [key: string]: any;\n id: string;\n anticipatedRemoval?: Date;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\n/** JSDoc */\ninterface InterventionReportBody {\n [key: string]: any;\n id: string;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\n/** Reporting API integration - https://w3c.github.io/reporting/ */\nexport class ReportingObserver implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'ReportingObserver';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = ReportingObserver.id;\n\n /**\n * Returns current hub.\n */\n private _getCurrentHub?: () => Hub;\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n types?: ReportTypes[];\n } = {\n types: [ReportTypes.Crash, ReportTypes.Deprecation, ReportTypes.Intervention],\n },\n ) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!supportsReportingObserver()) {\n return;\n }\n\n this._getCurrentHub = getCurrentHub;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const observer = new (getGlobalObject<any>().ReportingObserver)(this.handler.bind(this), {\n buffered: true,\n types: this._options.types,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n observer.observe();\n }\n\n /**\n * @inheritDoc\n */\n public handler(reports: Report[]): void {\n const hub = this._getCurrentHub && this._getCurrentHub();\n if (!hub || !hub.getIntegration(ReportingObserver)) {\n return;\n }\n for (const report of reports) {\n hub.withScope(scope => {\n scope.setExtra('url', report.url);\n\n const label = `ReportingObserver [${report.type}]`;\n let details = 'No details available';\n\n if (report.body) {\n // Object.keys doesn't work on ReportBody, as all properties are inheirted\n const plainBody: {\n [key: string]: any;\n } = {};\n\n // eslint-disable-next-line guard-for-in\n for (const prop in report.body) {\n plainBody[prop] = report.body[prop];\n }\n\n scope.setExtra('body', plainBody);\n\n if (report.type === ReportTypes.Crash) {\n const body = report.body as CrashReportBody;\n // A fancy way to create a message out of crashId OR reason OR both OR fallback\n details = [body.crashId || '', body.reason || ''].join(' ').trim() || details;\n } else {\n const body = report.body as DeprecationReportBody | InterventionReportBody;\n details = body.message || details;\n }\n }\n\n hub.captureMessage(`${label}: ${details}`);\n });\n }\n }\n}\n", "import { Event, EventProcessor, Hub, Integration, StackFrame, Stacktrace } from '@sentry/types';\nimport { basename, relative } from '@sentry/utils';\n\ntype StackFrameIteratee = (frame: StackFrame) => StackFrame;\n\n/** Rewrite event frames paths */\nexport class RewriteFrames implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'RewriteFrames';\n\n /**\n * @inheritDoc\n */\n public name: string = RewriteFrames.id;\n\n /**\n * @inheritDoc\n */\n private readonly _root?: string;\n\n /**\n * @inheritDoc\n */\n private readonly _prefix: string = 'app:///';\n\n /**\n * @inheritDoc\n */\n public constructor(options: { root?: string; prefix?: string; iteratee?: StackFrameIteratee } = {}) {\n if (options.root) {\n this._root = options.root;\n }\n if (options.prefix) {\n this._prefix = options.prefix;\n }\n if (options.iteratee) {\n this._iteratee = options.iteratee;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(RewriteFrames);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /** JSDoc */\n public process(originalEvent: Event): Event {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = this._processExceptionsEvent(processedEvent);\n }\n\n if (originalEvent.stacktrace) {\n processedEvent = this._processStacktraceEvent(processedEvent);\n }\n\n return processedEvent;\n }\n\n /**\n * @inheritDoc\n */\n private readonly _iteratee: StackFrameIteratee = (frame: StackFrame) => {\n if (!frame.filename) {\n return frame;\n }\n // Check if the frame filename begins with `/` or a Windows-style prefix such as `C:\\`\n const isWindowsFrame = /^[A-Z]:\\\\/.test(frame.filename);\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = this._root ? relative(this._root, filename) : basename(filename);\n frame.filename = `${this._prefix}${base}`;\n }\n return frame;\n };\n\n /** JSDoc */\n private _processExceptionsEvent(event: Event): Event {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception!.values!.map(value => ({\n ...value,\n stacktrace: this._processStacktrace(value.stacktrace),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n private _processStacktraceEvent(event: Event): Event {\n try {\n return {\n ...event,\n stacktrace: this._processStacktrace(event.stacktrace),\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n private _processStacktrace(stacktrace?: Stacktrace): Stacktrace {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => this._iteratee(f)),\n };\n }\n}\n", "import { Event, EventProcessor, Hub, Integration } from '@sentry/types';\n\n/** This function adds duration since Sentry was initialized till the time event was sent */\nexport class SessionTiming implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'SessionTiming';\n\n /**\n * @inheritDoc\n */\n public name: string = SessionTiming.id;\n\n /** Exact time Client was initialized expressed in milliseconds since Unix Epoch. */\n protected readonly _startTime: number = Date.now();\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(SessionTiming);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n public process(event: Event): Event {\n const now = Date.now();\n\n return {\n ...event,\n extra: {\n ...event.extra,\n ['session:start']: this._startTime,\n ['session:duration']: now - this._startTime,\n ['session:end']: now,\n },\n };\n }\n}\n", "import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\n\n/** Add node transaction to the event */\nexport class Transaction implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Transaction';\n\n /**\n * @inheritDoc\n */\n public name: string = Transaction.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(Transaction);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n public process(event: Event): Event {\n const frames = this._getFramesFromEvent(event);\n\n // use for loop so we don't have to reverse whole frames array\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame.in_app === true) {\n event.transaction = this._getTransaction(frame);\n break;\n }\n }\n\n return event;\n }\n\n /** JSDoc */\n private _getFramesFromEvent(event: Event): StackFrame[] {\n const exception = event.exception && event.exception.values && event.exception.values[0];\n return (exception && exception.stacktrace && exception.stacktrace.frames) || [];\n }\n\n /** JSDoc */\n private _getTransaction(frame: StackFrame): string {\n return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>';\n }\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { EventProcessor, Hub, Integration, IntegrationClass, Scope, Span, Transaction } from '@sentry/types';\nimport { basename, getGlobalObject, logger, timestampWithMs } from '@sentry/utils';\n\n/**\n * Used to extract Tracing integration from the current client,\n * without the need to import `Tracing` itself from the @sentry/apm package.\n * @deprecated as @sentry/tracing should be used over @sentry/apm.\n */\nconst TRACING_GETTER = ({\n id: 'Tracing',\n} as any) as IntegrationClass<Integration>;\n\n/**\n * Used to extract BrowserTracing integration from @sentry/tracing\n */\nconst BROWSER_TRACING_GETTER = ({\n id: 'BrowserTracing',\n} as any) as IntegrationClass<Integration>;\n\nconst VUE_OP = 'ui.vue';\n\n/** Global Vue object limited to the methods/attributes we require */\ninterface VueInstance {\n config: {\n errorHandler?(error: Error, vm?: ViewModel, info?: string): void;\n };\n util?: {\n warn(...input: any): void;\n };\n mixin(hooks: { [key: string]: () => void }): void;\n}\n\n/** Representation of Vue component internals */\ninterface ViewModel {\n [key: string]: any;\n // eslint-disable-next-line @typescript-eslint/ban-types\n $root: object;\n $options: {\n [key: string]: any;\n name?: string;\n propsData?: { [key: string]: any };\n _componentTag?: string;\n __file?: string;\n $_sentryPerfHook?: boolean;\n };\n $once(hook: string, cb: () => void): void;\n}\n\n/** Vue Integration configuration */\ninterface IntegrationOptions {\n /** Vue instance to be used inside the integration */\n Vue: VueInstance;\n\n /**\n * When set to `false`, Sentry will suppress reporting of all props data\n * from your Vue components for privacy concerns.\n */\n attachProps: boolean;\n /**\n * When set to `true`, original Vue's `logError` will be called as well.\n * https://github.com/vuejs/vue/blob/c2b1cfe9ccd08835f2d99f6ce60f67b4de55187f/src/core/util/error.js#L38-L48\n */\n logErrors: boolean;\n\n /**\n * When set to `true`, enables tracking of components lifecycle performance.\n * It requires `Tracing` integration to be also enabled.\n */\n tracing: boolean;\n\n /** {@link TracingOptions} */\n tracingOptions: TracingOptions;\n}\n\n/** Vue specific configuration for Tracing Integration */\ninterface TracingOptions {\n /**\n * Decides whether to track components by hooking into its lifecycle methods.\n * Can be either set to `boolean` to enable/disable tracking for all of them.\n * Or to an array of specific component names (case-sensitive).\n */\n trackComponents: boolean | string[];\n /** How long to wait until the tracked root activity is marked as finished and sent of to Sentry */\n timeout: number;\n /**\n * List of hooks to keep track of during component lifecycle.\n * Available hooks: 'activate' | 'create' | 'destroy' | 'mount' | 'update'\n * Based on https://vuejs.org/v2/api/#Options-Lifecycle-Hooks\n */\n hooks: Operation[];\n}\n\n/** Optional metadata attached to Sentry Event */\ninterface Metadata {\n [key: string]: any;\n componentName?: string;\n propsData?: { [key: string]: any };\n lifecycleHook?: string;\n}\n\n// https://vuejs.org/v2/api/#Options-Lifecycle-Hooks\ntype Hook =\n | 'activated'\n | 'beforeCreate'\n | 'beforeDestroy'\n | 'beforeMount'\n | 'beforeUpdate'\n | 'created'\n | 'deactivated'\n | 'destroyed'\n | 'mounted'\n | 'updated';\n\ntype Operation = 'activate' | 'create' | 'destroy' | 'mount' | 'update';\n\n// Mappings from operation to corresponding lifecycle hook.\nconst HOOKS: { [key in Operation]: Hook[] } = {\n activate: ['activated', 'deactivated'],\n create: ['beforeCreate', 'created'],\n destroy: ['beforeDestroy', 'destroyed'],\n mount: ['beforeMount', 'mounted'],\n update: ['beforeUpdate', 'updated'],\n};\n\nconst COMPONENT_NAME_REGEXP = /(?:^|[-_/])(\\w)/g;\nconst ROOT_COMPONENT_NAME = 'root';\nconst ANONYMOUS_COMPONENT_NAME = 'anonymous component';\n\n/** JSDoc */\nexport class Vue implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Vue';\n\n /**\n * @inheritDoc\n */\n public name: string = Vue.id;\n\n private readonly _options: IntegrationOptions;\n\n /**\n * Cache holding already processed component names\n */\n private readonly _componentsCache: { [key: string]: string } = {};\n private _rootSpan?: Span;\n private _rootSpanTimer?: ReturnType<typeof setTimeout>;\n private _tracingActivity?: number;\n\n /**\n * @inheritDoc\n */\n public constructor(\n options: Partial<Omit<IntegrationOptions, 'tracingOptions'> & { tracingOptions: Partial<TracingOptions> }>,\n ) {\n logger.log('You are still using the Vue.js integration, consider moving to @sentry/vue');\n this._options = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Vue: getGlobalObject<any>().Vue,\n attachProps: true,\n logErrors: false,\n tracing: false,\n ...options,\n tracingOptions: {\n hooks: ['mount', 'update'],\n timeout: 2000,\n trackComponents: false,\n ...options.tracingOptions,\n },\n };\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._options.Vue) {\n logger.error('Vue integration is missing a Vue instance');\n return;\n }\n\n this._attachErrorHandler(getCurrentHub);\n\n if (this._options.tracing) {\n this._startTracing(getCurrentHub);\n }\n }\n\n /**\n * Extract component name from the ViewModel\n */\n private _getComponentName(vm: ViewModel): string {\n // Such level of granularity is most likely not necessary, but better safe than sorry. \u2014 Kamil\n if (!vm) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n if (vm.$root === vm) {\n return ROOT_COMPONENT_NAME;\n }\n\n if (!vm.$options) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n if (vm.$options.name) {\n return vm.$options.name;\n }\n\n if (vm.$options._componentTag) {\n return vm.$options._componentTag;\n }\n\n // injected by vue-loader\n if (vm.$options.__file) {\n const unifiedFile = vm.$options.__file.replace(/^[a-zA-Z]:/, '').replace(/\\\\/g, '/');\n const filename = basename(unifiedFile, '.vue');\n return (\n this._componentsCache[filename] ||\n (this._componentsCache[filename] = filename.replace(COMPONENT_NAME_REGEXP, (_, c: string) =>\n c ? c.toUpperCase() : '',\n ))\n );\n }\n\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n /** Keep it as attribute function, to keep correct `this` binding inside the hooks callbacks */\n // eslint-disable-next-line @typescript-eslint/typedef\n private readonly _applyTracingHooks = (vm: ViewModel, getCurrentHub: () => Hub): void => {\n // Don't attach twice, just in case\n if (vm.$options.$_sentryPerfHook) {\n return;\n }\n vm.$options.$_sentryPerfHook = true;\n\n const name = this._getComponentName(vm);\n const rootMount = name === ROOT_COMPONENT_NAME;\n const spans: { [key: string]: Span } = {};\n\n // Render hook starts after once event is emitted,\n // but it ends before the second event of the same type.\n //\n // Because of this, we start measuring inside the first event,\n // but finish it before it triggers, to skip the event emitter timing itself.\n const rootHandler = (hook: Hook): void => {\n const now = timestampWithMs();\n\n // On the first handler call (before), it'll be undefined, as `$once` will add it in the future.\n // However, on the second call (after), it'll be already in place.\n if (this._rootSpan) {\n this._finishRootSpan(now, getCurrentHub);\n } else {\n vm.$once(`hook:${hook}`, () => {\n // Create an activity on the first event call. There'll be no second call, as rootSpan will be in place,\n // thus new event handler won't be attached.\n\n // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.\n // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line deprecation/deprecation\n const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);\n if (tracingIntegration) {\n this._tracingActivity = (tracingIntegration as any).constructor.pushActivity('Vue Application Render');\n const transaction = (tracingIntegration as any).constructor.getTransaction();\n if (transaction) {\n this._rootSpan = transaction.startChild({\n description: 'Application Render',\n op: VUE_OP,\n });\n }\n // Use functionality from @sentry/tracing\n } else {\n const activeTransaction = getActiveTransaction(getCurrentHub());\n if (activeTransaction) {\n this._rootSpan = activeTransaction.startChild({\n description: 'Application Render',\n op: VUE_OP,\n });\n }\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n });\n }\n };\n\n const childHandler = (hook: Hook, operation: Operation): void => {\n // Skip components that we don't want to track to minimize the noise and give a more granular control to the user\n const shouldTrack = Array.isArray(this._options.tracingOptions.trackComponents)\n ? this._options.tracingOptions.trackComponents.indexOf(name) > -1\n : this._options.tracingOptions.trackComponents;\n\n if (!this._rootSpan || !shouldTrack) {\n return;\n }\n\n const now = timestampWithMs();\n const span = spans[operation];\n\n // On the first handler call (before), it'll be undefined, as `$once` will add it in the future.\n // However, on the second call (after), it'll be already in place.\n if (span) {\n span.finish();\n this._finishRootSpan(now, getCurrentHub);\n } else {\n vm.$once(`hook:${hook}`, () => {\n if (this._rootSpan) {\n spans[operation] = this._rootSpan.startChild({\n description: `Vue <${name}>`,\n op: `${VUE_OP}.${operation}`,\n });\n }\n });\n }\n };\n\n // Each component has it's own scope, so all activities are only related to one of them\n this._options.tracingOptions.hooks.forEach(operation => {\n // Retrieve corresponding hooks from Vue lifecycle.\n // eg. mount => ['beforeMount', 'mounted']\n const internalHooks = HOOKS[operation];\n\n if (!internalHooks) {\n logger.warn(`Unknown hook: ${operation}`);\n return;\n }\n\n internalHooks.forEach(internalHook => {\n const handler = rootMount\n ? rootHandler.bind(this, internalHook)\n : childHandler.bind(this, internalHook, operation);\n const currentValue = vm.$options[internalHook];\n\n if (Array.isArray(currentValue)) {\n vm.$options[internalHook] = [handler, ...currentValue];\n } else if (typeof currentValue === 'function') {\n vm.$options[internalHook] = [handler, currentValue];\n } else {\n vm.$options[internalHook] = [handler];\n }\n });\n });\n };\n\n /** Finish top-level span and activity with a debounce configured using `timeout` option */\n private _finishRootSpan(timestamp: number, getCurrentHub: () => Hub): void {\n if (this._rootSpanTimer) {\n clearTimeout(this._rootSpanTimer);\n }\n\n this._rootSpanTimer = setTimeout(() => {\n if (this._tracingActivity) {\n // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.\n // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.\n // eslint-disable-next-line deprecation/deprecation\n const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);\n if (tracingIntegration) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (tracingIntegration as any).constructor.popActivity(this._tracingActivity);\n }\n }\n\n // We should always finish the span, only should pop activity if using @sentry/apm\n if (this._rootSpan) {\n this._rootSpan.finish(timestamp);\n }\n }, this._options.tracingOptions.timeout);\n }\n\n /** Inject configured tracing hooks into Vue's component lifecycles */\n private _startTracing(getCurrentHub: () => Hub): void {\n const applyTracingHooks = this._applyTracingHooks;\n\n this._options.Vue.mixin({\n beforeCreate(this: ViewModel): void {\n // eslint-disable-next-line deprecation/deprecation\n if (getCurrentHub().getIntegration(TRACING_GETTER) || getCurrentHub().getIntegration(BROWSER_TRACING_GETTER)) {\n // `this` points to currently rendered component\n applyTracingHooks(this, getCurrentHub);\n } else {\n logger.error('Vue integration has tracing enabled, but Tracing integration is not configured');\n }\n },\n });\n }\n\n /** Inject Sentry's handler into owns Vue's error handler */\n private _attachErrorHandler(getCurrentHub: () => Hub): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const currentErrorHandler = this._options.Vue.config.errorHandler;\n\n this._options.Vue.config.errorHandler = (error: Error, vm?: ViewModel, info?: string): void => {\n const metadata: Metadata = {};\n\n if (vm) {\n try {\n metadata.componentName = this._getComponentName(vm);\n\n if (this._options.attachProps) {\n metadata.propsData = vm.$options.propsData;\n }\n } catch (_oO) {\n logger.warn('Unable to extract metadata from Vue component.');\n }\n }\n\n if (info) {\n metadata.lifecycleHook = info;\n }\n\n if (getCurrentHub().getIntegration(Vue)) {\n // Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time.\n setTimeout(() => {\n getCurrentHub().withScope(scope => {\n scope.setContext('vue', metadata);\n getCurrentHub().captureException(error);\n });\n });\n }\n\n if (typeof currentErrorHandler === 'function') {\n currentErrorHandler.call(this._options.Vue, error, vm, info);\n }\n\n if (this._options.logErrors) {\n if (this._options.Vue.util) {\n this._options.Vue.util.warn(`Error in ${info}: \"${error && error.toString()}\"`, vm);\n }\n // eslint-disable-next-line no-console\n console.error(error);\n }\n };\n }\n}\n\ninterface HubType extends Hub {\n getScope?(): Scope | undefined;\n}\n\n/** Grabs active transaction off scope */\nexport function getActiveTransaction<T extends Transaction>(hub: HubType): T | undefined {\n if (hub && hub.getScope) {\n const scope = hub.getScope() as Scope;\n if (scope) {\n return scope.getTransaction() as T | undefined;\n }\n }\n\n return undefined;\n}\n", "export { Angular } from './angular';\nexport { CaptureConsole } from './captureconsole';\nexport { Debug } from './debug';\nexport { Dedupe } from './dedupe';\nexport { Ember } from './ember';\nexport { ExtraErrorData } from './extraerrordata';\nexport { Offline } from './offline';\nexport { ReportingObserver } from './reportingobserver';\nexport { RewriteFrames } from './rewriteframes';\nexport { SessionTiming } from './sessiontiming';\nexport { Transaction } from './transaction';\nexport { Vue } from './vue';\n", "#!/usr/bin/env node\n\nimport program from 'commander'\n\nimport { getCountryFlag } from './index'\nimport * as Sentry from \"@sentry/node\";\n\n// Importing @sentry/tracing patches the global hub for tracing to work.\nimport * as Tracing from \"@sentry/tracing\";\nimport { RewriteFrames } from '@sentry/integrations';\n\nSentry.init({\n dsn: \"https://aec0873e750c49b082fe3594def15af1@o1116132.ingest.sentry.io/6149280\",\n\n // We recommend adjusting this value in production, or using tracesSampler\n // for finer control\n tracesSampleRate: 1.0,\n integrations: [new RewriteFrames({root: global.__rootdir__})]\n});\n\nprogram\n .version('0.1.0')\n .name('country-flag-cli')\n .command('get <flag>')\n .action((flag) => {\n const transaction = Sentry.startTransaction({\n op: \"get flag from 2 alpha code\",\n name: \"GET flag from 2 alpha code\"\n })\n try {\n const result = getCountryFlag(flag);\n if (result === undefined) throw new Error(`Flag: ${flag} \\nResult: ${result}\\n`)\n console.log(result);\n } catch (e) {\n Sentry.captureException(e);\n } finally {\n transaction.finish()\n }\n })\n\nprogram.parse(process.argv)\n", "export function getCountryFlag (countryCode: string): string | undefined {\n if (countryCode.length != 2) { return undefined}\n return countryCode.toUpperCase().replace(/./g, char => \n String.fromCodePoint(127397 + char.charCodeAt(0)));\n}\n "],
5
- "mappings": ";qmBAAA,mBAIA,GAAI,IAAe,QAAQ,UAAU,aACjC,GAAQ,QAAQ,iBAAiB,MACjC,GAAO,QAAQ,QACf,GAAU,GAAK,QACf,GAAW,GAAK,SAChB,GAAK,QAAQ,MAMjB,QAAQ,QAAQ,SAAS,EAAS,IAMlC,GAAU,GAAO,QAAU,GAAI,GAM/B,GAAQ,QAAU,EAMlB,GAAQ,OAAS,GAUjB,YAAgB,EAAO,EAAa,CAClC,KAAK,MAAQ,EACb,KAAK,SAAW,EAAM,QAAQ,MAAQ,EACtC,KAAK,SAAW,EAAM,QAAQ,MAAQ,EACtC,KAAK,KAAO,EAAM,QAAQ,UAAY,GACtC,EAAQ,EAAM,MAAM,UAChB,EAAM,OAAS,GAAK,CAAC,QAAQ,KAAK,EAAM,KAAK,MAAK,MAAQ,EAAM,SACpE,KAAK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ACR,KAAK,oBACL,QAAQ,cACR,OAAO,AAAC,GAAS,CAChB,GAAM,GAAc,AAAO,oBAAiB,CAC1C,GAAI,6BACJ,KAAM,+BAER,GAAI,CACF,GAAM,GAAS,GAAe,GAC9B,GAAI,IAAW,OAAW,KAAM,IAAI,OAAM,SAAS;AAAA,UAAkB;AAAA,GACrE,QAAQ,IAAI,SACL,EAAP,CACA,AAAO,oBAAiB,UACxB,CACA,EAAY,YAIlB,WAAQ,MAAM,QAAQ",
3
+ "sources": ["../node_modules/commander/index.js", "../node_modules/tslib/tslib.js", "../node_modules/@sentry/types/src/loglevel.ts", "../node_modules/@sentry/types/src/session.ts", "../node_modules/@sentry/types/src/severity.ts", "../node_modules/@sentry/types/src/status.ts", "../node_modules/@sentry/types/src/transaction.ts", "../node_modules/@sentry/types/src/transport.ts", "../node_modules/@sentry/types/src/index.ts", "../node_modules/@sentry/utils/src/async.ts", "../node_modules/@sentry/utils/src/node.ts", "../node_modules/@sentry/utils/src/global.ts", "../node_modules/@sentry/utils/src/is.ts", "../node_modules/@sentry/utils/src/browser.ts", "../node_modules/@sentry/utils/src/polyfill.ts", "../node_modules/@sentry/utils/src/error.ts", "../node_modules/@sentry/utils/src/dsn.ts", "../node_modules/@sentry/utils/src/logger.ts", "../node_modules/@sentry/utils/src/memo.ts", "../node_modules/@sentry/utils/src/stacktrace.ts", "../node_modules/@sentry/utils/src/string.ts", "../node_modules/@sentry/utils/src/object.ts", "../node_modules/@sentry/utils/src/supports.ts", "../node_modules/@sentry/utils/src/instrument.ts", "../node_modules/@sentry/utils/src/misc.ts", "../node_modules/@sentry/utils/src/path.ts", "../node_modules/@sentry/utils/src/syncpromise.ts", "../node_modules/@sentry/utils/src/promisebuffer.ts", "../node_modules/@sentry/utils/src/time.ts", "../node_modules/@sentry/utils/src/index.ts", "../node_modules/@sentry/hub/src/scope.ts", "../node_modules/@sentry/hub/src/session.ts", "../node_modules/@sentry/hub/src/hub.ts", "../node_modules/@sentry/hub/src/sessionflusher.ts", "../node_modules/@sentry/hub/src/index.ts", "../node_modules/@sentry/minimal/src/index.ts", "../node_modules/@sentry/core/src/api.ts", "../node_modules/@sentry/core/src/integration.ts", "../node_modules/@sentry/core/src/baseclient.ts", "../node_modules/@sentry/core/src/transports/noop.ts", "../node_modules/@sentry/core/src/basebackend.ts", "../node_modules/@sentry/core/src/request.ts", "../node_modules/@sentry/core/src/sdk.ts", "../node_modules/@sentry/core/src/version.ts", "../node_modules/@sentry/core/src/integrations/functiontostring.ts", "../node_modules/@sentry/core/src/integrations/inboundfilters.ts", "../node_modules/@sentry/core/src/integrations/index.ts", "../node_modules/@sentry/core/src/index.ts", "../node_modules/lru_map/lru.js", "../node_modules/@sentry/node/src/stacktrace.ts", "../node_modules/@sentry/node/src/parsers.ts", "../node_modules/@sentry/node/src/version.ts", "../node_modules/@sentry/node/src/transports/base/index.ts", "../node_modules/ms/index.js", "../node_modules/debug/src/common.js", "../node_modules/debug/src/browser.js", "../node_modules/has-flag/index.js", "../node_modules/supports-color/index.js", "../node_modules/debug/src/node.js", "../node_modules/debug/src/index.js", "../node_modules/agent-base/src/promisify.ts", "../node_modules/agent-base/src/index.ts", "../node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../node_modules/https-proxy-agent/src/agent.ts", "../node_modules/https-proxy-agent/src/index.ts", "../node_modules/@sentry/node/src/transports/http.ts", "../node_modules/@sentry/node/src/transports/https.ts", "../node_modules/@sentry/node/src/transports/index.ts", "../node_modules/@sentry/node/src/backend.ts", "../node_modules/@sentry/node/src/client.ts", "../node_modules/@sentry/node/src/integrations/console.ts", "../node_modules/@sentry/node/src/integrations/utils/http.ts", "../node_modules/@sentry/node/src/integrations/http.ts", "../node_modules/@sentry/node/src/integrations/utils/errorhandling.ts", "../node_modules/@sentry/node/src/integrations/onuncaughtexception.ts", "../node_modules/@sentry/node/src/integrations/onunhandledrejection.ts", "../node_modules/@sentry/node/src/integrations/linkederrors.ts", "../node_modules/@sentry/node/src/integrations/modules.ts", "../node_modules/@sentry/node/src/integrations/index.ts", "../node_modules/@sentry/node/src/sdk.ts", "../node_modules/@sentry/node/src/utils.ts", "../node_modules/@sentry/tracing/src/spanstatus.ts", "../node_modules/@sentry/tracing/src/utils.ts", "../node_modules/@sentry/tracing/src/errors.ts", "../node_modules/@sentry/tracing/src/constants.ts", "../node_modules/@sentry/tracing/src/span.ts", "../node_modules/@sentry/tracing/src/transaction.ts", "../node_modules/@sentry/tracing/src/idletransaction.ts", "../node_modules/@sentry/tracing/src/hubextensions.ts", "../node_modules/@sentry/tracing/src/integrations/node/express.ts", "../node_modules/@sentry/tracing/src/integrations/node/postgres.ts", "../node_modules/@sentry/tracing/src/integrations/node/mysql.ts", "../node_modules/@sentry/tracing/src/integrations/node/mongo.ts", "../node_modules/@sentry/tracing/src/browser/backgroundtab.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/bindReporter.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/generateUniqueID.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/initMetric.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/observe.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/onHidden.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getCLS.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/lib/getVisibilityWatcher.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getFID.ts", "../node_modules/@sentry/tracing/src/browser/web-vitals/getLCP.ts", "../node_modules/@sentry/tracing/src/browser/metrics.ts", "../node_modules/@sentry/tracing/src/browser/request.ts", "../node_modules/@sentry/tracing/src/browser/router.ts", "../node_modules/@sentry/tracing/src/browser/browsertracing.ts", "../node_modules/@sentry/tracing/src/browser/index.ts", "../node_modules/@sentry/tracing/src/integrations/index.ts", "../node_modules/@sentry/tracing/src/index.ts", "../node_modules/cookie/index.js", "../node_modules/@sentry/node/src/handlers.ts", "../node_modules/@sentry/node/src/index.ts", "../node_modules/@sentry/integrations/src/angular.ts", "../node_modules/@sentry/integrations/src/captureconsole.ts", "../node_modules/@sentry/integrations/src/debug.ts", "../node_modules/@sentry/integrations/src/dedupe.ts", "../node_modules/@sentry/integrations/src/ember.ts", "../node_modules/@sentry/integrations/src/extraerrordata.ts", "../node_modules/localforage/dist/localforage.js", "../node_modules/@sentry/integrations/src/offline.ts", "../node_modules/@sentry/integrations/src/reportingobserver.ts", "../node_modules/@sentry/integrations/src/rewriteframes.ts", "../node_modules/@sentry/integrations/src/sessiontiming.ts", "../node_modules/@sentry/integrations/src/transaction.ts", "../node_modules/@sentry/integrations/src/vue.ts", "../node_modules/@sentry/integrations/src/index.ts", "../node_modules/source-map/lib/base64.js", "../node_modules/source-map/lib/base64-vlq.js", "../node_modules/source-map/lib/util.js", "../node_modules/source-map/lib/array-set.js", "../node_modules/source-map/lib/mapping-list.js", "../node_modules/source-map/lib/source-map-generator.js", "../node_modules/source-map/lib/binary-search.js", "../node_modules/source-map/lib/quick-sort.js", "../node_modules/source-map/lib/source-map-consumer.js", "../node_modules/source-map/lib/source-node.js", "../node_modules/source-map/source-map.js", "../node_modules/buffer-from/index.js", "../node_modules/source-map-support/source-map-support.js", "../src/cli.ts", "../src/index.ts", "../node_modules/source-map-support/register.js"],
4
+ "sourcesContent": ["/**\n * Module dependencies.\n */\n\nvar EventEmitter = require('events').EventEmitter;\nvar spawn = require('child_process').spawn;\nvar path = require('path');\nvar dirname = path.dirname;\nvar basename = path.basename;\nvar fs = require('fs');\n\n/**\n * Inherit `Command` from `EventEmitter.prototype`.\n */\n\nrequire('util').inherits(Command, EventEmitter);\n\n/**\n * Expose the root command.\n */\n\nexports = module.exports = new Command();\n\n/**\n * Expose `Command`.\n */\n\nexports.Command = Command;\n\n/**\n * Expose `Option`.\n */\n\nexports.Option = Option;\n\n/**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {String} flags\n * @param {String} description\n * @api public\n */\n\nfunction Option(flags, description) {\n this.flags = flags;\n this.required = flags.indexOf('<') >= 0;\n this.optional = flags.indexOf('[') >= 0;\n this.bool = flags.indexOf('-no-') === -1;\n flags = flags.split(/[ ,|]+/);\n if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();\n this.long = flags.shift();\n this.description = description || '';\n}\n\n/**\n * Return option name.\n *\n * @return {String}\n * @api private\n */\n\nOption.prototype.name = function() {\n return this.long\n .replace('--', '')\n .replace('no-', '');\n};\n\n/**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {String}\n * @api private\n */\n\nOption.prototype.attributeName = function() {\n return camelcase(this.name());\n};\n\n/**\n * Check if `arg` matches the short or long flag.\n *\n * @param {String} arg\n * @return {Boolean}\n * @api private\n */\n\nOption.prototype.is = function(arg) {\n return this.short === arg || this.long === arg;\n};\n\n/**\n * Initialize a new `Command`.\n *\n * @param {String} name\n * @api public\n */\n\nfunction Command(name) {\n this.commands = [];\n this.options = [];\n this._execs = {};\n this._allowUnknownOption = false;\n this._args = [];\n this._name = name || '';\n}\n\n/**\n * Add command `name`.\n *\n * The `.action()` callback is invoked when the\n * command `name` is specified via __ARGV__,\n * and the remaining arguments are applied to the\n * function for access.\n *\n * When the `name` is \"*\" an un-matched command\n * will be passed as the first arg, followed by\n * the rest of __ARGV__ remaining.\n *\n * Examples:\n *\n * program\n * .version('0.0.1')\n * .option('-C, --chdir <path>', 'change the working directory')\n * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')\n * .option('-T, --no-tests', 'ignore test hook')\n *\n * program\n * .command('setup')\n * .description('run remote setup commands')\n * .action(function() {\n * console.log('setup');\n * });\n *\n * program\n * .command('exec <cmd>')\n * .description('run the given remote command')\n * .action(function(cmd) {\n * console.log('exec \"%s\"', cmd);\n * });\n *\n * program\n * .command('teardown <dir> [otherDirs...]')\n * .description('run teardown commands')\n * .action(function(dir, otherDirs) {\n * console.log('dir \"%s\"', dir);\n * if (otherDirs) {\n * otherDirs.forEach(function (oDir) {\n * console.log('dir \"%s\"', oDir);\n * });\n * }\n * });\n *\n * program\n * .command('*')\n * .description('deploy the given env')\n * .action(function(env) {\n * console.log('deploying \"%s\"', env);\n * });\n *\n * program.parse(process.argv);\n *\n * @param {String} name\n * @param {String} [desc] for git-style sub-commands\n * @return {Command} the new command\n * @api public\n */\n\nCommand.prototype.command = function(name, desc, opts) {\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n var args = name.split(/ +/);\n var cmd = new Command(args.shift());\n\n if (desc) {\n cmd.description(desc);\n this.executables = true;\n this._execs[cmd._name] = true;\n if (opts.isDefault) this.defaultExecutable = cmd._name;\n }\n cmd._noHelp = !!opts.noHelp;\n this.commands.push(cmd);\n cmd.parseExpectedArgs(args);\n cmd.parent = this;\n\n if (desc) return this;\n return cmd;\n};\n\n/**\n * Define argument syntax for the top-level command.\n *\n * @api public\n */\n\nCommand.prototype.arguments = function(desc) {\n return this.parseExpectedArgs(desc.split(/ +/));\n};\n\n/**\n * Add an implicit `help [cmd]` subcommand\n * which invokes `--help` for the given command.\n *\n * @api private\n */\n\nCommand.prototype.addImplicitHelpCommand = function() {\n this.command('help [cmd]', 'display help for [cmd]');\n};\n\n/**\n * Parse expected `args`.\n *\n * For example `[\"[type]\"]` becomes `[{ required: false, name: 'type' }]`.\n *\n * @param {Array} args\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.parseExpectedArgs = function(args) {\n if (!args.length) return;\n var self = this;\n args.forEach(function(arg) {\n var argDetails = {\n required: false,\n name: '',\n variadic: false\n };\n\n switch (arg[0]) {\n case '<':\n argDetails.required = true;\n argDetails.name = arg.slice(1, -1);\n break;\n case '[':\n argDetails.name = arg.slice(1, -1);\n break;\n }\n\n if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {\n argDetails.variadic = true;\n argDetails.name = argDetails.name.slice(0, -3);\n }\n if (argDetails.name) {\n self._args.push(argDetails);\n }\n });\n return this;\n};\n\n/**\n * Register callback `fn` for the command.\n *\n * Examples:\n *\n * program\n * .command('help')\n * .description('display verbose help')\n * .action(function() {\n * // output help here\n * });\n *\n * @param {Function} fn\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.action = function(fn) {\n var self = this;\n var listener = function(args, unknown) {\n // Parse any so-far unknown options\n args = args || [];\n unknown = unknown || [];\n\n var parsed = self.parseOptions(unknown);\n\n // Output help if necessary\n outputHelpIfNecessary(self, parsed.unknown);\n\n // If there are still any unknown options, then we simply\n // die, unless someone asked for help, in which case we give it\n // to them, and then we die.\n if (parsed.unknown.length > 0) {\n self.unknownOption(parsed.unknown[0]);\n }\n\n // Leftover arguments need to be pushed back. Fixes issue #56\n if (parsed.args.length) args = parsed.args.concat(args);\n\n self._args.forEach(function(arg, i) {\n if (arg.required && args[i] == null) {\n self.missingArgument(arg.name);\n } else if (arg.variadic) {\n if (i !== self._args.length - 1) {\n self.variadicArgNotLast(arg.name);\n }\n\n args[i] = args.splice(i);\n }\n });\n\n // Always append ourselves to the end of the arguments,\n // to make sure we match the number of arguments the user\n // expects\n if (self._args.length) {\n args[self._args.length] = self;\n } else {\n args.push(self);\n }\n\n fn.apply(self, args);\n };\n var parent = this.parent || this;\n var name = parent === this ? '*' : this._name;\n parent.on('command:' + name, listener);\n if (this._alias) parent.on('command:' + this._alias, listener);\n return this;\n};\n\n/**\n * Define option with `flags`, `description` and optional\n * coercion `fn`.\n *\n * The `flags` string should contain both the short and long flags,\n * separated by comma, a pipe or space. The following are all valid\n * all will output this way when `--help` is used.\n *\n * \"-p, --pepper\"\n * \"-p|--pepper\"\n * \"-p --pepper\"\n *\n * Examples:\n *\n * // simple boolean defaulting to false\n * program.option('-p, --pepper', 'add pepper');\n *\n * --pepper\n * program.pepper\n * // => Boolean\n *\n * // simple boolean defaulting to true\n * program.option('-C, --no-cheese', 'remove cheese');\n *\n * program.cheese\n * // => true\n *\n * --no-cheese\n * program.cheese\n * // => false\n *\n * // required argument\n * program.option('-C, --chdir <path>', 'change the working directory');\n *\n * --chdir /tmp\n * program.chdir\n * // => \"/tmp\"\n *\n * // optional argument\n * program.option('-c, --cheese [type]', 'add cheese [marble]');\n *\n * @param {String} flags\n * @param {String} description\n * @param {Function|*} [fn] or default\n * @param {*} [defaultValue]\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.option = function(flags, description, fn, defaultValue) {\n var self = this,\n option = new Option(flags, description),\n oname = option.name(),\n name = option.attributeName();\n\n // default as 3rd arg\n if (typeof fn !== 'function') {\n if (fn instanceof RegExp) {\n var regex = fn;\n fn = function(val, def) {\n var m = regex.exec(val);\n return m ? m[0] : def;\n };\n } else {\n defaultValue = fn;\n fn = null;\n }\n }\n\n // preassign default value only for --no-*, [optional], or <required>\n if (!option.bool || option.optional || option.required) {\n // when --no-* we make sure default is true\n if (!option.bool) defaultValue = true;\n // preassign only if we have a default\n if (defaultValue !== undefined) {\n self[name] = defaultValue;\n option.defaultValue = defaultValue;\n }\n }\n\n // register the option\n this.options.push(option);\n\n // when it's passed assign the value\n // and conditionally invoke the callback\n this.on('option:' + oname, function(val) {\n // coercion\n if (val !== null && fn) {\n val = fn(val, self[name] === undefined ? defaultValue : self[name]);\n }\n\n // unassigned or bool\n if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {\n // if no value, bool true, and we have a default, then use it!\n if (val == null) {\n self[name] = option.bool\n ? defaultValue || true\n : false;\n } else {\n self[name] = val;\n }\n } else if (val !== null) {\n // reassign\n self[name] = val;\n }\n });\n\n return this;\n};\n\n/**\n * Allow unknown options on the command line.\n *\n * @param {Boolean} arg if `true` or omitted, no error will be thrown\n * for unknown options.\n * @api public\n */\nCommand.prototype.allowUnknownOption = function(arg) {\n this._allowUnknownOption = arguments.length === 0 || arg;\n return this;\n};\n\n/**\n * Parse `argv`, settings options and invoking commands when defined.\n *\n * @param {Array} argv\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.parse = function(argv) {\n // implicit help\n if (this.executables) this.addImplicitHelpCommand();\n\n // store raw args\n this.rawArgs = argv;\n\n // guess name\n this._name = this._name || basename(argv[1], '.js');\n\n // github-style sub-commands with no sub-command\n if (this.executables && argv.length < 3 && !this.defaultExecutable) {\n // this user needs help\n argv.push('--help');\n }\n\n // process argv\n var parsed = this.parseOptions(this.normalize(argv.slice(2)));\n var args = this.args = parsed.args;\n\n var result = this.parseArgs(this.args, parsed.unknown);\n\n // executable sub-commands\n var name = result.args[0];\n\n var aliasCommand = null;\n // check alias of sub commands\n if (name) {\n aliasCommand = this.commands.filter(function(command) {\n return command.alias() === name;\n })[0];\n }\n\n if (this._execs[name] === true) {\n return this.executeSubCommand(argv, args, parsed.unknown);\n } else if (aliasCommand) {\n // is alias of a subCommand\n args[0] = aliasCommand._name;\n return this.executeSubCommand(argv, args, parsed.unknown);\n } else if (this.defaultExecutable) {\n // use the default subcommand\n args.unshift(this.defaultExecutable);\n return this.executeSubCommand(argv, args, parsed.unknown);\n }\n\n return result;\n};\n\n/**\n * Execute a sub-command executable.\n *\n * @param {Array} argv\n * @param {Array} args\n * @param {Array} unknown\n * @api private\n */\n\nCommand.prototype.executeSubCommand = function(argv, args, unknown) {\n args = args.concat(unknown);\n\n if (!args.length) this.help();\n if (args[0] === 'help' && args.length === 1) this.help();\n\n // <cmd> --help\n if (args[0] === 'help') {\n args[0] = args[1];\n args[1] = '--help';\n }\n\n // executable\n var f = argv[1];\n // name of the subcommand, link `pm-install`\n var bin = basename(f, path.extname(f)) + '-' + args[0];\n\n // In case of globally installed, get the base dir where executable\n // subcommand file should be located at\n var baseDir;\n\n var resolvedLink = fs.realpathSync(f);\n\n baseDir = dirname(resolvedLink);\n\n // prefer local `./<bin>` to bin in the $PATH\n var localBin = path.join(baseDir, bin);\n\n // whether bin file is a js script with explicit `.js` or `.ts` extension\n var isExplicitJS = false;\n if (exists(localBin + '.js')) {\n bin = localBin + '.js';\n isExplicitJS = true;\n } else if (exists(localBin + '.ts')) {\n bin = localBin + '.ts';\n isExplicitJS = true;\n } else if (exists(localBin)) {\n bin = localBin;\n }\n\n args = args.slice(1);\n\n var proc;\n if (process.platform !== 'win32') {\n if (isExplicitJS) {\n args.unshift(bin);\n // add executable arguments to spawn\n args = (process.execArgv || []).concat(args);\n\n proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });\n } else {\n proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });\n }\n } else {\n args.unshift(bin);\n proc = spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach(function(signal) {\n process.on(signal, function() {\n if (proc.killed === false && proc.exitCode === null) {\n proc.kill(signal);\n }\n });\n });\n proc.on('close', process.exit.bind(process));\n proc.on('error', function(err) {\n if (err.code === 'ENOENT') {\n console.error('error: %s(1) does not exist, try --help', bin);\n } else if (err.code === 'EACCES') {\n console.error('error: %s(1) not executable. try chmod or run with root', bin);\n }\n process.exit(1);\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n};\n\n/**\n * Normalize `args`, splitting joined short flags. For example\n * the arg \"-abc\" is equivalent to \"-a -b -c\".\n * This also normalizes equal sign and splits \"--abc=def\" into \"--abc def\".\n *\n * @param {Array} args\n * @return {Array}\n * @api private\n */\n\nCommand.prototype.normalize = function(args) {\n var ret = [],\n arg,\n lastOpt,\n index;\n\n for (var i = 0, len = args.length; i < len; ++i) {\n arg = args[i];\n if (i > 0) {\n lastOpt = this.optionFor(args[i - 1]);\n }\n\n if (arg === '--') {\n // Honor option terminator\n ret = ret.concat(args.slice(i));\n break;\n } else if (lastOpt && lastOpt.required) {\n ret.push(arg);\n } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {\n arg.slice(1).split('').forEach(function(c) {\n ret.push('-' + c);\n });\n } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {\n ret.push(arg.slice(0, index), arg.slice(index + 1));\n } else {\n ret.push(arg);\n }\n }\n\n return ret;\n};\n\n/**\n * Parse command `args`.\n *\n * When listener(s) are available those\n * callbacks are invoked, otherwise the \"*\"\n * event is emitted and those actions are invoked.\n *\n * @param {Array} args\n * @return {Command} for chaining\n * @api private\n */\n\nCommand.prototype.parseArgs = function(args, unknown) {\n var name;\n\n if (args.length) {\n name = args[0];\n if (this.listeners('command:' + name).length) {\n this.emit('command:' + args.shift(), args, unknown);\n } else {\n this.emit('command:*', args);\n }\n } else {\n outputHelpIfNecessary(this, unknown);\n\n // If there were no args and we have unknown options,\n // then they are extraneous and we need to error.\n if (unknown.length > 0) {\n this.unknownOption(unknown[0]);\n }\n if (this.commands.length === 0 &&\n this._args.filter(function(a) { return a.required; }).length === 0) {\n this.emit('command:*');\n }\n }\n\n return this;\n};\n\n/**\n * Return an option matching `arg` if any.\n *\n * @param {String} arg\n * @return {Option}\n * @api private\n */\n\nCommand.prototype.optionFor = function(arg) {\n for (var i = 0, len = this.options.length; i < len; ++i) {\n if (this.options[i].is(arg)) {\n return this.options[i];\n }\n }\n};\n\n/**\n * Parse options from `argv` returning `argv`\n * void of these options.\n *\n * @param {Array} argv\n * @return {Array}\n * @api public\n */\n\nCommand.prototype.parseOptions = function(argv) {\n var args = [],\n len = argv.length,\n literal,\n option,\n arg;\n\n var unknownOptions = [];\n\n // parse options\n for (var i = 0; i < len; ++i) {\n arg = argv[i];\n\n // literal args after --\n if (literal) {\n args.push(arg);\n continue;\n }\n\n if (arg === '--') {\n literal = true;\n continue;\n }\n\n // find matching Option\n option = this.optionFor(arg);\n\n // option is defined\n if (option) {\n // requires arg\n if (option.required) {\n arg = argv[++i];\n if (arg == null) return this.optionMissingArgument(option);\n this.emit('option:' + option.name(), arg);\n // optional arg\n } else if (option.optional) {\n arg = argv[i + 1];\n if (arg == null || (arg[0] === '-' && arg !== '-')) {\n arg = null;\n } else {\n ++i;\n }\n this.emit('option:' + option.name(), arg);\n // bool\n } else {\n this.emit('option:' + option.name());\n }\n continue;\n }\n\n // looks like an option\n if (arg.length > 1 && arg[0] === '-') {\n unknownOptions.push(arg);\n\n // If the next argument looks like it might be\n // an argument for this option, we pass it on.\n // If it isn't, then it'll simply be ignored\n if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {\n unknownOptions.push(argv[++i]);\n }\n continue;\n }\n\n // arg\n args.push(arg);\n }\n\n return { args: args, unknown: unknownOptions };\n};\n\n/**\n * Return an object containing options as key-value pairs\n *\n * @return {Object}\n * @api public\n */\nCommand.prototype.opts = function() {\n var result = {},\n len = this.options.length;\n\n for (var i = 0; i < len; i++) {\n var key = this.options[i].attributeName();\n result[key] = key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n};\n\n/**\n * Argument `name` is missing.\n *\n * @param {String} name\n * @api private\n */\n\nCommand.prototype.missingArgument = function(name) {\n console.error(\"error: missing required argument `%s'\", name);\n process.exit(1);\n};\n\n/**\n * `Option` is missing an argument, but received `flag` or nothing.\n *\n * @param {String} option\n * @param {String} flag\n * @api private\n */\n\nCommand.prototype.optionMissingArgument = function(option, flag) {\n if (flag) {\n console.error(\"error: option `%s' argument missing, got `%s'\", option.flags, flag);\n } else {\n console.error(\"error: option `%s' argument missing\", option.flags);\n }\n process.exit(1);\n};\n\n/**\n * Unknown option `flag`.\n *\n * @param {String} flag\n * @api private\n */\n\nCommand.prototype.unknownOption = function(flag) {\n if (this._allowUnknownOption) return;\n console.error(\"error: unknown option `%s'\", flag);\n process.exit(1);\n};\n\n/**\n * Variadic argument with `name` is not the last argument as required.\n *\n * @param {String} name\n * @api private\n */\n\nCommand.prototype.variadicArgNotLast = function(name) {\n console.error(\"error: variadic arguments must be last `%s'\", name);\n process.exit(1);\n};\n\n/**\n * Set the program version to `str`.\n *\n * This method auto-registers the \"-V, --version\" flag\n * which will print the version number when passed.\n *\n * @param {String} str\n * @param {String} [flags]\n * @return {Command} for chaining\n * @api public\n */\n\nCommand.prototype.version = function(str, flags) {\n if (arguments.length === 0) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n var versionOption = new Option(flags, 'output the version number');\n this._versionOptionName = versionOption.long.substr(2) || 'version';\n this.options.push(versionOption);\n this.on('option:' + this._versionOptionName, function() {\n process.stdout.write(str + '\\n');\n process.exit(0);\n });\n return this;\n};\n\n/**\n * Set the description to `str`.\n *\n * @param {String} str\n * @param {Object} argsDescription\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.description = function(str, argsDescription) {\n if (arguments.length === 0) return this._description;\n this._description = str;\n this._argsDescription = argsDescription;\n return this;\n};\n\n/**\n * Set an alias for the command\n *\n * @param {String} alias\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.alias = function(alias) {\n var command = this;\n if (this.commands.length !== 0) {\n command = this.commands[this.commands.length - 1];\n }\n\n if (arguments.length === 0) return command._alias;\n\n if (alias === command._name) throw new Error('Command alias can\\'t be the same as its name');\n\n command._alias = alias;\n return this;\n};\n\n/**\n * Set / get the command usage `str`.\n *\n * @param {String} str\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.usage = function(str) {\n var args = this._args.map(function(arg) {\n return humanReadableArgName(arg);\n });\n\n var usage = '[options]' +\n (this.commands.length ? ' [command]' : '') +\n (this._args.length ? ' ' + args.join(' ') : '');\n\n if (arguments.length === 0) return this._usage || usage;\n this._usage = str;\n\n return this;\n};\n\n/**\n * Get or set the name of the command\n *\n * @param {String} str\n * @return {String|Command}\n * @api public\n */\n\nCommand.prototype.name = function(str) {\n if (arguments.length === 0) return this._name;\n this._name = str;\n return this;\n};\n\n/**\n * Return prepared commands.\n *\n * @return {Array}\n * @api private\n */\n\nCommand.prototype.prepareCommands = function() {\n return this.commands.filter(function(cmd) {\n return !cmd._noHelp;\n }).map(function(cmd) {\n var args = cmd._args.map(function(arg) {\n return humanReadableArgName(arg);\n }).join(' ');\n\n return [\n cmd._name +\n (cmd._alias ? '|' + cmd._alias : '') +\n (cmd.options.length ? ' [options]' : '') +\n (args ? ' ' + args : ''),\n cmd._description\n ];\n });\n};\n\n/**\n * Return the largest command length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestCommandLength = function() {\n var commands = this.prepareCommands();\n return commands.reduce(function(max, command) {\n return Math.max(max, command[0].length);\n }, 0);\n};\n\n/**\n * Return the largest option length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestOptionLength = function() {\n var options = [].slice.call(this.options);\n options.push({\n flags: '-h, --help'\n });\n return options.reduce(function(max, option) {\n return Math.max(max, option.flags.length);\n }, 0);\n};\n\n/**\n * Return the largest arg length.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.largestArgLength = function() {\n return this._args.reduce(function(max, arg) {\n return Math.max(max, arg.name.length);\n }, 0);\n};\n\n/**\n * Return the pad width.\n *\n * @return {Number}\n * @api private\n */\n\nCommand.prototype.padWidth = function() {\n var width = this.largestOptionLength();\n if (this._argsDescription && this._args.length) {\n if (this.largestArgLength() > width) {\n width = this.largestArgLength();\n }\n }\n\n if (this.commands && this.commands.length) {\n if (this.largestCommandLength() > width) {\n width = this.largestCommandLength();\n }\n }\n\n return width;\n};\n\n/**\n * Return help for options.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.optionHelp = function() {\n var width = this.padWidth();\n\n // Append the help information\n return this.options.map(function(option) {\n return pad(option.flags, width) + ' ' + option.description +\n ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');\n }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])\n .join('\\n');\n};\n\n/**\n * Return command help documentation.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.commandHelp = function() {\n if (!this.commands.length) return '';\n\n var commands = this.prepareCommands();\n var width = this.padWidth();\n\n return [\n 'Commands:',\n commands.map(function(cmd) {\n var desc = cmd[1] ? ' ' + cmd[1] : '';\n return (desc ? pad(cmd[0], width) : cmd[0]) + desc;\n }).join('\\n').replace(/^/gm, ' '),\n ''\n ].join('\\n');\n};\n\n/**\n * Return program help documentation.\n *\n * @return {String}\n * @api private\n */\n\nCommand.prototype.helpInformation = function() {\n var desc = [];\n if (this._description) {\n desc = [\n this._description,\n ''\n ];\n\n var argsDescription = this._argsDescription;\n if (argsDescription && this._args.length) {\n var width = this.padWidth();\n desc.push('Arguments:');\n desc.push('');\n this._args.forEach(function(arg) {\n desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);\n });\n desc.push('');\n }\n }\n\n var cmdName = this._name;\n if (this._alias) {\n cmdName = cmdName + '|' + this._alias;\n }\n var usage = [\n 'Usage: ' + cmdName + ' ' + this.usage(),\n ''\n ];\n\n var cmds = [];\n var commandHelp = this.commandHelp();\n if (commandHelp) cmds = [commandHelp];\n\n var options = [\n 'Options:',\n '' + this.optionHelp().replace(/^/gm, ' '),\n ''\n ];\n\n return usage\n .concat(desc)\n .concat(options)\n .concat(cmds)\n .join('\\n');\n};\n\n/**\n * Output help information for this command\n *\n * @api public\n */\n\nCommand.prototype.outputHelp = function(cb) {\n if (!cb) {\n cb = function(passthru) {\n return passthru;\n };\n }\n process.stdout.write(cb(this.helpInformation()));\n this.emit('--help');\n};\n\n/**\n * Output help information and exit.\n *\n * @api public\n */\n\nCommand.prototype.help = function(cb) {\n this.outputHelp(cb);\n process.exit();\n};\n\n/**\n * Camel-case the given `flag`\n *\n * @param {String} flag\n * @return {String}\n * @api private\n */\n\nfunction camelcase(flag) {\n return flag.split('-').reduce(function(str, word) {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Pad `str` to `width`.\n *\n * @param {String} str\n * @param {Number} width\n * @return {String}\n * @api private\n */\n\nfunction pad(str, width) {\n var len = Math.max(0, width - str.length);\n return str + Array(len + 1).join(' ');\n}\n\n/**\n * Output help information if necessary\n *\n * @param {Command} command to output help for\n * @param {Array} array of options to search for -h or --help\n * @api private\n */\n\nfunction outputHelpIfNecessary(cmd, options) {\n options = options || [];\n for (var i = 0; i < options.length; i++) {\n if (options[i] === '--help' || options[i] === '-h') {\n cmd.outputHelp();\n process.exit(0);\n }\n }\n}\n\n/**\n * Takes an argument an returns its human readable equivalent for help usage.\n *\n * @param {Object} arg\n * @return {String}\n * @api private\n */\n\nfunction humanReadableArgName(arg) {\n var nameOutput = arg.name + (arg.variadic === true ? '...' : '');\n\n return arg.required\n ? '<' + nameOutput + '>'\n : '[' + nameOutput + ']';\n}\n\n// for versions before node v0.8 when there weren't `fs.existsSync`\nfunction exists(file) {\n try {\n if (fs.statSync(file).isFile()) {\n return true;\n }\n } catch (e) {\n return false;\n }\n}\n", "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\n/* global global, define, System, Reflect, Promise */\r\nvar __extends;\r\nvar __assign;\r\nvar __rest;\r\nvar __decorate;\r\nvar __param;\r\nvar __metadata;\r\nvar __awaiter;\r\nvar __generator;\r\nvar __exportStar;\r\nvar __values;\r\nvar __read;\r\nvar __spread;\r\nvar __spreadArrays;\r\nvar __await;\r\nvar __asyncGenerator;\r\nvar __asyncDelegator;\r\nvar __asyncValues;\r\nvar __makeTemplateObject;\r\nvar __importStar;\r\nvar __importDefault;\r\nvar __classPrivateFieldGet;\r\nvar __classPrivateFieldSet;\r\nvar __createBinding;\r\n(function (factory) {\r\n var root = typeof global === \"object\" ? global : typeof self === \"object\" ? self : typeof this === \"object\" ? this : {};\r\n if (typeof define === \"function\" && define.amd) {\r\n define(\"tslib\", [\"exports\"], function (exports) { factory(createExporter(root, createExporter(exports))); });\r\n }\r\n else if (typeof module === \"object\" && typeof module.exports === \"object\") {\r\n factory(createExporter(root, createExporter(module.exports)));\r\n }\r\n else {\r\n factory(createExporter(root));\r\n }\r\n function createExporter(exports, previous) {\r\n if (exports !== root) {\r\n if (typeof Object.create === \"function\") {\r\n Object.defineProperty(exports, \"__esModule\", { value: true });\r\n }\r\n else {\r\n exports.__esModule = true;\r\n }\r\n }\r\n return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };\r\n }\r\n})\r\n(function (exporter) {\r\n var extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\n __extends = function (d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n };\r\n\r\n __assign = Object.assign || function (t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n\r\n __rest = function (s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n };\r\n\r\n __decorate = function (decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n };\r\n\r\n __param = function (paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n };\r\n\r\n __metadata = function (metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n };\r\n\r\n __awaiter = function (thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n };\r\n\r\n __generator = function (thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n };\r\n\r\n __createBinding = function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n };\r\n\r\n __exportStar = function (m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n };\r\n\r\n __values = function (o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n };\r\n\r\n __read = function (o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n };\r\n\r\n __spread = function () {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n };\r\n\r\n __spreadArrays = function () {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n };\r\n\r\n __await = function (v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n };\r\n\r\n __asyncGenerator = function (thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n };\r\n\r\n __asyncDelegator = function (o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n };\r\n\r\n __asyncValues = function (o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n };\r\n\r\n __makeTemplateObject = function (cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n };\r\n\r\n __importStar = function (mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result[\"default\"] = mod;\r\n return result;\r\n };\r\n\r\n __importDefault = function (mod) {\r\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\r\n };\r\n\r\n __classPrivateFieldGet = function (receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n };\r\n\r\n __classPrivateFieldSet = function (receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n };\r\n\r\n exporter(\"__extends\", __extends);\r\n exporter(\"__assign\", __assign);\r\n exporter(\"__rest\", __rest);\r\n exporter(\"__decorate\", __decorate);\r\n exporter(\"__param\", __param);\r\n exporter(\"__metadata\", __metadata);\r\n exporter(\"__awaiter\", __awaiter);\r\n exporter(\"__generator\", __generator);\r\n exporter(\"__exportStar\", __exportStar);\r\n exporter(\"__createBinding\", __createBinding);\r\n exporter(\"__values\", __values);\r\n exporter(\"__read\", __read);\r\n exporter(\"__spread\", __spread);\r\n exporter(\"__spreadArrays\", __spreadArrays);\r\n exporter(\"__await\", __await);\r\n exporter(\"__asyncGenerator\", __asyncGenerator);\r\n exporter(\"__asyncDelegator\", __asyncDelegator);\r\n exporter(\"__asyncValues\", __asyncValues);\r\n exporter(\"__makeTemplateObject\", __makeTemplateObject);\r\n exporter(\"__importStar\", __importStar);\r\n exporter(\"__importDefault\", __importDefault);\r\n exporter(\"__classPrivateFieldGet\", __classPrivateFieldGet);\r\n exporter(\"__classPrivateFieldSet\", __classPrivateFieldSet);\r\n});\r\n", "/** Console logging verbosity for the SDK. */\nexport enum LogLevel {\n /** No logs will be generated. */\n None = 0,\n /** Only SDK internal errors will be logged. */\n Error = 1,\n /** Information useful for debugging the SDK will be logged. */\n Debug = 2,\n /** All SDK actions will be logged. */\n Verbose = 3,\n}\n", "import { User } from './user';\n\n/**\n * @inheritdoc\n */\nexport interface Session extends SessionContext {\n /** JSDoc */\n update(context?: SessionContext): void;\n\n /** JSDoc */\n close(status?: SessionStatus): void;\n\n /** JSDoc */\n toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n };\n}\n\nexport interface RequestSession {\n status?: RequestSessionStatus;\n}\n\n/**\n * Session Context\n */\nexport interface SessionContext {\n sid?: string;\n did?: string;\n init?: boolean;\n // seconds since the UNIX epoch\n timestamp?: number;\n // seconds since the UNIX epoch\n started?: number;\n duration?: number;\n status?: SessionStatus;\n release?: string;\n environment?: string;\n userAgent?: string;\n ipAddress?: string;\n errors?: number;\n user?: User | null;\n ignoreDuration?: boolean;\n}\n\n/**\n * Session Status\n */\nexport enum SessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Exited = 'exited',\n /** JSDoc */\n Crashed = 'crashed',\n /** JSDoc */\n Abnormal = 'abnormal',\n}\n\nexport enum RequestSessionStatus {\n /** JSDoc */\n Ok = 'ok',\n /** JSDoc */\n Errored = 'errored',\n /** JSDoc */\n Crashed = 'crashed',\n}\n\n/** JSDoc */\nexport interface SessionAggregates {\n attrs?: {\n environment?: string;\n release?: string;\n };\n aggregates: Array<AggregationCounts>;\n}\n\nexport interface SessionFlusherLike {\n /**\n * Increments the Session Status bucket in SessionAggregates Object corresponding to the status of the session\n * captured\n */\n incrementSessionStatusCount(): void;\n\n /** Submits the aggregates request mode sessions to Sentry */\n sendSessionAggregates(sessionAggregates: SessionAggregates): void;\n\n /** Empties Aggregate Buckets and Sends them to Transport Buffer */\n flush(): void;\n\n /** Clears setInterval and calls flush */\n close(): void;\n}\n\nexport interface AggregationCounts {\n started: string;\n errored?: number;\n exited?: number;\n crashed?: number;\n}\n", "/** JSDoc */\n// eslint-disable-next-line import/export\nexport enum Severity {\n /** JSDoc */\n Fatal = 'fatal',\n /** JSDoc */\n Error = 'error',\n /** JSDoc */\n Warning = 'warning',\n /** JSDoc */\n Log = 'log',\n /** JSDoc */\n Info = 'info',\n /** JSDoc */\n Debug = 'debug',\n /** JSDoc */\n Critical = 'critical',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Severity {\n /**\n * Converts a string-based level into a {@link Severity}.\n *\n * @param level string representation of Severity\n * @returns Severity\n */\n export function fromString(level: string): Severity {\n switch (level) {\n case 'debug':\n return Severity.Debug;\n case 'info':\n return Severity.Info;\n case 'warn':\n case 'warning':\n return Severity.Warning;\n case 'error':\n return Severity.Error;\n case 'fatal':\n return Severity.Fatal;\n case 'critical':\n return Severity.Critical;\n case 'log':\n default:\n return Severity.Log;\n }\n }\n}\n", "/** The status of an event. */\n// eslint-disable-next-line import/export\nexport enum Status {\n /** The status could not be determined. */\n Unknown = 'unknown',\n /** The event was skipped due to configuration or callbacks. */\n Skipped = 'skipped',\n /** The event was sent to Sentry successfully. */\n Success = 'success',\n /** The client is currently rate limited and will try again later. */\n RateLimit = 'rate_limit',\n /** The event could not be processed. */\n Invalid = 'invalid',\n /** A server-side error occurred during submission. */\n Failed = 'failed',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace Status {\n /**\n * Converts a HTTP status code into a {@link Status}.\n *\n * @param code The HTTP response status code.\n * @returns The send status or {@link Status.Unknown}.\n */\n export function fromHttpCode(code: number): Status {\n if (code >= 200 && code < 300) {\n return Status.Success;\n }\n\n if (code === 429) {\n return Status.RateLimit;\n }\n\n if (code >= 400 && code < 500) {\n return Status.Invalid;\n }\n\n if (code >= 500) {\n return Status.Failed;\n }\n\n return Status.Unknown;\n }\n}\n", "import { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';\nimport { Span, SpanContext } from './span';\n\n/**\n * Interface holding Transaction-specific properties\n */\nexport interface TransactionContext extends SpanContext {\n /**\n * Human-readable identifier for the transaction\n */\n name: string;\n\n /**\n * If true, sets the end timestamp of the transaction to the highest timestamp of child spans, trimming\n * the duration of the transaction. This is useful to discard extra time in the transaction that is not\n * accounted for in child spans, like what happens in the idle transaction Tracing integration, where we finish the\n * transaction after a given \"idle time\" and we don't want this \"idle time\" to be part of the transaction.\n */\n trimEnd?: boolean;\n\n /**\n * If this transaction has a parent, the parent's sampling decision\n */\n parentSampled?: boolean;\n\n /**\n * Metadata associated with the transaction, for internal SDK use.\n */\n metadata?: TransactionMetadata;\n}\n\n/**\n * Data pulled from a `sentry-trace` header\n */\nexport type TraceparentData = Pick<TransactionContext, 'traceId' | 'parentSpanId' | 'parentSampled'>;\n\n/**\n * Transaction \"Class\", inherits Span only has `setName`\n */\nexport interface Transaction extends TransactionContext, Span {\n /**\n * @inheritDoc\n */\n spanId: string;\n\n /**\n * @inheritDoc\n */\n traceId: string;\n\n /**\n * @inheritDoc\n */\n startTimestamp: number;\n\n /**\n * @inheritDoc\n */\n tags: { [key: string]: Primitive };\n\n /**\n * @inheritDoc\n */\n data: { [key: string]: any };\n\n /**\n * Metadata about the transaction\n */\n metadata: TransactionMetadata;\n\n /**\n * Set the name of the transaction\n */\n setName(name: string): void;\n\n /** Returns the current transaction properties as a `TransactionContext` */\n toContext(): TransactionContext;\n\n /** Updates the current transaction with a new `TransactionContext` */\n updateWithContext(transactionContext: TransactionContext): this;\n}\n\n/**\n * Context data passed by the user when starting a transaction, to be used by the tracesSampler method.\n */\nexport interface CustomSamplingContext {\n [key: string]: any;\n}\n\n/**\n * Data passed to the `tracesSampler` function, which forms the basis for whatever decisions it might make.\n *\n * Adds default data to data provided by the user. See {@link Hub.startTransaction}\n */\nexport interface SamplingContext extends CustomSamplingContext {\n /**\n * Context data with which transaction being sampled was created\n */\n transactionContext: TransactionContext;\n\n /**\n * Sampling decision from the parent transaction, if any.\n */\n parentSampled?: boolean;\n\n /**\n * Object representing the URL of the current page or worker script. Passed by default when using the `BrowserTracing`\n * integration.\n */\n location?: WorkerLocation;\n\n /**\n * Object representing the incoming request to a node server. Passed by default when using the TracingHandler.\n */\n request?: ExtractedNodeRequestData;\n}\n\nexport type Measurements = Record<string, { value: number }>;\n\nexport enum TransactionSamplingMethod {\n Explicit = 'explicitly_set',\n Sampler = 'client_sampler',\n Rate = 'client_rate',\n Inheritance = 'inheritance',\n}\n\nexport interface TransactionMetadata {\n transactionSampling?: { rate?: number; method?: string };\n\n /** The two halves (sentry and third-party) of a transaction's tracestate header, used for dynamic sampling */\n tracestate?: {\n sentry?: string;\n thirdparty?: string;\n };\n\n /** For transactions tracing server-side request handling, the path of the request being tracked. */\n requestPath?: string;\n}\n", "import { DsnLike } from './dsn';\nimport { Event } from './event';\nimport { SentryRequestType } from './request';\nimport { Response } from './response';\nimport { SdkMetadata } from './sdkmetadata';\nimport { Session, SessionAggregates } from './session';\n\nexport enum Outcome {\n BeforeSend = 'before_send',\n EventProcessor = 'event_processor',\n NetworkError = 'network_error',\n QueueOverflow = 'queue_overflow',\n RateLimitBackoff = 'ratelimit_backoff',\n SampleRate = 'sample_rate',\n}\n\n/** Transport used sending data to Sentry */\nexport interface Transport {\n /**\n * Sends the event to the Store endpoint in Sentry.\n *\n * @param event Event that should be sent to Sentry.\n */\n sendEvent(event: Event): PromiseLike<Response>;\n\n /**\n * Sends the session to the Envelope endpoint in Sentry.\n *\n * @param session Session that should be sent to Sentry | Session Aggregates that should be sent to Sentry.\n */\n sendSession?(session: Session | SessionAggregates): PromiseLike<Response>;\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the transport should wait for events to be flushed. Omitting this parameter will\n * cause the transport to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n close(timeout?: number): PromiseLike<boolean>;\n\n /**\n * Increment the counter for the specific client outcome\n */\n recordLostEvent?(type: Outcome, category: SentryRequestType): void;\n}\n\n/** JSDoc */\nexport type TransportClass<T extends Transport> = new (options: TransportOptions) => T;\n\n/** JSDoc */\nexport interface TransportOptions {\n /** Sentry DSN */\n dsn: DsnLike;\n /** Define custom headers */\n headers?: { [key: string]: string };\n /** Set a HTTP proxy that should be used for outbound requests. */\n httpProxy?: string;\n /** Set a HTTPS proxy that should be used for outbound requests. */\n httpsProxy?: string;\n /** HTTPS proxy certificates path */\n caCerts?: string;\n /** Fetch API init parameters */\n fetchParameters?: { [key: string]: string };\n /** The envelope tunnel to use. */\n tunnel?: string;\n /** Send SDK Client Reports. Enabled by default. */\n sendClientReports?: boolean;\n /**\n * Set of metadata about the SDK that can be internally used to enhance envelopes and events,\n * and provide additional data about every request.\n * */\n _metadata?: SdkMetadata;\n}\n", "export { Breadcrumb, BreadcrumbHint } from './breadcrumb';\nexport { Client } from './client';\nexport { Context, Contexts } from './context';\nexport { Dsn, DsnComponents, DsnLike, DsnProtocol } from './dsn';\nexport { DebugImage, DebugImageType, DebugMeta } from './debugMeta';\nexport { ExtendedError } from './error';\nexport { Event, EventHint } from './event';\nexport { EventProcessor } from './eventprocessor';\nexport { Exception } from './exception';\nexport { Extra, Extras } from './extra';\nexport { Hub } from './hub';\nexport { Integration, IntegrationClass } from './integration';\nexport { LogLevel } from './loglevel';\nexport { Mechanism } from './mechanism';\nexport { ExtractedNodeRequestData, Primitive, WorkerLocation } from './misc';\nexport { Options } from './options';\nexport { Package } from './package';\nexport { QueryParams, Request, SentryRequest, SentryRequestType } from './request';\nexport { Response } from './response';\nexport { Runtime } from './runtime';\nexport { CaptureContext, Scope, ScopeContext } from './scope';\nexport { SdkInfo } from './sdkinfo';\nexport { SdkMetadata } from './sdkmetadata';\nexport {\n SessionAggregates,\n AggregationCounts,\n Session,\n SessionContext,\n SessionStatus,\n RequestSession,\n RequestSessionStatus,\n SessionFlusherLike,\n} from './session';\nexport { Severity } from './severity';\nexport { Span, SpanContext } from './span';\nexport { StackFrame } from './stackframe';\nexport { Stacktrace } from './stacktrace';\nexport { Status } from './status';\nexport {\n CustomSamplingContext,\n Measurements,\n SamplingContext,\n TraceparentData,\n Transaction,\n TransactionContext,\n TransactionMetadata,\n TransactionSamplingMethod,\n} from './transaction';\nexport { Thread } from './thread';\nexport { Outcome, Transport, TransportOptions, TransportClass } from './transport';\nexport { User } from './user';\nexport { WrappedFunction } from './wrappedfunction';\n", "/**\n * Consumes the promise and logs the error when it rejects.\n * @param promise A promise to forget.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function forget(promise: PromiseLike<any>): void {\n void promise.then(null, e => {\n // TODO: Use a better logging mechanism\n // eslint-disable-next-line no-console\n console.error(e);\n });\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nexport function isNodeEnv(): boolean {\n return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\nexport function dynamicRequire(mod: any, request: string): any {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @returns possibly required module\n */\nexport function loadModule<T>(moduleName: string): T | undefined {\n let mod: T | undefined;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { Integration } from '@sentry/types';\n\nimport { isNodeEnv } from './node';\n\n/** Internal */\ninterface SentryGlobal {\n Sentry?: {\n Integrations?: Integration[];\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n __SENTRY__: {\n globalEventProcessors: any;\n hub: any;\n logger: any;\n };\n}\n\nconst fallbackGlobalObject = {};\n\n/**\n * Safely get global scope object\n *\n * @returns Global scope object\n */\nexport function getGlobalObject<T>(): T & SentryGlobal {\n return (isNodeEnv()\n ? global\n : typeof window !== 'undefined' // eslint-disable-line no-restricted-globals\n ? window // eslint-disable-line no-restricted-globals\n : typeof self !== 'undefined'\n ? self\n : fallbackGlobalObject) as T & SentryGlobal;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n\nimport { Primitive } from '@sentry/types';\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: any): boolean {\n switch (Object.prototype.toString.call(wat)) {\n case '[object Error]':\n return true;\n case '[object Exception]':\n return true;\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object ErrorEvent]';\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object DOMError]';\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object DOMException]';\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object String]';\n}\n\n/**\n * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: any): wat is Primitive {\n return wat === null || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object Object]';\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: any): boolean {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: any): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: any): boolean {\n return Object.prototype.toString.call(wat) === '[object RegExp]';\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: any): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n", "import { getGlobalObject } from './global';\nimport { isString } from './is';\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(elem: unknown, keyAttrs?: string[]): string {\n type SimpleNode = {\n parentNode: SimpleNode;\n } | null;\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem as SimpleNode;\n const MAX_TRAVERSE_HEIGHT = 5;\n const MAX_OUTPUT_LEN = 80;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n\n // eslint-disable-next-line no-plusplus\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds MAX_OUTPUT_LEN\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '<unknown>';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\n };\n\n const out = [];\n let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs?.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\n }\n }\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nexport function getLocationHref(): string {\n const global = getGlobalObject<Window>();\n try {\n return global.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n", "export const setPrototypeOf =\n Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);\n\n/**\n * setPrototypeOf polyfill using __proto__\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction setProtoOf<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n // @ts-ignore __proto__ does not exist on obj\n obj.__proto__ = proto;\n return obj as TTarget & TProto;\n}\n\n/**\n * setPrototypeOf polyfill using mixin\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction mixinProperties<TTarget extends object, TProto>(obj: TTarget, proto: TProto): TTarget & TProto {\n for (const prop in proto) {\n if (!Object.prototype.hasOwnProperty.call(obj, prop)) {\n // @ts-ignore typescript complains about indexing so we remove\n obj[prop] = proto[prop];\n }\n }\n\n return obj as TTarget & TProto;\n}\n", "import { setPrototypeOf } from './polyfill';\n\n/** An error emitted by Sentry SDKs and related utilities. */\nexport class SentryError extends Error {\n /** Display name of this error instance. */\n public name: string;\n\n public constructor(public message: string) {\n super(message);\n\n this.name = new.target.prototype.constructor.name;\n setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { DsnComponents, DsnLike, DsnProtocol } from '@sentry/types';\n\nimport { SentryError } from './error';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+))?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\n/** Error message */\nconst ERROR_MESSAGE = 'Invalid Dsn';\n\n/** The Sentry Dsn, identifying a Sentry instance and project. */\nexport class Dsn implements DsnComponents {\n /** Protocol used to connect to Sentry. */\n public protocol!: DsnProtocol;\n /** Public authorization key (deprecated, renamed to publicKey). */\n public user!: string;\n /** Public authorization key. */\n public publicKey!: string;\n /** Private authorization key (deprecated, optional). */\n public pass!: string;\n /** Hostname of the Sentry instance. */\n public host!: string;\n /** Port of the Sentry instance. */\n public port!: string;\n /** Path */\n public path!: string;\n /** Project ID */\n public projectId!: string;\n\n /** Creates a new Dsn component */\n public constructor(from: DsnLike) {\n if (typeof from === 'string') {\n this._fromString(from);\n } else {\n this._fromComponents(from);\n }\n\n this._validate();\n }\n\n /**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\n public toString(withPassword: boolean = false): string {\n const { host, path, pass, port, projectId, protocol, publicKey } = this;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n }\n\n /** Parses a string into this Dsn. */\n private _fromString(str: string): void {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n throw new SentryError(ERROR_MESSAGE);\n }\n\n const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() as string;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n this._fromComponents({ host, pass, path, projectId, port, protocol: protocol as DsnProtocol, publicKey });\n }\n\n /** Maps Dsn components into this instance. */\n private _fromComponents(components: DsnComponents): void {\n // TODO this is for backwards compatibility, and can be removed in a future version\n if ('user' in components && !('publicKey' in components)) {\n components.publicKey = components.user;\n }\n this.user = components.publicKey || '';\n\n this.protocol = components.protocol;\n this.publicKey = components.publicKey || '';\n this.pass = components.pass || '';\n this.host = components.host;\n this.port = components.port || '';\n this.path = components.path || '';\n this.projectId = components.projectId;\n }\n\n /** Validates this Dsn and throws on error. */\n private _validate(): void {\n ['protocol', 'publicKey', 'host', 'projectId'].forEach(component => {\n if (!this[component as keyof DsnComponents]) {\n throw new SentryError(`${ERROR_MESSAGE}: ${component} missing`);\n }\n });\n\n if (!this.projectId.match(/^\\d+$/)) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid projectId ${this.projectId}`);\n }\n\n if (this.protocol !== 'http' && this.protocol !== 'https') {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid protocol ${this.protocol}`);\n }\n\n if (this.port && isNaN(parseInt(this.port, 10))) {\n throw new SentryError(`${ERROR_MESSAGE}: Invalid port ${this.port}`);\n }\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\n\n// TODO: Implement different loggers for different environments\nconst global = getGlobalObject<Window | NodeJS.Global>();\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** JSDoc */\ninterface ExtensibleConsole extends Console {\n [key: string]: any;\n}\n\n/**\n * Temporarily unwrap `console.log` and friends in order to perform the given callback using the original methods.\n * Restores wrapping after the callback completes.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => any): any {\n const global = getGlobalObject<Window>();\n const levels = ['debug', 'info', 'warn', 'error', 'log', 'assert'];\n\n if (!('console' in global)) {\n return callback();\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const originalConsole = (global as any).console as ExtensibleConsole;\n const wrappedLevels: { [key: string]: any } = {};\n\n // Restore all wrapped console methods\n levels.forEach(level => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (level in (global as any).console && (originalConsole[level] as WrappedFunction).__sentry_original__) {\n wrappedLevels[level] = originalConsole[level] as WrappedFunction;\n originalConsole[level] = (originalConsole[level] as WrappedFunction).__sentry_original__;\n }\n });\n\n // Perform callback manipulations\n const result = callback();\n\n // Revert restoration to wrapped state\n Object.keys(wrappedLevels).forEach(level => {\n originalConsole[level] = wrappedLevels[level];\n });\n\n return result;\n}\n\n/** JSDoc */\nclass Logger {\n /** JSDoc */\n private _enabled: boolean;\n\n /** JSDoc */\n public constructor() {\n this._enabled = false;\n }\n\n /** JSDoc */\n public disable(): void {\n this._enabled = false;\n }\n\n /** JSDoc */\n public enable(): void {\n this._enabled = true;\n }\n\n /** JSDoc */\n public log(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.log(`${PREFIX}[Log]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public warn(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.warn(`${PREFIX}[Warn]: ${args.join(' ')}`);\n });\n }\n\n /** JSDoc */\n public error(...args: any[]): void {\n if (!this._enabled) {\n return;\n }\n consoleSandbox(() => {\n global.console.error(`${PREFIX}[Error]: ${args.join(' ')}`);\n });\n }\n}\n\n// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used\nglobal.__SENTRY__ = global.__SENTRY__ || {};\nconst logger = (global.__SENTRY__.logger as Logger) || (global.__SENTRY__.logger = new Logger());\n\nexport { logger };\n", "/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/**\n * Memo class used for decycle json objects. Uses WeakSet if available otherwise array.\n */\nexport class Memo {\n /** Determines if WeakSet is available */\n private readonly _hasWeakSet: boolean;\n /** Either WeakSet or Array */\n private readonly _inner: any;\n\n public constructor() {\n this._hasWeakSet = typeof WeakSet === 'function';\n this._inner = this._hasWeakSet ? new WeakSet() : [];\n }\n\n /**\n * Sets obj to remember.\n * @param obj Object to remember\n */\n public memoize(obj: any): boolean {\n if (this._hasWeakSet) {\n if (this._inner.has(obj)) {\n return true;\n }\n this._inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < this._inner.length; i++) {\n const value = this._inner[i];\n if (value === obj) {\n return true;\n }\n }\n this._inner.push(obj);\n return false;\n }\n\n /**\n * Removes object from internal storage.\n * @param obj Object to forget\n */\n public unmemoize(obj: any): void {\n if (this._hasWeakSet) {\n this._inner.delete(obj);\n } else {\n for (let i = 0; i < this._inner.length; i++) {\n if (this._inner[i] === obj) {\n this._inner.splice(i, 1);\n break;\n }\n }\n }\n }\n}\n", "const defaultFunctionName = '<anonymous>';\n\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn: unknown): string {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n", "import { isRegExp, isString } from './is';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str: string, max: number = 0): string {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.substr(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line: string, colno: number): string {\n let newLine = line;\n const ll = newLine.length;\n if (ll <= 150) {\n return newLine;\n }\n if (colno > ll) {\n // eslint-disable-next-line no-param-reassign\n colno = ll;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, ll);\n if (end > ll - 5) {\n end = ll;\n }\n if (end === ll) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < ll) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input: any[], delimiter?: string): string {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n output.push(String(value));\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the value matches a regex or includes the string\n * @param value The string value to be checked against\n * @param pattern Either a regex or a string that must be contained in value\n */\nexport function isMatchingPattern(value: string, pattern: RegExp | string): boolean {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return (pattern as RegExp).test(value);\n }\n if (typeof pattern === 'string') {\n return value.indexOf(pattern) !== -1;\n }\n return false;\n}\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString: string): string {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { ExtendedError, WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive, isSyntheticEvent } from './is';\nimport { Memo } from './memo';\nimport { getFunctionName } from './stacktrace';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other\n * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n try {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __sentry_original__: {\n enumerable: false,\n value: original,\n },\n });\n } catch (_Oo) {\n // This can throw if multiple fill happens on a global object like XMLHttpRequest\n // Fixes https://github.com/getsentry/sentry-javascript/issues/2043\n }\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any object into an object literal with all its attributes\n * attached to it.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n */\nfunction getWalkSource(\n value: any,\n): {\n [key: string]: any;\n} {\n if (isError(value)) {\n const error = value as ExtendedError;\n const err: {\n [key: string]: any;\n stack: string | undefined;\n message: string;\n name: string;\n } = {\n message: error.message,\n name: error.name,\n stack: error.stack,\n };\n\n for (const i in error) {\n if (Object.prototype.hasOwnProperty.call(error, i)) {\n err[i] = error[i];\n }\n }\n\n return err;\n }\n\n if (isEvent(value)) {\n /**\n * Event-like interface that's usable in browser and node\n */\n interface SimpleEvent {\n [key: string]: unknown;\n type: string;\n target?: unknown;\n currentTarget?: unknown;\n }\n\n const event = value as SimpleEvent;\n\n const source: {\n [key: string]: any;\n } = {};\n\n // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and\n // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a\n // try-catch in at least two years and no one's complained, so that's likely not an issue anymore\n source.type = event.type;\n\n try {\n source.target = isElement(event.target)\n ? htmlTreeAsString(event.target)\n : Object.prototype.toString.call(event.target);\n } catch (_oO) {\n source.target = '<unknown>';\n }\n\n try {\n source.currentTarget = isElement(event.currentTarget)\n ? htmlTreeAsString(event.currentTarget)\n : Object.prototype.toString.call(event.currentTarget);\n } catch (_oO) {\n source.currentTarget = '<unknown>';\n }\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n source.detail = event.detail;\n }\n\n for (const attr in event) {\n if (Object.prototype.hasOwnProperty.call(event, attr)) {\n source[attr] = event[attr];\n }\n }\n\n return source;\n }\n\n return value as {\n [key: string]: any;\n };\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value: string): number {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\nfunction jsonSize(value: any): number {\n return utf8Length(JSON.stringify(value));\n}\n\n/** JSDoc */\nexport function normalizeToSize<T>(\n object: { [key: string]: any },\n // Default Node.js REPL depth\n depth: number = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize: number = 100 * 1024,\n): T {\n const serialized = normalize(object, depth);\n\n if (jsonSize(serialized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return serialized as T;\n}\n\n/**\n * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers,\n * booleans, null, and undefined.\n *\n * @param value The value to stringify\n * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or\n * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value,\n * unchanged.\n */\nfunction serializeValue(value: any): any {\n const type = Object.prototype.toString.call(value);\n\n // Node.js REPL notation\n if (typeof value === 'string') {\n return value;\n }\n if (type === '[object Object]') {\n return '[Object]';\n }\n if (type === '[object Array]') {\n return '[Array]';\n }\n\n const normalized = normalizeValue(value);\n return isPrimitive(normalized) ? normalized : type;\n}\n\n/**\n * normalizeValue()\n *\n * Takes unserializable input and make it serializable friendly\n *\n * - translates undefined/NaN values to \"[undefined]\"/\"[NaN]\" respectively,\n * - serializes Error objects\n * - filter global objects\n */\nfunction normalizeValue<T>(value: T, key?: any): T | string {\n if (key === 'domain' && value && typeof value === 'object' && ((value as unknown) as { _events: any })._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n if (typeof (global as any) !== 'undefined' && (value as unknown) === global) {\n return '[Global]';\n }\n\n // It's safe to use `window` and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (window as any) !== 'undefined' && (value as unknown) === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof (document as any) !== 'undefined' && (value as unknown) === document) {\n return '[Document]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && value !== value) {\n return '[NaN]';\n }\n\n if (value === void 0) {\n return '[undefined]';\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n return value;\n}\n\n/**\n * Walks an object to perform a normalization on it\n *\n * @param key of object that's walked in current iteration\n * @param value object to be walked\n * @param depth Optional number indicating how deep should walking be performed\n * @param memo Optional Memo class handling decycling\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function walk(key: string, value: any, depth: number = +Infinity, memo: Memo = new Memo()): any {\n // If we reach the maximum depth, serialize whatever has left\n if (depth === 0) {\n return serializeValue(value);\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // If value implements `toJSON` method, call it and return early\n if (value !== null && value !== undefined && typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further\n const normalized = normalizeValue(value, key);\n if (isPrimitive(normalized)) {\n return normalized;\n }\n\n // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself\n const source = getWalkSource(value);\n\n // Create an accumulator that will act as a parent for all future itterations of that branch\n const acc = Array.isArray(value) ? [] : {};\n\n // If we already walked that branch, bail out, as it's circular reference\n if (memo.memoize(value)) {\n return '[Circular ~]';\n }\n\n // Walk all keys of the source\n for (const innerKey in source) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(source, innerKey)) {\n continue;\n }\n // Recursively walk through all the child nodes\n (acc as { [key: string]: any })[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);\n }\n\n // Once walked through all the branches, remove the parent from memo storage\n memo.unmemoize(value);\n\n // Return accumulated values\n return acc;\n}\n\n/**\n * normalize()\n *\n * - Creates a copy to prevent original input mutation\n * - Skip non-enumerablers\n * - Calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format\n * - Translates known global objects/Classes to a string representations\n * - Takes care of Error objects serialization\n * - Optionally limit depth of final output\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function normalize(input: any, depth?: number): any {\n try {\n return JSON.parse(JSON.stringify(input, (key: string, value: any) => walk(key, value, depth)));\n } catch (_oO) {\n return '**non-serializable**';\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function extractExceptionKeysForMessage(exception: any, maxLength: number = 40): string {\n const keys = Object.keys(getWalkSource(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return the new object with removed keys that value was `undefined`.\n * Works recursively on objects and arrays.\n */\nexport function dropUndefinedKeys<T>(val: T): T {\n if (isPlainObject(val)) {\n const obj = val as { [key: string]: any };\n const rv: { [key: string]: any } = {};\n for (const key of Object.keys(obj)) {\n if (typeof obj[key] !== 'undefined') {\n rv[key] = dropUndefinedKeys(obj[key]);\n }\n }\n return rv as T;\n }\n\n if (Array.isArray(val)) {\n return (val as any[]).map(dropUndefinedKeys) as any;\n }\n\n return val;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n", "import { getGlobalObject } from './global';\nimport { logger } from './logger';\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent(): boolean {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError(): boolean {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException(): boolean {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch(): boolean {\n if (!('fetch' in getGlobalObject<Window>())) {\n return false;\n }\n\n try {\n new Headers();\n new Request('');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func: Function): boolean {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch(): boolean {\n if (!supportsFetch()) {\n return false;\n }\n\n const global = getGlobalObject<Window>();\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(global.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = global.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement as unknown) === `function`) {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver(): boolean {\n return 'ReportingObserver' in getGlobalObject();\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy(): boolean {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default\n // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' as ReferrerPolicy,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory(): boolean {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n const global = getGlobalObject<Window>();\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (global as any).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/ban-types */\nimport { WrappedFunction } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { isInstanceOf, isString } from './is';\nimport { logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\n\nconst global = getGlobalObject<Window>();\n\n/** Object describing handler that will be triggered for a given `type` of instrumentation */\ninterface InstrumentHandler {\n type: InstrumentHandlerType;\n callback: InstrumentHandlerCallback;\n}\ntype InstrumentHandlerType =\n | 'console'\n | 'dom'\n | 'fetch'\n | 'history'\n | 'sentry'\n | 'xhr'\n | 'error'\n | 'unhandledrejection';\ntype InstrumentHandlerCallback = (data: any) => void;\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers: { [key in InstrumentHandlerType]?: InstrumentHandlerCallback[] } = {};\nconst instrumented: { [key in InstrumentHandlerType]?: boolean } = {};\n\n/** Instruments given API */\nfunction instrument(type: InstrumentHandlerType): void {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n logger.warn('unknown instrumentation type:', type);\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(handler: InstrumentHandler): void {\n if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {\n return;\n }\n handlers[handler.type] = handlers[handler.type] || [];\n (handlers[handler.type] as InstrumentHandlerCallback[]).push(handler.callback);\n instrument(handler.type);\n}\n\n/** JSDoc */\nfunction triggerHandlers(type: InstrumentHandlerType, data: any): void {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(\n handler,\n )}\\nError: ${e}`,\n );\n }\n }\n}\n\n/** JSDoc */\nfunction instrumentConsole(): void {\n if (!('console' in global)) {\n return;\n }\n\n ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function(level: string): void {\n if (!(level in global.console)) {\n return;\n }\n\n fill(global.console, level, function(originalConsoleLevel: () => any): Function {\n return function(...args: any[]): void {\n triggerHandlers('console', { args, level });\n\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, global.console, args);\n }\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch(): void {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(global, 'fetch', function(originalFetch: () => void): () => void {\n return function(...args: any[]): void {\n const handlerData = {\n args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(global, args).then(\n (response: Response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error: Error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\n });\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\ntype XHRSendInput = null | Blob | BufferSource | FormData | URLSearchParams | string;\n\n/** JSDoc */\ninterface SentryWrappedXMLHttpRequest extends XMLHttpRequest {\n [key: string]: any;\n __sentry_xhr__?: {\n method?: string;\n url?: string;\n status_code?: number;\n body?: XHRSendInput;\n };\n}\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs: any[] = []): string {\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs: any[] = []): string {\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n\n/** JSDoc */\nfunction instrumentXHR(): void {\n if (!('XMLHttpRequest' in global)) {\n return;\n }\n\n // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.\n const requestKeys: XMLHttpRequest[] = [];\n const requestValues: Array<any>[] = [];\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function(originalOpen: () => void): () => void {\n return function(this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const url = args[1];\n xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = function(): void {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n if (xhr.__sentry_xhr__) {\n xhr.__sentry_xhr__.status_code = xhr.status;\n }\n } catch (e) {\n /* do nothing */\n }\n\n try {\n const requestPos = requestKeys.indexOf(xhr);\n if (requestPos !== -1) {\n // Make sure to pop both key and value to keep it in sync.\n requestKeys.splice(requestPos);\n const args = requestValues.splice(requestPos)[0];\n if (xhr.__sentry_xhr__ && args[0] !== undefined) {\n xhr.__sentry_xhr__.body = args[0] as XHRSendInput;\n }\n }\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr,\n });\n }\n };\n\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function(original: WrappedFunction): Function {\n return function(...readyStateArgs: any[]): void {\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n } else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n return originalOpen.apply(xhr, args);\n };\n });\n\n fill(xhrproto, 'send', function(originalSend: () => void): () => void {\n return function(this: SentryWrappedXMLHttpRequest, ...args: any[]): void {\n requestKeys.push(this);\n requestValues.push(args);\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref: string;\n\n/** JSDoc */\nfunction instrumentHistory(): void {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = global.onpopstate;\n global.onpopstate = function(this: WindowEventHandlers, ...args: any[]): any {\n const to = global.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction: () => void): () => void {\n return function(this: History, ...args: any[]): void {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(global.history, 'pushState', historyReplacementFunction);\n fill(global.history, 'replaceState', historyReplacementFunction);\n}\n\nconst debounceDuration = 1000;\nlet debounceTimerID: number | undefined;\nlet lastCapturedEvent: Event | undefined;\n\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous: Event | undefined, current: Event): boolean {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event: Event): boolean {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n\n try {\n const target = event.target as HTMLElement;\n\n if (!target || !target.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler: Function, globalListener: boolean = false): (event: Event) => void {\n return (event: Event): void => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = global.setTimeout(() => {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n\ntype AddEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n) => void;\ntype RemoveEventListener = (\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n) => void;\n\ntype InstrumentedElement = Element & {\n __sentry_instrumentation_handlers__?: {\n [key in 'click' | 'keypress']?: {\n handler?: Function;\n /** The number of custom listeners attached to this element */\n refCount: number;\n };\n };\n};\n\n/** JSDoc */\nfunction instrumentDOM(): void {\n if (!('document' in global)) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n global.document.addEventListener('click', globalDOMEventHandler, false);\n global.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target: string) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (global as any)[target] && (global as any)[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function(originalAddEventListener: AddEventListener): AddEventListener {\n return function(\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): AddEventListener {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount += 1;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(proto, 'removeEventListener', function(originalRemoveEventListener: RemoveEventListener): RemoveEventListener {\n return function(\n this: Element,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ): () => void {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this as InstrumentedElement;\n const handlers = el.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount -= 1;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n });\n });\n}\n\nlet _oldOnErrorHandler: OnErrorEventHandler = null;\n/** JSDoc */\nfunction instrumentError(): void {\n _oldOnErrorHandler = global.onerror;\n\n global.onerror = function(msg: any, url: any, line: any, column: any, error: any): boolean {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n}\n\nlet _oldOnUnhandledRejectionHandler: ((e: any) => void) | null = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection(): void {\n _oldOnUnhandledRejectionHandler = global.onunhandledrejection;\n\n global.onunhandledrejection = function(e: any): boolean {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Event, Mechanism, StackFrame } from '@sentry/types';\n\nimport { getGlobalObject } from './global';\nimport { snipLine } from './string';\n\n/**\n * Extended Window interface that allows for Crypto API usage in IE browsers\n */\ninterface MsCryptoWindow extends Window {\n msCrypto?: Crypto;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const global = getGlobalObject() as MsCryptoWindow;\n const crypto = global.crypto || global.msCrypto;\n\n if (!(crypto === void 0) && crypto.getRandomValues) {\n // Use window.crypto API if available\n const arr = new Uint16Array(8);\n crypto.getRandomValues(arr);\n\n // set 4 in byte 7\n // eslint-disable-next-line no-bitwise\n arr[3] = (arr[3] & 0xfff) | 0x4000;\n // set 2 most significant bits of byte 9 to '10'\n // eslint-disable-next-line no-bitwise\n arr[4] = (arr[4] & 0x3fff) | 0x8000;\n\n const pad = (num: number): string => {\n let v = num.toString(16);\n while (v.length < 4) {\n v = `0${v}`;\n }\n return v;\n };\n\n return (\n pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])\n );\n }\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {\n // eslint-disable-next-line no-bitwise\n const r = (Math.random() * 16) | 0;\n // eslint-disable-next-line no-bitwise\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not <a/> href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(\n url: string,\n): {\n host?: string;\n path?: string;\n protocol?: string;\n relative?: string;\n} {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n if (event.message) {\n return event.message;\n }\n if (event.exception && event.exception.values && event.exception.values[0]) {\n const exception = event.exception.values[0];\n\n if (exception.type && exception.value) {\n return `${exception.type}: ${exception.value}`;\n }\n return exception.type || exception.value || event.event_id || '<unknown>';\n }\n return event.event_id || '<unknown>';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].value = event.exception.values[0].value || value || '';\n event.exception.values[0].type = event.exception.values[0].type || type || 'Error';\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial<Mechanism>): void {\n if (!event.exception || !event.exception.values) {\n return;\n }\n const exceptionValue0 = event.exception.values[0];\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = exceptionValue0.mechanism;\n exceptionValue0.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n exceptionValue0.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst 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-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\nconst defaultRetryAfter = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param now current unix timestamp\n * @param header string representation of 'Retry-After' header\n */\nexport function parseRetryAfterHeader(now: number, header?: string | number | null): number {\n if (!header) {\n return defaultRetryAfter;\n }\n\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return defaultRetryAfter;\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n const lineno = frame.lineno || 0;\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath: string): string {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if ((exception as any)?.__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n Object.defineProperty(exception, '__sentry_captured__', {\n value: true,\n });\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n", "// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js\n\n/** JSDoc */\nfunction normalizeArray(parts: string[], allowAboveRoot?: boolean): string[] {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n // eslint-disable-next-line no-plusplus\n up++;\n } else if (up) {\n parts.splice(i, 1);\n // eslint-disable-next-line no-plusplus\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n // eslint-disable-next-line no-plusplus\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^/]+?|)(\\.[^./]*|))(?:[/]*)$/;\n/** JSDoc */\nfunction splitPath(filename: string): string[] {\n const parts = splitPathRe.exec(filename);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nexport function resolve(...args: string[]): string {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr: string[]): string[] {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nexport function relative(from: string, to: string): string {\n /* eslint-disable no-param-reassign */\n from = resolve(from).substr(1);\n to = resolve(to).substr(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nexport function normalizePath(path: string): string {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.substr(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nexport function isAbsolute(path: string): boolean {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nexport function join(...args: string[]): string {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nexport function dirname(path: string): string {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nexport function basename(path: string, ext?: string): string {\n let f = splitPath(path)[2];\n if (ext && f.substr(ext.length * -1) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n}\n", "/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n\n/** SyncPromise internal states */\nconst enum States {\n /** Pending */\n PENDING = 'PENDING',\n /** Resolved / OK */\n RESOLVED = 'RESOLVED',\n /** Rejected / Error */\n REJECTED = 'REJECTED',\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise<T> implements PromiseLike<T> {\n private _state: States = States.PENDING;\n private _handlers: Array<{\n done: boolean;\n onfulfilled?: ((value: T) => T | PromiseLike<T>) | null;\n onrejected?: ((reason: any) => any) | null;\n }> = [];\n private _value: any;\n\n public constructor(\n executor: (resolve: (value?: T | PromiseLike<T> | null) => void, reject: (reason?: any) => void) => void,\n ) {\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\n public static resolve<T>(value: T | PromiseLike<T>): PromiseLike<T> {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n }\n\n /** JSDoc */\n public static reject<T = never>(reason?: any): PromiseLike<T> {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n }\n\n /** JSDoc */\n public static all<U = any>(collection: Array<U | PromiseLike<U>>): PromiseLike<U[]> {\n return new SyncPromise<U[]>((resolve, reject) => {\n if (!Array.isArray(collection)) {\n reject(new TypeError(`Promise.all requires an array as input.`));\n return;\n }\n\n if (collection.length === 0) {\n resolve([]);\n return;\n }\n\n let counter = collection.length;\n const resolvedCollection: U[] = [];\n\n collection.forEach((item, index) => {\n void SyncPromise.resolve(item)\n .then(value => {\n resolvedCollection[index] = value;\n counter -= 1;\n\n if (counter !== 0) {\n return;\n }\n resolve(resolvedCollection);\n })\n .then(null, reject);\n });\n });\n }\n\n /** JSDoc */\n public then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): PromiseLike<TResult1 | TResult2> {\n return new SyncPromise((resolve, reject) => {\n this._attachHandler({\n done: false,\n onfulfilled: result => {\n if (!onfulfilled) {\n // TODO: \u00AF\\_(\u30C4)_/\u00AF\n // TODO: FIXME\n resolve(result as any);\n return;\n }\n try {\n resolve(onfulfilled(result));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n onrejected: reason => {\n if (!onrejected) {\n reject(reason);\n return;\n }\n try {\n resolve(onrejected(reason));\n return;\n } catch (e) {\n reject(e);\n return;\n }\n },\n });\n });\n }\n\n /** JSDoc */\n public catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): PromiseLike<T | TResult> {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\n public finally<TResult>(onfinally?: (() => void) | null): PromiseLike<TResult> {\n return new SyncPromise<TResult>((resolve, reject) => {\n let val: TResult | any;\n let isRejected: boolean;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve((val as unknown) as any);\n });\n });\n }\n\n /** JSDoc */\n public toString(): string {\n return '[object SyncPromise]';\n }\n\n /** JSDoc */\n private readonly _resolve = (value?: T | PromiseLike<T> | null) => {\n this._setResult(States.RESOLVED, value);\n };\n\n /** JSDoc */\n private readonly _reject = (reason?: any) => {\n this._setResult(States.REJECTED, reason);\n };\n\n /** JSDoc */\n private readonly _setResult = (state: States, value?: T | PromiseLike<T> | any) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value as PromiseLike<T>).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n // TODO: FIXME\n /** JSDoc */\n private readonly _attachHandler = (handler: {\n /** JSDoc */\n done: boolean;\n /** JSDoc */\n onfulfilled?(value: T): any;\n /** JSDoc */\n onrejected?(reason: any): any;\n }) => {\n this._handlers = this._handlers.concat(handler);\n this._executeHandlers();\n };\n\n /** JSDoc */\n private readonly _executeHandlers = () => {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler.done) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n if (handler.onfulfilled) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler.onfulfilled((this._value as unknown) as any);\n }\n }\n\n if (this._state === States.REJECTED) {\n if (handler.onrejected) {\n handler.onrejected(this._value);\n }\n }\n\n handler.done = true;\n });\n };\n}\n\nexport { SyncPromise };\n", "import { SentryError } from './error';\nimport { SyncPromise } from './syncpromise';\n\n/** A simple queue that holds promises. */\nexport class PromiseBuffer<T> {\n /** Internal set of queued Promises */\n private readonly _buffer: Array<PromiseLike<T>> = [];\n\n public constructor(protected _limit?: number) {}\n\n /**\n * Says if the buffer is ready to take more requests\n */\n public isReady(): boolean {\n return this._limit === undefined || this.length() < this._limit;\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:\n * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n public add(taskProducer: () => PromiseLike<T>): PromiseLike<T> {\n if (!this.isReady()) {\n return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (this._buffer.indexOf(task) === -1) {\n this._buffer.push(task);\n }\n void task\n .then(() => this.remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n this.remove(task).then(null, () => {\n // We have to add another catch here because `this.remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike<T>\n * @returns Removed promise.\n */\n public remove(task: PromiseLike<T>): PromiseLike<T> {\n const removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0];\n return removedTask;\n }\n\n /**\n * This function returns the number of unresolved promises in the queue.\n */\n public length(): number {\n return this._buffer.length;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise<boolean>(resolve => {\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n void SyncPromise.all(this._buffer)\n .then(() => {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n })\n .then(null, () => {\n resolve(true);\n });\n });\n }\n}\n", "import { getGlobalObject } from './global';\nimport { dynamicRequire, isNodeEnv } from './node';\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\ninterface TimestampSource {\n nowSeconds(): number;\n}\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource: TimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance(): Performance | undefined {\n const { performance } = getGlobalObject<Window>();\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance(): Performance | undefined {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') as { performance: Performance };\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance: Performance | undefined = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource: TimestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport const dateTimestampInSeconds: () => number = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds: () => number = timestampSource.nowSeconds.bind(timestampSource);\n\n// Re-exported with an old name for backwards-compatibility.\nexport const timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport const usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = getGlobalObject<Window>();\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n", "export * from './async';\nexport * from './browser';\nexport * from './dsn';\nexport * from './error';\nexport * from './global';\nexport * from './instrument';\nexport * from './is';\nexport * from './logger';\nexport * from './memo';\nexport * from './misc';\nexport * from './node';\nexport * from './object';\nexport * from './path';\nexport * from './promisebuffer';\nexport * from './stacktrace';\nexport * from './string';\nexport * from './supports';\nexport * from './syncpromise';\nexport * from './time';\n", "/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n CaptureContext,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n Severity,\n Span,\n Transaction,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, getGlobalObject, isPlainObject, isThenable, SyncPromise } from '@sentry/utils';\n\nimport { Session } from './session';\n\n/**\n * Absolute maximum number of breadcrumbs added to an event.\n * The `maxBreadcrumbs` option cannot be higher than this value.\n */\nconst MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nexport class Scope implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean = false;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void> = [];\n\n /** Callback list that will be called after {@link applyToEvent}. */\n protected _eventProcessors: EventProcessor[] = [];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[] = [];\n\n /** User */\n protected _user: User = {};\n\n /** Tags */\n protected _tags: { [key: string]: Primitive } = {};\n\n /** Extra */\n protected _extra: Extras = {};\n\n /** Contexts */\n protected _contexts: Contexts = {};\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: Severity;\n\n /** Transaction Name */\n protected _transactionName?: string;\n\n /** Span */\n protected _span?: Span;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n public static clone(scope?: Scope): Scope {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n this._user = user || {};\n if (this._session) {\n this._session.update({ user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(level: Severity): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Can be removed in major version.\n * @deprecated in favor of {@link this.setTransactionName}\n */\n public setTransaction(name?: string): this {\n return this.setTransactionName(name);\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts = { ...this._contexts, [key]: context };\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSpan(span?: Span): this {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSpan(): Span | undefined {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n public getTransaction(): Transaction | undefined {\n // often, this span will be a transaction, but it's not guaranteed to be\n const span = this.getSpan() as undefined | (Span & { spanRecorder: { spans: Span[] } });\n\n // try it the new way first\n if (span?.transaction) {\n return span?.transaction;\n }\n\n // fallback to the old way (known bug: this only finds transactions with sampled = true)\n if (span?.spanRecorder?.spans[0]) {\n return span.spanRecorder.spans[0] as Transaction;\n }\n\n // neither way found a transaction\n return undefined;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext as <T>(scope: T) => T)(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext as ScopeContext;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs);\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Applies the current context and fingerprint to the event.\n * Note that breadcrumbs will be added by the client.\n * Also if the event has already breadcrumbs on it, we do not merge them.\n * @param event Event\n * @param hint May contain additional information about the original exception.\n * @hidden\n */\n public applyToEvent(event: Event, hint?: EventHint): PromiseLike<Event | null> {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transactionName = this._span.transaction?.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n\n this._applyFingerprint(event);\n\n event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs];\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n\n return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint);\n }\n\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n protected _notifyEventProcessors(\n processors: EventProcessor[],\n event: Event | null,\n hint?: EventHint,\n index: number = 0,\n ): PromiseLike<Event | null> {\n return new SyncPromise<Event | null>((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) as Event | null;\n if (isThenable(result)) {\n void (result as PromiseLike<Event | null>)\n .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n private _applyFingerprint(event: Event): void {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors(): EventProcessor[] {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n const global = getGlobalObject<any>();\n global.__SENTRY__ = global.__SENTRY__ || {};\n global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || [];\n return global.__SENTRY__.globalEventProcessors;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback: EventProcessor): void {\n getGlobalEventProcessors().push(callback);\n}\n", "import { Session as SessionInterface, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n\n/**\n * @inheritdoc\n */\nexport class Session implements SessionInterface {\n public userAgent?: string;\n public errors: number = 0;\n public release?: string;\n public sid: string = uuid4();\n public did?: string;\n public timestamp: number;\n public started: number;\n public duration?: number = 0;\n public status: SessionStatus = SessionStatus.Ok;\n public environment?: string;\n public ipAddress?: string;\n public init: boolean = true;\n public ignoreDuration: boolean = false;\n\n public constructor(context?: Omit<SessionContext, 'started' | 'status'>) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n this.timestamp = startingTime;\n this.started = startingTime;\n if (context) {\n this.update(context);\n }\n }\n\n /** JSDoc */\n // eslint-disable-next-line complexity\n public update(context: SessionContext = {}): void {\n if (context.user) {\n if (!this.ipAddress && context.user.ip_address) {\n this.ipAddress = context.user.ip_address;\n }\n\n if (!this.did && !context.did) {\n this.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n this.timestamp = context.timestamp || timestampInSeconds();\n if (context.ignoreDuration) {\n this.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. \u2014 Kamil\n this.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n this.init = context.init;\n }\n if (!this.did && context.did) {\n this.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n this.started = context.started;\n }\n if (this.ignoreDuration) {\n this.duration = undefined;\n } else if (typeof context.duration === 'number') {\n this.duration = context.duration;\n } else {\n const duration = this.timestamp - this.started;\n this.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n this.release = context.release;\n }\n if (context.environment) {\n this.environment = context.environment;\n }\n if (!this.ipAddress && context.ipAddress) {\n this.ipAddress = context.ipAddress;\n }\n if (!this.userAgent && context.userAgent) {\n this.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n this.errors = context.errors;\n }\n if (context.status) {\n this.status = context.status;\n }\n }\n\n /** JSDoc */\n public close(status?: Exclude<SessionStatus, SessionStatus.Ok>): void {\n if (status) {\n this.update({ status });\n } else if (this.status === SessionStatus.Ok) {\n this.update({ status: SessionStatus.Exited });\n } else {\n this.update();\n }\n }\n\n /** JSDoc */\n public toJSON(): {\n init: boolean;\n sid: string;\n did?: string;\n timestamp: string;\n started: string;\n duration?: number;\n status: SessionStatus;\n errors: number;\n attrs?: {\n release?: string;\n environment?: string;\n user_agent?: string;\n ip_address?: string;\n };\n } {\n return dropUndefinedKeys({\n sid: `${this.sid}`,\n init: this.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(this.started * 1000).toISOString(),\n timestamp: new Date(this.timestamp * 1000).toISOString(),\n status: this.status,\n errors: this.errors,\n did: typeof this.did === 'number' || typeof this.did === 'string' ? `${this.did}` : undefined,\n duration: this.duration,\n attrs: dropUndefinedKeys({\n release: this.release,\n environment: this.environment,\n ip_address: this.ipAddress,\n user_agent: this.userAgent,\n }),\n });\n }\n}\n", "/* eslint-disable max-lines */\nimport {\n Breadcrumb,\n BreadcrumbHint,\n Client,\n CustomSamplingContext,\n Event,\n EventHint,\n Extra,\n Extras,\n Hub as HubInterface,\n Integration,\n IntegrationClass,\n Primitive,\n SessionContext,\n SessionStatus,\n Severity,\n Span,\n SpanContext,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils';\n\nimport { Scope } from './scope';\nimport { Session } from './session';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport const API_VERSION = 4;\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * A layer in the process stack.\n * @hidden\n */\nexport interface Layer {\n client?: Client;\n scope?: Scope;\n}\n\n/**\n * An object that contains a hub and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: {\n hub?: Hub;\n /**\n * Extra Hub properties injected by various SDKs\n */\n integrations?: Integration[];\n extensions?: {\n /** Hack to prevent bundlers from breaking our usage of the domain package in the cross-platform Hub package */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n domain?: { [key: string]: any };\n } & {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n };\n}\n\n/**\n * @hidden\n * @deprecated Can be removed once `Hub.getActiveDomain` is removed.\n */\nexport interface DomainAsCarrier extends Carrier {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: { [key: string]: any }[];\n}\n\n/**\n * @inheritDoc\n */\nexport class Hub implements HubInterface {\n /** Is a {@link Layer}[] containing the client and scope */\n private readonly _stack: Layer[] = [{}];\n\n /** Contains the last event id of a captured event. */\n private _lastEventId?: string;\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n public constructor(client?: Client, scope: Scope = new Scope(), private readonly _version: number = API_VERSION) {\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n public isOlderThan(version: number): boolean {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n public bindClient(client?: Client): void {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n public pushScope(): Scope {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n public popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n public withScope(callback: (scope: Scope) => void): void {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n public getClient<C extends Client>(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /** Returns the scope of the top stack. */\n public getScope(): Scope | undefined {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint): string {\n const eventId = (this._lastEventId = uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: exception,\n syntheticException,\n };\n }\n\n this._invokeClient('captureException', exception, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint): string {\n const eventId = (this._lastEventId = uuid4());\n let finalHint = hint;\n\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n finalHint = {\n originalException: message,\n syntheticException,\n };\n }\n\n this._invokeClient('captureMessage', message, level, {\n ...finalHint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = uuid4();\n if (event.type !== 'transaction') {\n this._lastEventId = eventId;\n }\n\n this._invokeClient('captureEvent', event, {\n ...hint,\n event_id: eventId,\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n const { scope, client } = this.getStackTop();\n\n if (!scope || !client) return;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && client.getOptions()) || {};\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) as Breadcrumb | null)\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): void {\n const scope = this.getScope();\n if (scope) scope.setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): void {\n const scope = this.getScope();\n if (scope) scope.setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): void {\n const scope = this.getScope();\n if (scope) scope.setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): void {\n const scope = this.getScope();\n if (scope) scope.setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): void {\n const scope = this.getScope();\n if (scope) scope.setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public setContext(name: string, context: { [key: string]: any } | null): void {\n const scope = this.getScope();\n if (scope) scope.setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n public configureScope(callback: (scope: Scope) => void): void {\n const { scope, client } = this.getStackTop();\n if (scope && client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n public run(callback: (hub: Hub) => void): void {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n public startSpan(context: SpanContext): Span {\n return this._callExtensionMethod('startSpan', context);\n }\n\n /**\n * @inheritDoc\n */\n public startTransaction(context: TransactionContext, customSamplingContext?: CustomSamplingContext): Transaction {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n }\n\n /**\n * @inheritDoc\n */\n public traceHeaders(): { [key: string]: string } {\n return this._callExtensionMethod<{ [key: string]: string }>('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(endSession: boolean = false): void {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n public endSession(): void {\n this.getStackTop()\n ?.scope?.getSession()\n ?.close();\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n this.getStackTop()?.scope?.setSession();\n }\n\n /**\n * @inheritDoc\n */\n public startSession(context?: SessionContext): Session {\n const { scope, client } = this.getStackTop();\n const { release, environment } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const global = getGlobalObject<{ navigator?: { userAgent?: string } }>();\n const { userAgent } = global.navigator || {};\n\n const session = new Session({\n release,\n environment,\n ...(scope && { user: scope.getUser() }),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n if (scope) {\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === SessionStatus.Ok) {\n currentSession.update({ status: SessionStatus.Exited });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n\n return session;\n }\n\n /**\n * Sends the current Session on the scope\n */\n private _sendSessionUpdate(): void {\n const { scope, client } = this.getStackTop();\n if (!scope) return;\n\n const session = scope.getSession && scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _invokeClient<M extends keyof Client>(method: M, ...args: any[]): void {\n const { scope, client } = this.getStackTop();\n if (client && client[method]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (client as any)[method](...args, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _callExtensionMethod<T>(method: string, ...args: any[]): T {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n const carrier = getGlobalObject();\n carrier.__SENTRY__ = carrier.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return carrier;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub: Hub): Hub {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub(): Hub {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * Returns the active domain, if one exists\n * @deprecated No longer used; remove in v7\n * @returns The domain, or undefined if there is no active domain\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveDomain(): DomainAsCarrier | undefined {\n logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');\n\n const sentry = getMainCarrier().__SENTRY__;\n\n return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n}\n\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry: Carrier): Hub {\n try {\n const activeDomain = getMainCarrier().__SENTRY__?.extensions?.domain?.active;\n\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n const registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n } catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier: Carrier): boolean {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier: Carrier): Hub {\n if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) return carrier.__SENTRY__.hub;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = new Hub();\n return carrier.__SENTRY__.hub;\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier: Carrier, hub: Hub): boolean {\n if (!carrier) return false;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = hub;\n return true;\n}\n", "import {\n AggregationCounts,\n RequestSessionStatus,\n SessionAggregates,\n SessionFlusherLike,\n Transport,\n} from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\n\nimport { getCurrentHub } from './hub';\n\ntype ReleaseHealthAttributes = {\n environment?: string;\n release: string;\n};\n\n/**\n * @inheritdoc\n */\nexport class SessionFlusher implements SessionFlusherLike {\n public readonly flushTimeout: number = 60;\n private _pendingAggregates: Record<number, AggregationCounts> = {};\n private _sessionAttrs: ReleaseHealthAttributes;\n private _intervalId: ReturnType<typeof setInterval>;\n private _isEnabled: boolean = true;\n private _transport: Transport;\n\n public constructor(transport: Transport, attrs: ReleaseHealthAttributes) {\n this._transport = transport;\n // Call to setInterval, so that flush is called every 60 seconds\n this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000);\n this._sessionAttrs = attrs;\n }\n\n /** Sends session aggregates to Transport */\n public sendSessionAggregates(sessionAggregates: SessionAggregates): void {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n void this._transport.sendSession(sessionAggregates).then(null, reason => {\n logger.error(`Error while sending session: ${reason}`);\n });\n }\n\n /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */\n public flush(): void {\n const sessionAggregates = this.getSessionAggregates();\n if (sessionAggregates.aggregates.length === 0) {\n return;\n }\n this._pendingAggregates = {};\n this.sendSessionAggregates(sessionAggregates);\n }\n\n /** Massages the entries in `pendingAggregates` and returns aggregated sessions */\n public getSessionAggregates(): SessionAggregates {\n const aggregates: AggregationCounts[] = Object.keys(this._pendingAggregates).map((key: string) => {\n return this._pendingAggregates[parseInt(key)];\n });\n\n const sessionAggregates: SessionAggregates = {\n attrs: this._sessionAttrs,\n aggregates,\n };\n return dropUndefinedKeys(sessionAggregates);\n }\n\n /** JSDoc */\n public close(): void {\n clearInterval(this._intervalId);\n this._isEnabled = false;\n this.flush();\n }\n\n /**\n * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then\n * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to\n * `_incrementSessionStatusCount` along with the start date\n */\n public incrementSessionStatusCount(): void {\n if (!this._isEnabled) {\n return;\n }\n const scope = getCurrentHub().getScope();\n const requestSession = scope?.getRequestSession();\n\n if (requestSession && requestSession.status) {\n this._incrementSessionStatusCount(requestSession.status, new Date());\n // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in\n // case captureRequestSession is called more than once to prevent double count\n scope?.setRequestSession(undefined);\n\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n }\n }\n\n /**\n * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of\n * the session received\n */\n private _incrementSessionStatusCount(status: RequestSessionStatus, date: Date): number {\n // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys\n const sessionStartedTrunc = new Date(date).setSeconds(0, 0);\n this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {};\n\n // corresponds to aggregated sessions in one specific minute bucket\n // for example, {\"started\":\"2021-03-16T08:00:00.000Z\",\"exited\":4, \"errored\": 1}\n const aggregationCounts: AggregationCounts = this._pendingAggregates[sessionStartedTrunc];\n if (!aggregationCounts.started) {\n aggregationCounts.started = new Date(sessionStartedTrunc).toISOString();\n }\n\n switch (status) {\n case RequestSessionStatus.Errored:\n aggregationCounts.errored = (aggregationCounts.errored || 0) + 1;\n return aggregationCounts.errored;\n case RequestSessionStatus.Ok:\n aggregationCounts.exited = (aggregationCounts.exited || 0) + 1;\n return aggregationCounts.exited;\n case RequestSessionStatus.Crashed:\n aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1;\n return aggregationCounts.crashed;\n }\n }\n}\n", "export { addGlobalEventProcessor, Scope } from './scope';\nexport { Session } from './session';\nexport { SessionFlusher } from './sessionflusher';\nexport {\n // eslint-disable-next-line deprecation/deprecation\n getActiveDomain,\n getCurrentHub,\n getHubFromCarrier,\n getMainCarrier,\n Hub,\n makeMain,\n setHubOnCarrier,\n Carrier,\n // eslint-disable-next-line deprecation/deprecation\n DomainAsCarrier,\n Layer,\n} from './hub';\n", "import { getCurrentHub, Hub, Scope } from '@sentry/hub';\nimport {\n Breadcrumb,\n CaptureContext,\n CustomSamplingContext,\n Event,\n Extra,\n Extras,\n Primitive,\n Severity,\n Transaction,\n TransactionContext,\n User,\n} from '@sentry/types';\n\n/**\n * This calls a function on the current hub.\n * @param method function to call on hub.\n * @param args to pass to function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction callOnHub<T>(method: string, ...args: any[]): T {\n const hub = getCurrentHub();\n if (hub && hub[method as keyof Hub]) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (hub[method as keyof Hub] as any)(...args);\n }\n throw new Error(`No hub defined or ${method} was not found on the hub, please open a bug report.`);\n}\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function captureException(exception: any, captureContext?: CaptureContext): string {\n let syntheticException: Error;\n try {\n throw new Error('Sentry syntheticException');\n } catch (exception) {\n syntheticException = exception as Error;\n }\n return callOnHub('captureException', exception, {\n captureContext,\n originalException: exception,\n syntheticException,\n });\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param level Define the level of the message.\n * @returns The generated eventId.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | Severity): string {\n let syntheticException: Error;\n try {\n throw new Error(message);\n } catch (exception) {\n syntheticException = exception as Error;\n }\n\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n\n return callOnHub('captureMessage', message, level, {\n originalException: message,\n syntheticException,\n ...context,\n });\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @returns The generated eventId.\n */\nexport function captureEvent(event: Event): string {\n return callOnHub('captureEvent', event);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nexport function configureScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('configureScope', callback);\n}\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n *\n * @param breadcrumb The breadcrumb to record.\n */\nexport function addBreadcrumb(breadcrumb: Breadcrumb): void {\n callOnHub<void>('addBreadcrumb', breadcrumb);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): void {\n callOnHub<void>('setContext', name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): void {\n callOnHub<void>('setExtras', extras);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n callOnHub<void>('setTags', tags);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): void {\n callOnHub<void>('setExtra', key, extra);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): void {\n callOnHub<void>('setTag', key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): void {\n callOnHub<void>('setUser', user);\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n *\n * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nexport function withScope(callback: (scope: Scope) => void): void {\n callOnHub<void>('withScope', callback);\n}\n\n/**\n * Calls a function on the latest client. Use this with caution, it's meant as\n * in \"internal\" helper so we don't need to expose every possible function in\n * the shim. It is not guaranteed that the client actually implements the\n * function.\n *\n * @param method The method to call on the client/client.\n * @param args Arguments to pass to the client/fontend.\n * @hidden\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _callOnClient(method: string, ...args: any[]): void {\n callOnHub<void>('_invokeClient', method, ...args);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nexport function startTransaction(\n context: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n return callOnHub('startTransaction', { ...context }, customSamplingContext);\n}\n", "import { DsnLike, SdkMetadata } from '@sentry/types';\nimport { Dsn, urlEncode } from '@sentry/utils';\n\nconst SENTRY_API_VERSION = '7';\n\n/**\n * Helper class to provide urls, headers and metadata that can be used to form\n * different types of requests to Sentry endpoints.\n * Supports both envelopes and regular event requests.\n **/\nexport class API {\n /** The DSN as passed to Sentry.init() */\n public dsn: DsnLike;\n\n /** Metadata about the SDK (name, version, etc) for inclusion in envelope headers */\n public metadata: SdkMetadata;\n\n /** The internally used Dsn object. */\n private readonly _dsnObject: Dsn;\n\n /** The envelope tunnel to use. */\n private readonly _tunnel?: string;\n\n /** Create a new instance of API */\n public constructor(dsn: DsnLike, metadata: SdkMetadata = {}, tunnel?: string) {\n this.dsn = dsn;\n this._dsnObject = new Dsn(dsn);\n this.metadata = metadata;\n this._tunnel = tunnel;\n }\n\n /** Returns the Dsn object. */\n public getDsn(): Dsn {\n return this._dsnObject;\n }\n\n /** Does this transport force envelopes? */\n public forceEnvelope(): boolean {\n return !!this._tunnel;\n }\n\n /** Returns the prefix to construct Sentry ingestion API endpoints. */\n public getBaseApiEndpoint(): string {\n const dsn = this.getDsn();\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n }\n\n /** Returns the store endpoint URL. */\n public getStoreEndpoint(): string {\n return this._getIngestEndpoint('store');\n }\n\n /**\n * Returns the store endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getStoreEndpointWithUrlEncodedAuth(): string {\n return `${this.getStoreEndpoint()}?${this._encodedAuth()}`;\n }\n\n /**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\n public getEnvelopeEndpointWithUrlEncodedAuth(): string {\n if (this.forceEnvelope()) {\n return this._tunnel as string;\n }\n\n return `${this._getEnvelopeEndpoint()}?${this._encodedAuth()}`;\n }\n\n /** Returns only the path component for the store endpoint. */\n public getStoreEndpointPath(): string {\n const dsn = this.getDsn();\n return `${dsn.path ? `/${dsn.path}` : ''}/api/${dsn.projectId}/store/`;\n }\n\n /**\n * Returns an object that can be used in request headers.\n * This is needed for node and the old /store endpoint in sentry\n */\n public getRequestHeaders(clientName: string, clientVersion: string): { [key: string]: string } {\n // CHANGE THIS to use metadata but keep clientName and clientVersion compatible\n const dsn = this.getDsn();\n const header = [`Sentry sentry_version=${SENTRY_API_VERSION}`];\n header.push(`sentry_client=${clientName}/${clientVersion}`);\n header.push(`sentry_key=${dsn.publicKey}`);\n if (dsn.pass) {\n header.push(`sentry_secret=${dsn.pass}`);\n }\n return {\n 'Content-Type': 'application/json',\n 'X-Sentry-Auth': header.join(', '),\n };\n }\n\n /** Returns the url to the report dialog endpoint. */\n public getReportDialogEndpoint(\n dialogOptions: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n user?: { name?: string; email?: string };\n } = {},\n ): string {\n const dsn = this.getDsn();\n const endpoint = `${this.getBaseApiEndpoint()}embed/error-page/`;\n\n const encodedOptions = [];\n encodedOptions.push(`dsn=${dsn.toString()}`);\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'user') {\n if (!dialogOptions.user) {\n continue;\n }\n if (dialogOptions.user.name) {\n encodedOptions.push(`name=${encodeURIComponent(dialogOptions.user.name)}`);\n }\n if (dialogOptions.user.email) {\n encodedOptions.push(`email=${encodeURIComponent(dialogOptions.user.email)}`);\n }\n } else {\n encodedOptions.push(`${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] as string)}`);\n }\n }\n if (encodedOptions.length) {\n return `${endpoint}?${encodedOptions.join('&')}`;\n }\n\n return endpoint;\n }\n\n /** Returns the envelope endpoint URL. */\n private _getEnvelopeEndpoint(): string {\n return this._getIngestEndpoint('envelope');\n }\n\n /** Returns the ingest API endpoint for target. */\n private _getIngestEndpoint(target: 'store' | 'envelope'): string {\n if (this._tunnel) {\n return this._tunnel;\n }\n const base = this.getBaseApiEndpoint();\n const dsn = this.getDsn();\n return `${base}${dsn.projectId}/${target}/`;\n }\n\n /** Returns a URL-encoded string with auth config suitable for a query string. */\n private _encodedAuth(): string {\n const dsn = this.getDsn();\n const auth = {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n };\n return urlEncode(auth);\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Integration, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nexport const installedIntegrations: string[] = [];\n\n/** Map of integrations assigned to a client */\nexport type IntegrationIndex = {\n [key: string]: Integration;\n} & { initialized?: boolean };\n\n/**\n * @private\n */\nfunction filterDuplicates(integrations: Integration[]): Integration[] {\n return integrations.reduce((acc, integrations) => {\n if (acc.every(accIntegration => integrations.name !== accIntegration.name)) {\n acc.push(integrations);\n }\n return acc;\n }, [] as Integration[]);\n}\n\n/** Gets integration to install */\nexport function getIntegrationsToSetup(options: Options): Integration[] {\n const defaultIntegrations = (options.defaultIntegrations && [...options.defaultIntegrations]) || [];\n const userIntegrations = options.integrations;\n\n let integrations: Integration[] = [...filterDuplicates(defaultIntegrations)];\n\n if (Array.isArray(userIntegrations)) {\n // Filter out integrations that are also included in user options\n integrations = [\n ...integrations.filter(integrations =>\n userIntegrations.every(userIntegration => userIntegration.name !== integrations.name),\n ),\n // And filter out duplicated user options integrations\n ...filterDuplicates(userIntegrations),\n ];\n } else if (typeof userIntegrations === 'function') {\n integrations = userIntegrations(integrations);\n integrations = Array.isArray(integrations) ? integrations : [integrations];\n }\n\n // Make sure that if present, `Debug` integration will always run last\n const integrationsNames = integrations.map(i => i.name);\n const alwaysLastToRun = 'Debug';\n if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {\n integrations.push(...integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1));\n }\n\n return integrations;\n}\n\n/** Setup given integration */\nexport function setupIntegration(integration: Integration): void {\n if (installedIntegrations.indexOf(integration.name) !== -1) {\n return;\n }\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n logger.log(`Integration installed: ${integration.name}`);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nexport function setupIntegrations<O extends Options>(options: O): IntegrationIndex {\n const integrations: IntegrationIndex = {};\n getIntegrationsToSetup(options).forEach(integration => {\n integrations[integration.name] = integration;\n setupIntegration(integration);\n });\n // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty`\n // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be\n // considered a member of the index the way the actual integrations are\n Object.defineProperty(integrations, 'initialized', { value: true });\n return integrations;\n}\n", "/* eslint-disable max-lines */\nimport { Scope, Session } from '@sentry/hub';\nimport {\n Client,\n Event,\n EventHint,\n Integration,\n IntegrationClass,\n Options,\n Outcome,\n SessionStatus,\n Severity,\n Transport,\n} from '@sentry/types';\nimport {\n checkOrSetAlreadyCaught,\n dateTimestampInSeconds,\n Dsn,\n isPlainObject,\n isPrimitive,\n isThenable,\n logger,\n normalize,\n SentryError,\n SyncPromise,\n truncate,\n uuid4,\n} from '@sentry/utils';\n\nimport { Backend, BackendClass } from './basebackend';\nimport { IntegrationIndex, setupIntegrations } from './integration';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding backend constructor and options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}. Also, the Backend instance is available via\n * {@link Client.getBackend}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event via the backend, it is passed through\n * {@link BaseClient._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends BaseClient<NodeBackend, NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(NodeBackend, options);\n * }\n *\n * // ...\n * }\n */\nexport abstract class BaseClient<B extends Backend, O extends Options> implements Client<O> {\n /**\n * The backend used to physically interact in the environment. Usually, this\n * will correspond to the client. When composing SDKs, however, the Backend\n * from the root SDK will be used.\n */\n protected readonly _backend: B;\n\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n protected readonly _dsn?: Dsn;\n\n /** Array of used integrations. */\n protected _integrations: IntegrationIndex = {};\n\n /** Number of calls being processed */\n protected _numProcessing: number = 0;\n\n /**\n * Initializes this client instance.\n *\n * @param backendClass A constructor function to create the backend.\n * @param options Options for the client.\n */\n protected constructor(backendClass: BackendClass<B, O>, options: O) {\n this._backend = new backendClass(options);\n this._options = options;\n\n if (options.dsn) {\n this._dsn = new Dsn(options.dsn);\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._getBackend()\n .eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: Severity, hint?: EventHint, scope?: Scope): string | undefined {\n let eventId: string | undefined = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this._getBackend().eventFromMessage(String(message), level, hint)\n : this._getBackend().eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId: string | undefined = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureSession(session: Session): void {\n if (!this._isEnabled()) {\n logger.warn('SDK not enabled, will not capture session.');\n return;\n }\n\n if (!(typeof session.release === 'string')) {\n logger.warn('Discarded session because of missing or non-string release');\n } else {\n this._sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n session.update({ init: false });\n }\n }\n\n /**\n * @inheritDoc\n */\n public getDsn(): Dsn | undefined {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n public getOptions(): O {\n return this._options;\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._getBackend().getTransport();\n }\n\n /**\n * @inheritDoc\n */\n public flush(timeout?: number): PromiseLike<boolean> {\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return this.getTransport()\n .close(timeout)\n .then(transportFlushed => clientFinished && transportFlushed);\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /**\n * Sets up the integrations\n */\n public setupIntegrations(): void {\n if (this._isEnabled() && !this._integrations.initialized) {\n this._integrations = setupIntegrations(this._options);\n }\n }\n\n /**\n * @inheritDoc\n */\n public getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null {\n try {\n return (this._integrations[integration.id] as T) || null;\n } catch (_oO) {\n logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /** Updates existing session based on the provided event */\n protected _updateSessionFromEvent(session: Session, event: Event): void {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && event.exception.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism && mechanism.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === SessionStatus.Ok;\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n session.update({\n ...(crashed && { status: SessionStatus.Crashed }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /** Deliver captured session to Sentry */\n protected _sendSession(session: Session): void {\n this._getBackend().sendSession(session);\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n protected _isClientDoneProcessing(timeout?: number): PromiseLike<boolean> {\n return new SyncPromise(resolve => {\n let ticked: number = 0;\n const tick: number = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Returns the current backend. */\n protected _getBackend(): B {\n return this._backend;\n }\n\n /** Determines whether this SDK is enabled and a valid Dsn is present. */\n protected _isEnabled(): boolean {\n return this.getOptions().enabled !== false && this._dsn !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n const { normalizeDepth = 3 } = this.getOptions();\n const prepared: Event = {\n ...event,\n event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n\n this._applyClientOptions(prepared);\n this._applyIntegrationsMetadata(prepared);\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n let finalScope = scope;\n if (hint && hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = SyncPromise.resolve<Event | null>(prepared);\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n if (finalScope) {\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint);\n }\n\n return result.then(evt => {\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return this._normalizeEvent(evt, normalizeDepth);\n }\n return evt;\n });\n }\n\n /**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\n protected _normalizeEvent(event: Event | null, depth: number): Event | null {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth),\n }),\n };\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts && event.contexts.trace) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n normalized.contexts.trace = event.contexts.trace;\n }\n\n const { _experiments = {} } = this.getOptions();\n if (_experiments.ensureNoCircularStructures) {\n return normalize(normalized);\n }\n\n return normalized;\n }\n\n /**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n * @param event event instance to be enhanced\n */\n protected _applyClientOptions(event: Event): void {\n const options = this.getOptions();\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : 'production';\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n }\n\n /**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\n protected _applyIntegrationsMetadata(event: Event): void {\n const integrationsArray = Object.keys(this._integrations);\n if (integrationsArray.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray];\n }\n }\n\n /**\n * Tells the backend to send this event\n * @param event The Sentry event to send\n */\n protected _sendEvent(event: Event): void {\n this._getBackend().sendEvent(event);\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n protected _captureEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<string | undefined> {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n logger.error(reason);\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n protected _processEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike<Event> {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeSend, sampleRate } = this.getOptions();\n const transport = this.getTransport();\n\n if (!this._isEnabled()) {\n return SyncPromise.reject(new SentryError('SDK not enabled, will not capture event.'));\n }\n\n const isTransaction = event.type === 'transaction';\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n transport.recordLostEvent?.(Outcome.SampleRate, 'event');\n return SyncPromise.reject(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n return this._prepareEvent(event, scope, hint)\n .then(prepared => {\n if (prepared === null) {\n transport.recordLostEvent?.(Outcome.EventProcessor, event.type || 'event');\n throw new SentryError('An event processor returned null, will not send event.');\n }\n\n const isInternalException = hint && hint.data && (hint.data as { __sentry__: boolean }).__sentry__ === true;\n if (isInternalException || isTransaction || !beforeSend) {\n return prepared;\n }\n\n const beforeSendResult = beforeSend(prepared, hint);\n return this._ensureBeforeSendRv(beforeSendResult);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n transport.recordLostEvent?.(Outcome.BeforeSend, event.type || 'event');\n throw new SentryError('`beforeSend` returned `null`, will not send event.');\n }\n\n const session = scope && scope.getSession && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n this._sendEvent(processedEvent);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason as Error,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n protected _process<T>(promise: PromiseLike<T>): void {\n this._numProcessing += 1;\n void promise.then(\n value => {\n this._numProcessing -= 1;\n return value;\n },\n reason => {\n this._numProcessing -= 1;\n return reason;\n },\n );\n }\n\n /**\n * Verifies that return value of configured `beforeSend` is of expected type.\n */\n protected _ensureBeforeSendRv(\n rv: PromiseLike<Event | null> | Event | null,\n ): PromiseLike<Event | null> | Event | null {\n const nullErr = '`beforeSend` method has to return `null` or a valid event.';\n if (isThenable(rv)) {\n return (rv as PromiseLike<Event | null>).then(\n event => {\n if (!(isPlainObject(event) || event === null)) {\n throw new SentryError(nullErr);\n }\n return event;\n },\n e => {\n throw new SentryError(`beforeSend rejected with ${e}`);\n },\n );\n } else if (!(isPlainObject(rv) || rv === null)) {\n throw new SentryError(nullErr);\n }\n return rv;\n }\n}\n", "import { Event, Response, Status, Transport } from '@sentry/types';\nimport { SyncPromise } from '@sentry/utils';\n\n/** Noop transport */\nexport class NoopTransport implements Transport {\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike<Response> {\n return SyncPromise.resolve({\n reason: `NoopTransport: Event has been skipped because no Dsn is configured.`,\n status: Status.Skipped,\n });\n }\n\n /**\n * @inheritDoc\n */\n public close(_?: number): PromiseLike<boolean> {\n return SyncPromise.resolve(true);\n }\n}\n", "import { Event, EventHint, Options, Session, Severity, Transport } from '@sentry/types';\nimport { logger, SentryError } from '@sentry/utils';\n\nimport { NoopTransport } from './transports/noop';\n\n/**\n * Internal platform-dependent Sentry SDK Backend.\n *\n * While {@link Client} contains business logic specific to an SDK, the\n * Backend offers platform specific implementations for low-level operations.\n * These are persisting and loading information, sending events, and hooking\n * into the environment.\n *\n * Backends receive a handle to the Client in their constructor. When a\n * Backend automatically generates events, it must pass them to\n * the Client for validation and processing first.\n *\n * Usually, the Client will be of corresponding type, e.g. NodeBackend\n * receives NodeClient. However, higher-level SDKs can choose to instantiate\n * multiple Backends and delegate tasks between them. In this case, an event\n * generated by one backend might very well be sent by another one.\n *\n * The client also provides access to options via {@link Client.getOptions}.\n * @hidden\n */\nexport interface Backend {\n /** Creates a {@link Event} from an exception. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n eventFromException(exception: any, hint?: EventHint): PromiseLike<Event>;\n\n /** Creates a {@link Event} from a plain message. */\n eventFromMessage(message: string, level?: Severity, hint?: EventHint): PromiseLike<Event>;\n\n /** Submits the event to Sentry */\n sendEvent(event: Event): void;\n\n /** Submits the session to Sentry */\n sendSession(session: Session): void;\n\n /**\n * Returns the transport that is used by the backend.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n *\n * @returns The transport.\n */\n getTransport(): Transport;\n}\n\n/**\n * A class object that can instantiate Backend objects.\n * @hidden\n */\nexport type BackendClass<B extends Backend, O extends Options> = new (options: O) => B;\n\n/**\n * This is the base implemention of a Backend.\n * @hidden\n */\nexport abstract class BaseBackend<O extends Options> implements Backend {\n /** Options passed to the SDK. */\n protected readonly _options: O;\n\n /** Cached transport used internally. */\n protected _transport: Transport;\n\n /** Creates a new backend instance. */\n public constructor(options: O) {\n this._options = options;\n if (!this._options.dsn) {\n logger.warn('No DSN provided, backend will not do anything.');\n }\n this._transport = this._setupTransport();\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(_exception: any, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromException` method');\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(_message: string, _level?: Severity, _hint?: EventHint): PromiseLike<Event> {\n throw new SentryError('Backend has to implement `eventFromMessage` method');\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): void {\n void this._transport.sendEvent(event).then(null, reason => {\n logger.error(`Error while sending event: ${reason}`);\n });\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session): void {\n if (!this._transport.sendSession) {\n logger.warn(\"Dropping session because custom transport doesn't implement sendSession\");\n return;\n }\n\n void this._transport.sendSession(session).then(null, reason => {\n logger.error(`Error while sending session: ${reason}`);\n });\n }\n\n /**\n * @inheritDoc\n */\n public getTransport(): Transport {\n return this._transport;\n }\n\n /**\n * Sets up the transport so it can be used later to send requests.\n */\n protected _setupTransport(): Transport {\n return new NoopTransport();\n }\n}\n", "import { Event, SdkInfo, SentryRequest, SentryRequestType, Session, SessionAggregates } from '@sentry/types';\n\nimport { API } from './api';\n\n/** Extract sdk info from from the API metadata */\nfunction getSdkMetadataForEnvelopeHeader(api: API): SdkInfo | undefined {\n if (!api.metadata || !api.metadata.sdk) {\n return;\n }\n const { name, version } = api.metadata.sdk;\n return { name, version };\n}\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event: Event, sdkInfo?: SdkInfo): Event {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates a SentryRequest from a Session. */\nexport function sessionToSentryRequest(session: Session | SessionAggregates, api: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const envelopeHeaders = JSON.stringify({\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(api.forceEnvelope() && { dsn: api.getDsn().toString() }),\n });\n // I know this is hacky but we don't want to add `session` to request type since it's never rate limited\n const type: SentryRequestType = 'aggregates' in session ? ('sessions' as SentryRequestType) : 'session';\n const itemHeaders = JSON.stringify({\n type,\n });\n\n return {\n body: `${envelopeHeaders}\\n${itemHeaders}\\n${JSON.stringify(session)}`,\n type,\n url: api.getEnvelopeEndpointWithUrlEncodedAuth(),\n };\n}\n\n/** Creates a SentryRequest from an event. */\nexport function eventToSentryRequest(event: Event, api: API): SentryRequest {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(api);\n const eventType = event.type || 'event';\n const useEnvelope = eventType === 'transaction' || api.forceEnvelope();\n\n const { transactionSampling, ...metadata } = event.debug_meta || {};\n const { method: samplingMethod, rate: sampleRate } = transactionSampling || {};\n if (Object.keys(metadata).length === 0) {\n delete event.debug_meta;\n } else {\n event.debug_meta = metadata;\n }\n\n const req: SentryRequest = {\n body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event),\n type: eventType,\n url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),\n };\n\n // https://develop.sentry.dev/sdk/envelopes/\n\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n if (useEnvelope) {\n const envelopeHeaders = JSON.stringify({\n event_id: event.event_id,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(api.forceEnvelope() && { dsn: api.getDsn().toString() }),\n });\n const itemHeaders = JSON.stringify({\n type: eventType,\n\n // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and\n // explicitly-set sampling decisions). Are we good with that?\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n\n // The content-type is assumed to be 'application/json' and not part of\n // the current spec for transaction items, so we don't bloat the request\n // body with it.\n //\n // content_type: 'application/json',\n //\n // The length is optional. It must be the number of bytes in req.Body\n // encoded as UTF-8. Since the server can figure this out and would\n // otherwise refuse events that report the length incorrectly, we decided\n // not to send the length to avoid problems related to reporting the wrong\n // size and to reduce request body size.\n //\n // length: new TextEncoder().encode(req.body).length,\n });\n // The trailing newline is optional. We intentionally don't send it to avoid\n // sending unnecessary bytes.\n //\n // const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}\\n`;\n const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}`;\n req.body = envelope;\n }\n\n return req;\n}\n", "import { getCurrentHub } from '@sentry/hub';\nimport { Client, Options } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** A class object that can instantiate Client objects. */\nexport type ClientClass<F extends Client, O extends Options> = new (options: O) => F;\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nexport function initAndBind<F extends Client, O extends Options>(clientClass: ClientClass<F, O>, options: O): void {\n if (options.debug === true) {\n logger.enable();\n }\n const hub = getCurrentHub();\n hub.getScope()?.update(options.initialScope);\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n", "export const SDK_VERSION = '6.16.1';\n", "import { Integration, WrappedFunction } from '@sentry/types';\n\nlet originalFunctionToString: () => void;\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class FunctionToString implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'FunctionToString';\n\n /**\n * @inheritDoc\n */\n public name: string = FunctionToString.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function(this: WrappedFunction, ...args: any[]): string {\n const context = this.__sentry_original__ || this;\n return originalFunctionToString.apply(context, args);\n };\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub';\nimport { Event, Integration, StackFrame } from '@sentry/types';\nimport { getEventDescription, isMatchingPattern, logger } from '@sentry/utils';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\n/** JSDoc */\ninterface InboundFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreInternal: boolean;\n\n /** @deprecated use {@link InboundFiltersOptions.allowUrls} instead. */\n whitelistUrls: Array<string | RegExp>;\n /** @deprecated use {@link InboundFiltersOptions.denyUrls} instead. */\n blacklistUrls: Array<string | RegExp>;\n}\n\n/** Inbound filters configurable by the user */\nexport class InboundFilters implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'InboundFilters';\n\n /**\n * @inheritDoc\n */\n public name: string = InboundFilters.id;\n\n public constructor(private readonly _options: Partial<InboundFiltersOptions> = {}) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event) => {\n const hub = getCurrentHub();\n if (!hub) {\n return event;\n }\n const self = hub.getIntegration(InboundFilters);\n if (self) {\n const client = hub.getClient();\n const clientOptions = client ? client.getOptions() : {};\n // This checks prevents most of the occurrences of the bug linked below:\n // https://github.com/getsentry/sentry-javascript/issues/2622\n // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code.\n // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config),\n // as we cannot force people using multiple instances in their apps to sync SDK versions.\n const options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {};\n if (typeof self._shouldDropEvent !== 'function') {\n return event;\n }\n return self._shouldDropEvent(event, options) ? null : event;\n }\n return event;\n });\n }\n\n /** JSDoc */\n private _shouldDropEvent(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (this._isSentryError(event, options)) {\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (this._isIgnoredError(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (this._isDeniedUrl(event, options)) {\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!this._isAllowedUrl(event, options)) {\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${this._getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n }\n\n /** JSDoc */\n private _isSentryError(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (!options.ignoreInternal) {\n return false;\n }\n\n try {\n return (\n (event &&\n event.exception &&\n event.exception.values &&\n event.exception.values[0] &&\n event.exception.values[0].type === 'SentryError') ||\n false\n );\n } catch (_oO) {\n return false;\n }\n }\n\n /** JSDoc */\n private _isIgnoredError(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n if (!options.ignoreErrors || !options.ignoreErrors.length) {\n return false;\n }\n\n return this._getPossibleEventMessages(event).some(message =>\n // Not sure why TypeScript complains here...\n (options.ignoreErrors as Array<RegExp | string>).some(pattern => isMatchingPattern(message, pattern)),\n );\n }\n\n /** JSDoc */\n private _isDeniedUrl(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n // TODO: Use Glob instead?\n if (!options.denyUrls || !options.denyUrls.length) {\n return false;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? false : options.denyUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _isAllowedUrl(event: Event, options: Partial<InboundFiltersOptions>): boolean {\n // TODO: Use Glob instead?\n if (!options.allowUrls || !options.allowUrls.length) {\n return true;\n }\n const url = this._getEventFilterUrl(event);\n return !url ? true : options.allowUrls.some(pattern => isMatchingPattern(url, pattern));\n }\n\n /** JSDoc */\n private _mergeOptions(clientOptions: Partial<InboundFiltersOptions> = {}): Partial<InboundFiltersOptions> {\n return {\n allowUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.whitelistUrls || []),\n ...(this._options.allowUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.whitelistUrls || []),\n ...(clientOptions.allowUrls || []),\n ],\n denyUrls: [\n // eslint-disable-next-line deprecation/deprecation\n ...(this._options.blacklistUrls || []),\n ...(this._options.denyUrls || []),\n // eslint-disable-next-line deprecation/deprecation\n ...(clientOptions.blacklistUrls || []),\n ...(clientOptions.denyUrls || []),\n ],\n ignoreErrors: [\n ...(this._options.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...DEFAULT_IGNORE_ERRORS,\n ],\n ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true,\n };\n }\n\n /** JSDoc */\n private _getPossibleEventMessages(event: Event): string[] {\n if (event.message) {\n return [event.message];\n }\n if (event.exception) {\n try {\n const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {};\n return [`${value}`, `${type}: ${value}`];\n } catch (oO) {\n logger.error(`Cannot extract message for event ${getEventDescription(event)}`);\n return [];\n }\n }\n return [];\n }\n\n /** JSDoc */\n private _getLastValidUrl(frames: StackFrame[] = []): string | null {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame?.filename !== '<anonymous>' && frame?.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n }\n\n /** JSDoc */\n private _getEventFilterUrl(event: Event): string | null {\n try {\n if (event.stacktrace) {\n const frames = event.stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n if (event.exception) {\n const frames =\n event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames;\n return this._getLastValidUrl(frames);\n }\n return null;\n } catch (oO) {\n logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n }\n}\n", "export { FunctionToString } from './functiontostring';\nexport { InboundFilters } from './inboundfilters';\n", "export {\n addBreadcrumb,\n captureException,\n captureEvent,\n captureMessage,\n configureScope,\n startTransaction,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n} from '@sentry/minimal';\nexport { addGlobalEventProcessor, getCurrentHub, getHubFromCarrier, Hub, makeMain, Scope } from '@sentry/hub';\nexport { API } from './api';\nexport { BaseClient } from './baseclient';\nexport { BackendClass, BaseBackend } from './basebackend';\nexport { eventToSentryRequest, sessionToSentryRequest } from './request';\nexport { initAndBind, ClientClass } from './sdk';\nexport { NoopTransport } from './transports/noop';\nexport { SDK_VERSION } from './version';\n\nimport * as Integrations from './integrations';\n\nexport { Integrations };\n", "/**\n * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most\n * recently used items while discarding least recently used items when its limit\n * is reached.\n *\n * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>\n * See README.md for details.\n *\n * Illustration of the design:\n *\n * entry entry entry entry\n * ______ ______ ______ ______\n * | head |.newer => | |.newer => | |.newer => | tail |\n * | A | | B | | C | | D |\n * |______| <= older.|______| <= older.|______| <= older.|______|\n *\n * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added\n */\n(function(g,f){\n const e = typeof exports == 'object' ? exports : typeof g == 'object' ? g : {};\n f(e);\n if (typeof define == 'function' && define.amd) { define('lru', e); }\n})(this, function(exports) {\n\nconst NEWER = Symbol('newer');\nconst OLDER = Symbol('older');\n\nfunction LRUMap(limit, entries) {\n if (typeof limit !== 'number') {\n // called as (entries)\n entries = limit;\n limit = 0;\n }\n\n this.size = 0;\n this.limit = limit;\n this.oldest = this.newest = undefined;\n this._keymap = new Map();\n\n if (entries) {\n this.assign(entries);\n if (limit < 1) {\n this.limit = this.size;\n }\n }\n}\n\nexports.LRUMap = LRUMap;\n\nfunction Entry(key, value) {\n this.key = key;\n this.value = value;\n this[NEWER] = undefined;\n this[OLDER] = undefined;\n}\n\n\nLRUMap.prototype._markEntryAsUsed = function(entry) {\n if (entry === this.newest) {\n // Already the most recenlty used entry, so no need to update the list\n return;\n }\n // HEAD--------------TAIL\n // <.older .newer>\n // <--- add direction --\n // A B C <D> E\n if (entry[NEWER]) {\n if (entry === this.oldest) {\n this.oldest = entry[NEWER];\n }\n entry[NEWER][OLDER] = entry[OLDER]; // C <-- E.\n }\n if (entry[OLDER]) {\n entry[OLDER][NEWER] = entry[NEWER]; // C. --> E\n }\n entry[NEWER] = undefined; // D --x\n entry[OLDER] = this.newest; // D. --> E\n if (this.newest) {\n this.newest[NEWER] = entry; // E. <-- D\n }\n this.newest = entry;\n};\n\nLRUMap.prototype.assign = function(entries) {\n let entry, limit = this.limit || Number.MAX_VALUE;\n this._keymap.clear();\n let it = entries[Symbol.iterator]();\n for (let itv = it.next(); !itv.done; itv = it.next()) {\n let e = new Entry(itv.value[0], itv.value[1]);\n this._keymap.set(e.key, e);\n if (!entry) {\n this.oldest = e;\n } else {\n entry[NEWER] = e;\n e[OLDER] = entry;\n }\n entry = e;\n if (limit-- == 0) {\n throw new Error('overflow');\n }\n }\n this.newest = entry;\n this.size = this._keymap.size;\n};\n\nLRUMap.prototype.get = function(key) {\n // First, find our cache entry\n var entry = this._keymap.get(key);\n if (!entry) return; // Not cached. Sorry.\n // As <key> was found in the cache, register it as being requested recently\n this._markEntryAsUsed(entry);\n return entry.value;\n};\n\nLRUMap.prototype.set = function(key, value) {\n var entry = this._keymap.get(key);\n\n if (entry) {\n // update existing\n entry.value = value;\n this._markEntryAsUsed(entry);\n return this;\n }\n\n // new entry\n this._keymap.set(key, (entry = new Entry(key, value)));\n\n if (this.newest) {\n // link previous tail to the new tail (entry)\n this.newest[NEWER] = entry;\n entry[OLDER] = this.newest;\n } else {\n // we're first in -- yay\n this.oldest = entry;\n }\n\n // add new entry to the end of the linked list -- it's now the freshest entry.\n this.newest = entry;\n ++this.size;\n if (this.size > this.limit) {\n // we hit the limit -- remove the head\n this.shift();\n }\n\n return this;\n};\n\nLRUMap.prototype.shift = function() {\n // todo: handle special case when limit == 1\n var entry = this.oldest;\n if (entry) {\n if (this.oldest[NEWER]) {\n // advance the list\n this.oldest = this.oldest[NEWER];\n this.oldest[OLDER] = undefined;\n } else {\n // the cache is exhausted\n this.oldest = undefined;\n this.newest = undefined;\n }\n // Remove last strong reference to <entry> and remove links from the purged\n // entry being returned:\n entry[NEWER] = entry[OLDER] = undefined;\n this._keymap.delete(entry.key);\n --this.size;\n return [entry.key, entry.value];\n }\n};\n\n// ----------------------------------------------------------------------------\n// Following code is optional and can be removed without breaking the core\n// functionality.\n\nLRUMap.prototype.find = function(key) {\n let e = this._keymap.get(key);\n return e ? e.value : undefined;\n};\n\nLRUMap.prototype.has = function(key) {\n return this._keymap.has(key);\n};\n\nLRUMap.prototype['delete'] = function(key) {\n var entry = this._keymap.get(key);\n if (!entry) return;\n this._keymap.delete(entry.key);\n if (entry[NEWER] && entry[OLDER]) {\n // relink the older entry with the newer entry\n entry[OLDER][NEWER] = entry[NEWER];\n entry[NEWER][OLDER] = entry[OLDER];\n } else if (entry[NEWER]) {\n // remove the link to us\n entry[NEWER][OLDER] = undefined;\n // link the newer entry to head\n this.oldest = entry[NEWER];\n } else if (entry[OLDER]) {\n // remove the link to us\n entry[OLDER][NEWER] = undefined;\n // link the newer entry to head\n this.newest = entry[OLDER];\n } else {// if(entry[OLDER] === undefined && entry.newer === undefined) {\n this.oldest = this.newest = undefined;\n }\n\n this.size--;\n return entry.value;\n};\n\nLRUMap.prototype.clear = function() {\n // Not clearing links should be safe, as we don't expose live links to user\n this.oldest = this.newest = undefined;\n this.size = 0;\n this._keymap.clear();\n};\n\n\nfunction EntryIterator(oldestEntry) { this.entry = oldestEntry; }\nEntryIterator.prototype[Symbol.iterator] = function() { return this; }\nEntryIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: [ent.key, ent.value] };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nfunction KeyIterator(oldestEntry) { this.entry = oldestEntry; }\nKeyIterator.prototype[Symbol.iterator] = function() { return this; }\nKeyIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.key };\n } else {\n return { done: true, value: undefined };\n }\n};\n\nfunction ValueIterator(oldestEntry) { this.entry = oldestEntry; }\nValueIterator.prototype[Symbol.iterator] = function() { return this; }\nValueIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.value };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nLRUMap.prototype.keys = function() {\n return new KeyIterator(this.oldest);\n};\n\nLRUMap.prototype.values = function() {\n return new ValueIterator(this.oldest);\n};\n\nLRUMap.prototype.entries = function() {\n return this;\n};\n\nLRUMap.prototype[Symbol.iterator] = function() {\n return new EntryIterator(this.oldest);\n};\n\nLRUMap.prototype.forEach = function(fun, thisObj) {\n if (typeof thisObj !== 'object') {\n thisObj = this;\n }\n let entry = this.oldest;\n while (entry) {\n fun.call(thisObj, entry.value, entry.key, this);\n entry = entry[NEWER];\n }\n};\n\n/** Returns a JSON (array) representation */\nLRUMap.prototype.toJSON = function() {\n var s = new Array(this.size), i = 0, entry = this.oldest;\n while (entry) {\n s[i++] = { key: entry.key, value: entry.value };\n entry = entry[NEWER];\n }\n return s;\n};\n\n/** Returns a String representation */\nLRUMap.prototype.toString = function() {\n var s = '', entry = this.oldest;\n while (entry) {\n s += String(entry.key)+':'+entry.value;\n entry = entry[NEWER];\n if (entry) {\n s += ' < ';\n }\n }\n return s;\n};\n\n});\n", "/**\n * stack-trace - Parses node.js stack traces\n *\n * This was originally forked to fix this issue:\n * https://github.com/felixge/node-stack-trace/issues/31\n *\n * Mar 19,2019 - #4fd379e\n *\n * https://github.com/felixge/node-stack-trace/\n * @license MIT\n */\n\n/** Decoded StackFrame */\nexport interface StackFrame {\n fileName: string;\n lineNumber: number;\n functionName: string;\n typeName: string;\n methodName: string;\n native: boolean;\n columnNumber: number;\n}\n\n/** Extracts StackFrames from the Error */\nexport function parse(err: Error): StackFrame[] {\n if (!err.stack) {\n return [];\n }\n\n const lines = err.stack.split('\\n').slice(1);\n\n return lines\n .map(line => {\n if (line.match(/^\\s*[-]{4,}$/)) {\n return {\n columnNumber: null,\n fileName: line,\n functionName: null,\n lineNumber: null,\n methodName: null,\n native: null,\n typeName: null,\n };\n }\n\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\n if (!lineMatch) {\n return undefined;\n }\n\n let object = null;\n let method = null;\n let functionName = null;\n let typeName = null;\n let methodName = null;\n const isNative = lineMatch[5] === 'native';\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n // eslint-disable-next-line no-plusplus\n methodStart--;\n }\n if (methodStart > 0) {\n object = functionName.substr(0, methodStart);\n method = functionName.substr(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.substr(objectEnd + 1);\n object = object.substr(0, objectEnd);\n }\n }\n typeName = null;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '<anonymous>') {\n methodName = null;\n functionName = null;\n }\n\n const properties = {\n columnNumber: parseInt(lineMatch[4], 10) || null,\n fileName: lineMatch[2] || null,\n functionName,\n lineNumber: parseInt(lineMatch[3], 10) || null,\n methodName,\n native: isNative,\n typeName,\n };\n\n return properties;\n })\n .filter(callSite => !!callSite) as StackFrame[];\n}\n", "import { Event, Exception, ExtendedError, StackFrame } from '@sentry/types';\nimport { addContextToFrame, basename, dirname, SyncPromise } from '@sentry/utils';\nimport { readFile } from 'fs';\nimport { LRUMap } from 'lru_map';\n\nimport * as stacktrace from './stacktrace';\nimport { NodeOptions } from './types';\n\nconst DEFAULT_LINES_OF_CONTEXT: number = 7;\nconst FILE_CONTENT_CACHE = new LRUMap<string, string | null>(100);\n\n/**\n * Resets the file cache. Exists for testing purposes.\n * @hidden\n */\nexport function resetFileContentCache(): void {\n FILE_CONTENT_CACHE.clear();\n}\n\n/** JSDoc */\nfunction getFunction(frame: stacktrace.StackFrame): string {\n try {\n return frame.functionName || `${frame.typeName}.${frame.methodName || '<anonymous>'}`;\n } catch (e) {\n // This seems to happen sometimes when using 'use strict',\n // stemming from `getTypeName`.\n // [TypeError: Cannot read property 'constructor' of undefined]\n return '<anonymous>';\n }\n}\n\nconst mainModule: string = `${(require.main && require.main.filename && dirname(require.main.filename)) ||\n global.process.cwd()}/`;\n\n/** JSDoc */\nfunction getModule(filename: string, base?: string): string {\n if (!base) {\n // eslint-disable-next-line no-param-reassign\n base = mainModule;\n }\n\n // It's specifically a module\n const file = basename(filename, '.js');\n // eslint-disable-next-line no-param-reassign\n filename = dirname(filename);\n let n = filename.lastIndexOf('/node_modules/');\n if (n > -1) {\n // /node_modules/ is 14 chars\n return `${filename.substr(n + 14).replace(/\\//g, '.')}:${file}`;\n }\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n n = `${filename}/`.lastIndexOf(base, 0);\n if (n === 0) {\n let moduleName = filename.substr(base.length).replace(/\\//g, '.');\n if (moduleName) {\n moduleName += ':';\n }\n moduleName += file;\n return moduleName;\n }\n return file;\n}\n\n/**\n * This function reads file contents and caches them in a global LRU cache.\n * Returns a Promise filepath => content array for all files that we were able to read.\n *\n * @param filenames Array of filepaths to read content from.\n */\nfunction readSourceFiles(filenames: string[]): PromiseLike<{ [key: string]: string | null }> {\n // we're relying on filenames being de-duped already\n if (filenames.length === 0) {\n return SyncPromise.resolve({});\n }\n\n return new SyncPromise<{\n [key: string]: string | null;\n }>(resolve => {\n const sourceFiles: {\n [key: string]: string | null;\n } = {};\n\n let count = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < filenames.length; i++) {\n const filename = filenames[i];\n\n const cache = FILE_CONTENT_CACHE.get(filename);\n // We have a cache hit\n if (cache !== undefined) {\n // If it's not null (which means we found a file and have a content)\n // we set the content and return it later.\n if (cache !== null) {\n sourceFiles[filename] = cache;\n }\n // eslint-disable-next-line no-plusplus\n count++;\n // In any case we want to skip here then since we have a content already or we couldn't\n // read the file and don't want to try again.\n if (count === filenames.length) {\n resolve(sourceFiles);\n }\n continue;\n }\n\n readFile(filename, (err: Error | null, data: Buffer) => {\n const content = err ? null : data.toString();\n sourceFiles[filename] = content;\n\n // We always want to set the cache, even to null which means there was an error reading the file.\n // We do not want to try to read the file again.\n FILE_CONTENT_CACHE.set(filename, content);\n // eslint-disable-next-line no-plusplus\n count++;\n if (count === filenames.length) {\n resolve(sourceFiles);\n }\n });\n }\n });\n}\n\n/**\n * @hidden\n */\nexport function extractStackFromError(error: Error): stacktrace.StackFrame[] {\n const stack = stacktrace.parse(error);\n if (!stack) {\n return [];\n }\n return stack;\n}\n\n/**\n * @hidden\n */\nexport function parseStack(stack: stacktrace.StackFrame[], options?: NodeOptions): PromiseLike<StackFrame[]> {\n const filesToRead: string[] = [];\n\n const linesOfContext =\n options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n const frames: StackFrame[] = stack.map(frame => {\n const parsedFrame: StackFrame = {\n colno: frame.columnNumber,\n filename: frame.fileName?.startsWith('file://') ? frame.fileName.substr(7) : frame.fileName || '',\n function: getFunction(frame),\n lineno: frame.lineNumber,\n };\n\n const isInternal =\n frame.native ||\n (parsedFrame.filename &&\n !parsedFrame.filename.startsWith('/') &&\n !parsedFrame.filename.startsWith('.') &&\n parsedFrame.filename.indexOf(':\\\\') !== 1);\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n parsedFrame.in_app =\n !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1;\n\n // Extract a module name based on the filename\n if (parsedFrame.filename) {\n parsedFrame.module = getModule(parsedFrame.filename);\n\n if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) {\n filesToRead.push(parsedFrame.filename);\n }\n }\n\n return parsedFrame;\n });\n\n // We do an early return if we do not want to fetch context liens\n if (linesOfContext <= 0) {\n return SyncPromise.resolve(frames);\n }\n\n try {\n return addPrePostContext(filesToRead, frames, linesOfContext);\n } catch (_) {\n // This happens in electron for example where we are not able to read files from asar.\n // So it's fine, we recover be just returning all frames without pre/post context.\n return SyncPromise.resolve(frames);\n }\n}\n\n/**\n * This function tries to read the source files + adding pre and post context (source code)\n * to a frame.\n * @param filesToRead string[] of filepaths\n * @param frames StackFrame[] containg all frames\n */\nfunction addPrePostContext(\n filesToRead: string[],\n frames: StackFrame[],\n linesOfContext: number,\n): PromiseLike<StackFrame[]> {\n return new SyncPromise<StackFrame[]>(resolve =>\n readSourceFiles(filesToRead).then(sourceFiles => {\n const result = frames.map(frame => {\n if (frame.filename && sourceFiles[frame.filename]) {\n try {\n const lines = (sourceFiles[frame.filename] as string).split('\\n');\n\n addContextToFrame(lines, frame, linesOfContext);\n } catch (e) {\n // anomaly, being defensive in case\n // unlikely to ever happen in practice but can definitely happen in theory\n }\n }\n return frame;\n });\n\n resolve(result);\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function getExceptionFromError(error: Error, options?: NodeOptions): PromiseLike<Exception> {\n const name = error.name || error.constructor.name;\n const stack = extractStackFromError(error);\n return new SyncPromise<Exception>(resolve =>\n parseStack(stack, options).then(frames => {\n const result = {\n stacktrace: {\n frames: prepareFramesForEvent(frames),\n },\n type: name,\n value: error.message,\n };\n resolve(result);\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function parseError(error: ExtendedError, options?: NodeOptions): PromiseLike<Event> {\n return new SyncPromise<Event>(resolve =>\n getExceptionFromError(error, options).then((exception: Exception) => {\n resolve({\n exception: {\n values: [exception],\n },\n });\n }),\n );\n}\n\n/**\n * @hidden\n */\nexport function prepareFramesForEvent(stack: StackFrame[]): StackFrame[] {\n if (!stack || !stack.length) {\n return [];\n }\n\n let localStack = stack;\n const firstFrameFunction = localStack[0].function || '';\n\n if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) {\n localStack = localStack.slice(1);\n }\n\n // The frame where the crash happened, should be the last entry in the array\n return localStack.reverse();\n}\n", "// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata\nexport const SDK_NAME = 'sentry.javascript.node';\n", "import { API, SDK_VERSION } from '@sentry/core';\nimport {\n DsnProtocol,\n Event,\n Response,\n SentryRequest,\n SentryRequestType,\n Session,\n SessionAggregates,\n Status,\n Transport,\n TransportOptions,\n} from '@sentry/types';\nimport { logger, parseRetryAfterHeader, PromiseBuffer, SentryError } from '@sentry/utils';\nimport * as fs from 'fs';\nimport * as http from 'http';\nimport * as https from 'https';\nimport { URL } from 'url';\n\nimport { SDK_NAME } from '../../version';\nimport { HTTPModule } from './http-module';\n\nexport type URLParts = Pick<URL, 'hostname' | 'pathname' | 'port' | 'protocol'>;\nexport type UrlParser = (url: string) => URLParts;\n\nconst CATEGORY_MAPPING: {\n [key in SentryRequestType]: string;\n} = {\n event: 'error',\n transaction: 'transaction',\n session: 'session',\n attachment: 'attachment',\n};\n\n/** Base Transport class implementation */\nexport abstract class BaseTransport implements Transport {\n /** The Agent used for corresponding transport */\n public module?: HTTPModule;\n\n /** The Agent used for corresponding transport */\n public client?: http.Agent | https.Agent;\n\n /** API object */\n protected _api: API;\n\n /** A simple buffer holding all requests. */\n protected readonly _buffer: PromiseBuffer<Response> = new PromiseBuffer(30);\n\n /** Locks transport after receiving rate limits in a response */\n protected readonly _rateLimits: Record<string, Date> = {};\n\n /** Create instance and set this.dsn */\n public constructor(public options: TransportOptions) {\n this._api = new API(options.dsn, options._metadata, options.tunnel);\n }\n\n /** Default function used to parse URLs */\n public urlParser: UrlParser = url => new URL(url);\n\n /**\n * @inheritDoc\n */\n public sendEvent(_: Event): PromiseLike<Response> {\n throw new SentryError('Transport Class has to implement `sendEvent` method.');\n }\n\n /**\n * @inheritDoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n return this._buffer.drain(timeout);\n }\n\n /**\n * Extracts proxy settings from client options and env variables.\n *\n * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion.\n *\n * An order of priority for available protocols is:\n * `http` => `options.httpProxy` | `process.env.http_proxy`\n * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy`\n */\n protected _getProxy(protocol: DsnProtocol): string | undefined {\n const { no_proxy, http_proxy, https_proxy } = process.env;\n const { httpProxy, httpsProxy } = this.options;\n const proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy;\n\n if (!no_proxy) {\n return proxy;\n }\n\n const { host, port } = this._api.getDsn();\n for (const np of no_proxy.split(',')) {\n if (host.endsWith(np) || `${host}:${port}`.endsWith(np)) {\n return;\n }\n }\n\n return proxy;\n }\n\n /** Returns a build request option object used by request */\n protected _getRequestOptions(urlParts: URLParts): http.RequestOptions | https.RequestOptions {\n const headers = {\n ...this._api.getRequestHeaders(SDK_NAME, SDK_VERSION),\n ...this.options.headers,\n };\n const { hostname, pathname, port, protocol } = urlParts;\n // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290\n // We ignore the query string on purpose\n const path = `${pathname}`;\n\n return {\n agent: this.client,\n headers,\n hostname,\n method: 'POST',\n path,\n port,\n protocol,\n ...(this.options.caCerts && {\n ca: fs.readFileSync(this.options.caCerts),\n }),\n };\n }\n\n /**\n * Gets the time that given category is disabled until for rate limiting\n */\n protected _disabledUntil(requestType: SentryRequestType): Date {\n const category = CATEGORY_MAPPING[requestType];\n return this._rateLimits[category] || this._rateLimits.all;\n }\n\n /**\n * Checks if a category is rate limited\n */\n protected _isRateLimited(requestType: SentryRequestType): boolean {\n return this._disabledUntil(requestType) > new Date(Date.now());\n }\n\n /**\n * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header.\n */\n protected _handleRateLimit(headers: Record<string, string | null>): boolean {\n const now = Date.now();\n const rlHeader = headers['x-sentry-rate-limits'];\n const raHeader = headers['retry-after'];\n\n if (rlHeader) {\n // rate limit headers are of the form\n // <header>,<header>,..\n // where each <header> is of the form\n // <retry_after>: <categories>: <scope>: <reason_code>\n // where\n // <retry_after> is a delay in ms\n // <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form\n // <category>;<category>;...\n // <scope> is what's being limited (org, project, or key) - ignored by SDK\n // <reason_code> is an arbitrary string like \"org_quota\" - ignored by SDK\n for (const limit of rlHeader.trim().split(',')) {\n const parameters = limit.split(':', 2);\n const headerDelay = parseInt(parameters[0], 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n for (const category of (parameters[1] && parameters[1].split(';')) || ['all']) {\n // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this\n // sdk and any categories that are not supported will not be added redundantly to the rateLimits object\n const categoriesAllowed = [\n ...(Object.keys(CATEGORY_MAPPING) as [SentryRequestType]).map(k => CATEGORY_MAPPING[k]),\n 'all',\n ];\n if (categoriesAllowed.includes(category)) this._rateLimits[category] = new Date(now + delay);\n }\n }\n return true;\n } else if (raHeader) {\n this._rateLimits.all = new Date(now + parseRetryAfterHeader(now, raHeader));\n return true;\n }\n return false;\n }\n\n /** JSDoc */\n protected async _send(\n sentryRequest: SentryRequest,\n originalPayload?: Event | Session | SessionAggregates,\n ): Promise<Response> {\n if (!this.module) {\n throw new SentryError('No module available');\n }\n if (originalPayload && this._isRateLimited(sentryRequest.type)) {\n return Promise.reject({\n payload: originalPayload,\n type: sentryRequest.type,\n reason: `Transport for ${sentryRequest.type} requests locked till ${this._disabledUntil(\n sentryRequest.type,\n )} due to too many requests.`,\n status: 429,\n });\n }\n\n return this._buffer.add(\n () =>\n new Promise<Response>((resolve, reject) => {\n if (!this.module) {\n throw new SentryError('No module available');\n }\n const options = this._getRequestOptions(this.urlParser(sentryRequest.url));\n const req = this.module.request(options, res => {\n const statusCode = res.statusCode || 500;\n const status = Status.fromHttpCode(statusCode);\n\n res.setEncoding('utf8');\n\n /**\n * \"Key-value pairs of header names and values. Header names are lower-cased.\"\n * https://nodejs.org/api/http.html#http_message_headers\n */\n let retryAfterHeader = res.headers ? res.headers['retry-after'] : '';\n retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader) as string;\n\n let rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : '';\n rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader) as string;\n\n const headers = {\n 'x-sentry-rate-limits': rlHeader,\n 'retry-after': retryAfterHeader,\n };\n\n const limited = this._handleRateLimit(headers);\n if (limited)\n logger.warn(\n `Too many ${sentryRequest.type} requests, backing off until: ${this._disabledUntil(\n sentryRequest.type,\n )}`,\n );\n\n if (status === Status.Success) {\n resolve({ status });\n } else {\n let rejectionMessage = `HTTP Error (${statusCode})`;\n if (res.headers && res.headers['x-sentry-error']) {\n rejectionMessage += `: ${res.headers['x-sentry-error']}`;\n }\n reject(new SentryError(rejectionMessage));\n }\n\n // Force the socket to drain\n res.on('data', () => {\n // Drain\n });\n res.on('end', () => {\n // Drain\n });\n });\n req.on('error', reject);\n req.end(sentryRequest.body);\n }),\n );\n }\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n 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(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n", "'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.format()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.format(...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", null, null, null, null, null, "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Response, Session, SessionAggregates, TransportOptions } from '@sentry/types';\nimport * as http from 'http';\n\nimport { BaseTransport } from './base';\n\n/** Node http module transport */\nexport class HTTPTransport extends BaseTransport {\n /** Create a new instance and set this.agent */\n public constructor(public options: TransportOptions) {\n super(options);\n const proxy = this._getProxy('http');\n this.module = http;\n this.client = proxy\n ? (new (require('https-proxy-agent'))(proxy) as http.Agent)\n : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): Promise<Response> {\n return this._send(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): PromiseLike<Response> {\n return this._send(sessionToSentryRequest(session, this._api), session);\n }\n}\n", "import { eventToSentryRequest, sessionToSentryRequest } from '@sentry/core';\nimport { Event, Response, Session, SessionAggregates, TransportOptions } from '@sentry/types';\nimport * as https from 'https';\n\nimport { BaseTransport } from './base';\n\n/** Node https module transport */\nexport class HTTPSTransport extends BaseTransport {\n /** Create a new instance and set this.agent */\n public constructor(public options: TransportOptions) {\n super(options);\n const proxy = this._getProxy('https');\n this.module = https;\n this.client = proxy\n ? (new (require('https-proxy-agent'))(proxy) as https.Agent)\n : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 });\n }\n\n /**\n * @inheritDoc\n */\n public sendEvent(event: Event): Promise<Response> {\n return this._send(eventToSentryRequest(event, this._api), event);\n }\n\n /**\n * @inheritDoc\n */\n public sendSession(session: Session | SessionAggregates): PromiseLike<Response> {\n return this._send(sessionToSentryRequest(session, this._api), session);\n }\n}\n", "export { BaseTransport } from './base';\nexport { HTTPTransport } from './http';\nexport { HTTPSTransport } from './https';\n", "import { BaseBackend, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Mechanism, Severity, Transport, TransportOptions } from '@sentry/types';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n Dsn,\n extractExceptionKeysForMessage,\n isError,\n isPlainObject,\n normalizeToSize,\n SyncPromise,\n} from '@sentry/utils';\n\nimport { extractStackFromError, parseError, parseStack, prepareFramesForEvent } from './parsers';\nimport { HTTPSTransport, HTTPTransport } from './transports';\nimport { NodeOptions } from './types';\n\n/**\n * The Sentry Node SDK Backend.\n * @hidden\n */\nexport class NodeBackend extends BaseBackend<NodeOptions> {\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public eventFromException(exception: any, hint?: EventHint): PromiseLike<Event> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ex: any = exception;\n const providedMechanism: Mechanism | undefined =\n hint && hint.data && (hint.data as { mechanism: Mechanism }).mechanism;\n const mechanism: Mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n if (!isError(exception)) {\n if (isPlainObject(exception)) {\n // This will allow us to group events based on top-level keys\n // which is much better than creating new group when any key/value change\n const message = `Non-Error exception captured with keys: ${extractExceptionKeysForMessage(exception)}`;\n\n getCurrentHub().configureScope(scope => {\n scope.setExtra('__serialized__', normalizeToSize(exception as Record<string, unknown>));\n });\n\n ex = (hint && hint.syntheticException) || new Error(message);\n (ex as Error).message = message;\n } else {\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n ex = (hint && hint.syntheticException) || new Error(exception as string);\n (ex as Error).message = exception;\n }\n mechanism.synthetic = true;\n }\n\n return new SyncPromise<Event>((resolve, reject) =>\n parseError(ex as Error, this._options)\n .then(event => {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n resolve({\n ...event,\n event_id: hint && hint.event_id,\n });\n })\n .then(null, reject),\n );\n }\n\n /**\n * @inheritDoc\n */\n public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike<Event> {\n const event: Event = {\n event_id: hint && hint.event_id,\n level,\n message,\n };\n\n return new SyncPromise<Event>(resolve => {\n if (this._options.attachStacktrace && hint && hint.syntheticException) {\n const stack = hint.syntheticException ? extractStackFromError(hint.syntheticException) : [];\n void parseStack(stack, this._options)\n .then(frames => {\n event.stacktrace = {\n frames: prepareFramesForEvent(frames),\n };\n resolve(event);\n })\n .then(null, () => {\n resolve(event);\n });\n } else {\n resolve(event);\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n protected _setupTransport(): Transport {\n if (!this._options.dsn) {\n // We return the noop transport here in case there is no Dsn.\n return super._setupTransport();\n }\n\n const dsn = new Dsn(this._options.dsn);\n\n const transportOptions: TransportOptions = {\n ...this._options.transportOptions,\n ...(this._options.httpProxy && { httpProxy: this._options.httpProxy }),\n ...(this._options.httpsProxy && { httpsProxy: this._options.httpsProxy }),\n ...(this._options.caCerts && { caCerts: this._options.caCerts }),\n dsn: this._options.dsn,\n tunnel: this._options.tunnel,\n _metadata: this._options._metadata,\n };\n\n if (this._options.transport) {\n return new this._options.transport(transportOptions);\n }\n if (dsn.protocol === 'http') {\n return new HTTPTransport(transportOptions);\n }\n return new HTTPSTransport(transportOptions);\n }\n}\n", "import { BaseClient, Scope, SDK_VERSION } from '@sentry/core';\nimport { SessionFlusher } from '@sentry/hub';\nimport { Event, EventHint, RequestSessionStatus } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { NodeBackend } from './backend';\nimport { NodeOptions } from './types';\n\n/**\n * The Sentry Node SDK Client.\n *\n * @see NodeOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nexport class NodeClient extends BaseClient<NodeBackend, NodeOptions> {\n protected _sessionFlusher: SessionFlusher | undefined;\n\n /**\n * Creates a new Node SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: NodeOptions) {\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.node',\n packages: [\n {\n name: 'npm:@sentry/node',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(NodeBackend, options);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const requestSession = scope.getRequestSession();\n\n // Necessary checks to ensure this is code block is executed only within a request\n // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage\n if (requestSession && requestSession.status === RequestSessionStatus.Ok) {\n requestSession.status = RequestSessionStatus.Errored;\n }\n }\n\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined {\n // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only\n // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload\n // sent to the Server only when the `requestHandler` middleware is used\n if (this._options.autoSessionTracking && this._sessionFlusher && scope) {\n const eventType = event.type || 'exception';\n const isException =\n eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0;\n\n // If the event is of type Exception, then a request session should be captured\n if (isException) {\n const requestSession = scope.getRequestSession();\n\n // Ensure that this is happening within the bounds of a request, and make sure not to override\n // Session Status if Errored / Crashed\n if (requestSession && requestSession.status === RequestSessionStatus.Ok) {\n requestSession.status = RequestSessionStatus.Errored;\n }\n }\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n *\n * @inheritdoc\n */\n public close(timeout?: number): PromiseLike<boolean> {\n this._sessionFlusher?.close();\n return super.close(timeout);\n }\n\n /** Method that initialises an instance of SessionFlusher on Client */\n public initSessionFlusher(): void {\n const { release, environment } = this._options;\n if (!release) {\n logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!');\n } else {\n this._sessionFlusher = new SessionFlusher(this.getTransport(), {\n release,\n environment,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n protected _prepareEvent(event: Event, scope?: Scope, hint?: EventHint): PromiseLike<Event | null> {\n event.platform = event.platform || 'node';\n if (this.getOptions().serverName) {\n event.server_name = this.getOptions().serverName;\n }\n return super._prepareEvent(event, scope, hint);\n }\n\n /**\n * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment\n * appropriate session aggregates bucket\n */\n protected _captureRequestSession(): void {\n if (!this._sessionFlusher) {\n logger.warn('Discarded request mode session because autoSessionTracking option was disabled');\n } else {\n this._sessionFlusher.incrementSessionStatusCount();\n }\n }\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { Integration, Severity } from '@sentry/types';\nimport { fill } from '@sentry/utils';\nimport * as util from 'util';\n\n/** Console module integration */\nexport class Console implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Console';\n\n /**\n * @inheritDoc\n */\n public name: string = Console.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n for (const level of ['debug', 'info', 'warn', 'error', 'log']) {\n fill(console, level, createConsoleWrapper(level));\n }\n }\n}\n\n/**\n * Wrapper function that'll be used for every console level\n */\nfunction createConsoleWrapper(level: string): (originalConsoleMethod: () => void) => void {\n return function consoleWrapper(originalConsoleMethod: () => void): () => void {\n let sentryLevel: Severity;\n\n switch (level) {\n case 'debug':\n sentryLevel = Severity.Debug;\n break;\n case 'error':\n sentryLevel = Severity.Error;\n break;\n case 'info':\n sentryLevel = Severity.Info;\n break;\n case 'warn':\n sentryLevel = Severity.Warning;\n break;\n default:\n sentryLevel = Severity.Log;\n }\n\n /* eslint-disable prefer-rest-params */\n return function(this: typeof console): void {\n if (getCurrentHub().getIntegration(Console)) {\n getCurrentHub().addBreadcrumb(\n {\n category: 'console',\n level: sentryLevel,\n message: util.format.apply(undefined, arguments),\n },\n {\n input: [...arguments],\n level,\n },\n );\n }\n\n originalConsoleMethod.apply(this, arguments);\n };\n /* eslint-enable prefer-rest-params */\n };\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { parseSemver } from '@sentry/utils';\nimport * as http from 'http';\nimport * as https from 'https';\nimport { URL } from 'url';\n\nconst NODE_VERSION = parseSemver(process.versions.node);\n\n/**\n * Checks whether given url points to Sentry server\n * @param url url to verify\n */\nexport function isSentryRequest(url: string): boolean {\n const dsn = getCurrentHub()\n .getClient()\n ?.getDsn();\n return dsn ? url.includes(dsn.host) : false;\n}\n\n/**\n * Assemble a URL to be used for breadcrumbs and spans.\n *\n * @param requestOptions RequestOptions object containing the component parts for a URL\n * @returns Fully-formed URL\n */\nexport function extractUrl(requestOptions: RequestOptions): string {\n const protocol = requestOptions.protocol || '';\n const hostname = requestOptions.hostname || requestOptions.host || '';\n // Don't log standard :80 (http) and :443 (https) ports to reduce the noise\n const port =\n !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`;\n const path = requestOptions.path ? requestOptions.path : '/';\n\n return `${protocol}//${hostname}${port}${path}`;\n}\n\n/**\n * Handle various edge cases in the span description (for spans representing http(s) requests).\n *\n * @param description current `description` property of the span representing the request\n * @param requestOptions Configuration data for the request\n * @param Request Request object\n *\n * @returns The cleaned description\n */\nexport function cleanSpanDescription(\n description: string | undefined,\n requestOptions: RequestOptions,\n request: http.ClientRequest,\n): string | undefined {\n // nothing to clean\n if (!description) {\n return description;\n }\n\n // eslint-disable-next-line prefer-const\n let [method, requestUrl] = description.split(' ');\n\n // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing,\n // we're likely dealing with an internal route and this doesn't apply)\n if (requestOptions.host && !requestOptions.protocol) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n requestOptions.protocol = (request as any)?.agent?.protocol; // worst comes to worst, this is undefined and nothing changes\n requestUrl = extractUrl(requestOptions);\n }\n\n // internal routes can end up starting with a triple slash rather than a single one\n if (requestUrl?.startsWith('///')) {\n requestUrl = requestUrl.slice(2);\n }\n\n return `${method} ${requestUrl}`;\n}\n\n// the node types are missing a few properties which node's `urlToOptions` function spits out\nexport type RequestOptions = http.RequestOptions & { hash?: string; search?: string; pathname?: string; href?: string };\ntype RequestCallback = (response: http.IncomingMessage) => void;\nexport type RequestMethodArgs =\n | [RequestOptions | string | URL, RequestCallback?]\n | [string | URL, RequestOptions, RequestCallback?];\nexport type RequestMethod = (...args: RequestMethodArgs) => http.ClientRequest;\n\n/**\n * Convert a URL object into a RequestOptions object.\n *\n * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the\n * RequestOptions type above.\n *\n * See https://github.com/nodejs/node/blob/master/lib/internal/url.js.\n */\nexport function urlToOptions(url: URL): RequestOptions {\n const options: RequestOptions = {\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `${url.pathname || ''}${url.search || ''}`,\n href: url.href,\n };\n if (url.port !== '') {\n options.port = Number(url.port);\n }\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`;\n }\n return options;\n}\n\n/**\n * Normalize inputs to `http(s).request()` and `http(s).get()`.\n *\n * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms:\n * [ RequestOptions | string | URL ],\n * [ RequestOptions | string | URL, RequestCallback ],\n * [ string | URL, RequestOptions ], and\n * [ string | URL, RequestOptions, RequestCallback ].\n *\n * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is\n * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact\n * with the args in a standard way.\n *\n * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array.\n *\n * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ].\n */\nexport function normalizeRequestArgs(\n httpModule: typeof http | typeof https,\n requestArgs: RequestMethodArgs,\n): [RequestOptions] | [RequestOptions, RequestCallback] {\n let callback, requestOptions;\n\n // pop off the callback, if there is one\n if (typeof requestArgs[requestArgs.length - 1] === 'function') {\n callback = requestArgs.pop() as RequestCallback;\n }\n\n // create a RequestOptions object of whatever's at index 0\n if (typeof requestArgs[0] === 'string') {\n requestOptions = urlToOptions(new URL(requestArgs[0]));\n } else if (requestArgs[0] instanceof URL) {\n requestOptions = urlToOptions(requestArgs[0]);\n } else {\n requestOptions = requestArgs[0];\n }\n\n // if the options were given separately from the URL, fold them in\n if (requestArgs.length === 2) {\n requestOptions = { ...requestOptions, ...requestArgs[1] };\n }\n\n // Figure out the protocol if it's currently missing\n if (requestOptions.protocol === undefined) {\n // Worst case we end up populating protocol with undefined, which it already is\n /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // Because of that, we cannot rely on `httpModule` to provide us with valid protocol,\n // as it will always return `http`, even when using `https` module.\n //\n // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n requestOptions.protocol =\n (httpModule?.globalAgent as any)?.protocol ||\n (requestOptions.agent as any)?.protocol ||\n (requestOptions._defaultAgent as any)?.protocol;\n } else {\n requestOptions.protocol =\n (requestOptions.agent as any)?.protocol ||\n (requestOptions._defaultAgent as any)?.protocol ||\n (httpModule?.globalAgent as any)?.protocol;\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */\n }\n\n // return args in standardized form\n if (callback) {\n return [requestOptions, callback];\n } else {\n return [requestOptions];\n }\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { Integration, Span } from '@sentry/types';\nimport { fill, logger, parseSemver } from '@sentry/utils';\nimport * as http from 'http';\nimport * as https from 'https';\n\nimport {\n cleanSpanDescription,\n extractUrl,\n isSentryRequest,\n normalizeRequestArgs,\n RequestMethod,\n RequestMethodArgs,\n} from './utils/http';\n\nconst NODE_VERSION = parseSemver(process.versions.node);\n\n/** http module integration */\nexport class Http implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Http';\n\n /**\n * @inheritDoc\n */\n public name: string = Http.id;\n\n /**\n * @inheritDoc\n */\n private readonly _breadcrumbs: boolean;\n\n /**\n * @inheritDoc\n */\n private readonly _tracing: boolean;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { breadcrumbs?: boolean; tracing?: boolean } = {}) {\n this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;\n this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n // No need to instrument if we don't want to track anything\n if (!this._breadcrumbs && !this._tracing) {\n return;\n }\n\n const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing);\n\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpModule = require('http');\n fill(httpModule, 'get', wrappedHandlerMaker);\n fill(httpModule, 'request', wrappedHandlerMaker);\n\n // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it.\n // If we do, we'd get double breadcrumbs and double spans for `https` calls.\n // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately.\n if (NODE_VERSION.major && NODE_VERSION.major > 8) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const httpsModule = require('https');\n fill(httpsModule, 'get', wrappedHandlerMaker);\n fill(httpsModule, 'request', wrappedHandlerMaker);\n }\n }\n}\n\n// for ease of reading below\ntype OriginalRequestMethod = RequestMethod;\ntype WrappedRequestMethod = RequestMethod;\ntype WrappedRequestMethodFactory = (original: OriginalRequestMethod) => WrappedRequestMethod;\n\n/**\n * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http`\n * and `https` modules. (NB: Not a typo - this is a creator^2!)\n *\n * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs\n * @param tracingEnabled Whether or not to record outgoing requests as tracing spans\n *\n * @returns A function which accepts the exiting handler and returns a wrapped handler\n */\nfunction _createWrappedRequestMethodFactory(\n breadcrumbsEnabled: boolean,\n tracingEnabled: boolean,\n): WrappedRequestMethodFactory {\n return function wrappedRequestMethodFactory(originalRequestMethod: OriginalRequestMethod): WrappedRequestMethod {\n return function wrappedMethod(this: typeof http | typeof https, ...args: RequestMethodArgs): http.ClientRequest {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const httpModule = this;\n\n const requestArgs = normalizeRequestArgs(this, args);\n const requestOptions = requestArgs[0];\n const requestUrl = extractUrl(requestOptions);\n\n // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method\n if (isSentryRequest(requestUrl)) {\n return originalRequestMethod.apply(httpModule, requestArgs);\n }\n\n let span: Span | undefined;\n let parentSpan: Span | undefined;\n\n const scope = getCurrentHub().getScope();\n if (scope && tracingEnabled) {\n parentSpan = scope.getSpan();\n if (parentSpan) {\n span = parentSpan.startChild({\n description: `${requestOptions.method || 'GET'} ${requestUrl}`,\n op: 'http.client',\n });\n\n const sentryTraceHeader = span.toTraceparent();\n logger.log(\n `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to ${requestUrl}: `,\n );\n requestOptions.headers = { ...requestOptions.headers, 'sentry-trace': sentryTraceHeader };\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalRequestMethod\n .apply(httpModule, requestArgs)\n .once('response', function(this: http.ClientRequest, res: http.IncomingMessage): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('response', requestUrl, req, res);\n }\n if (tracingEnabled && span) {\n if (res.statusCode) {\n span.setHttpStatus(res.statusCode);\n }\n span.description = cleanSpanDescription(span.description, requestOptions, req);\n span.finish();\n }\n })\n .once('error', function(this: http.ClientRequest): void {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const req = this;\n\n if (breadcrumbsEnabled) {\n addRequestBreadcrumb('error', requestUrl, req);\n }\n if (tracingEnabled && span) {\n span.setHttpStatus(500);\n span.description = cleanSpanDescription(span.description, requestOptions, req);\n span.finish();\n }\n });\n };\n };\n}\n\n/**\n * Captures Breadcrumb based on provided request/response pair\n */\nfunction addRequestBreadcrumb(event: string, url: string, req: http.ClientRequest, res?: http.IncomingMessage): void {\n if (!getCurrentHub().getIntegration(Http)) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: 'http',\n data: {\n method: req.method,\n status_code: res && res.statusCode,\n url,\n },\n type: 'http',\n },\n {\n event,\n request: req,\n response: res,\n },\n );\n}\n", "import { getCurrentHub } from '@sentry/core';\nimport { forget, logger } from '@sentry/utils';\n\nimport { NodeClient } from '../../client';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\n/**\n * @hidden\n */\nexport function logAndExitProcess(error: Error): void {\n // eslint-disable-next-line no-console\n console.error(error && error.stack ? error.stack : error);\n\n const client = getCurrentHub().getClient<NodeClient>();\n\n if (client === undefined) {\n logger.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n return;\n }\n\n const options = client.getOptions();\n const timeout =\n (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||\n DEFAULT_SHUTDOWN_TIMEOUT;\n forget(\n client.close(timeout).then((result: boolean) => {\n if (!result) {\n logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n }),\n );\n}\n", "import { getCurrentHub, Scope } from '@sentry/core';\nimport { Integration, Severity } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\nimport { NodeClient } from '../client';\nimport { logAndExitProcess } from './utils/errorhandling';\n\ntype OnFatalErrorHandler = (firstError: Error, secondError?: Error) => void;\n\n/** Global Promise Rejection handler */\nexport class OnUncaughtException implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'OnUncaughtException';\n\n /**\n * @inheritDoc\n */\n public name: string = OnUncaughtException.id;\n\n /**\n * @inheritDoc\n */\n public readonly handler: (error: Error) => void = this._makeErrorHandler();\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n /**\n * Default onFatalError handler\n * @param firstError Error that has been thrown\n * @param secondError If this was called multiple times this will be set\n */\n onFatalError?(firstError: Error, secondError?: Error): void;\n } = {},\n ) {}\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n global.process.on('uncaughtException', this.handler.bind(this));\n }\n\n /**\n * @hidden\n */\n private _makeErrorHandler(): (error: Error) => void {\n const timeout = 2000;\n let caughtFirstError: boolean = false;\n let caughtSecondError: boolean = false;\n let calledFatalError: boolean = false;\n let firstError: Error;\n\n return (error: Error): void => {\n let onFatalError: OnFatalErrorHandler = logAndExitProcess;\n const client = getCurrentHub().getClient<NodeClient>();\n\n if (this._options.onFatalError) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n onFatalError = this._options.onFatalError;\n } else if (client && client.getOptions().onFatalError) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n onFatalError = client.getOptions().onFatalError as OnFatalErrorHandler;\n }\n\n if (!caughtFirstError) {\n const hub = getCurrentHub();\n\n // this is the first uncaught error and the ultimate reason for shutting down\n // we want to do absolutely everything possible to ensure it gets captured\n // also we want to make sure we don't go recursion crazy if more errors happen after this one\n firstError = error;\n caughtFirstError = true;\n\n if (hub.getIntegration(OnUncaughtException)) {\n hub.withScope((scope: Scope) => {\n scope.setLevel(Severity.Fatal);\n hub.captureException(error, {\n originalException: error,\n data: { mechanism: { handled: false, type: 'onuncaughtexception' } },\n });\n if (!calledFatalError) {\n calledFatalError = true;\n onFatalError(error);\n }\n });\n } else {\n if (!calledFatalError) {\n calledFatalError = true;\n onFatalError(error);\n }\n }\n } else if (calledFatalError) {\n // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down\n logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown');\n logAndExitProcess(error);\n } else if (!caughtSecondError) {\n // two cases for how we can hit this branch:\n // - capturing of first error blew up and we just caught the exception from that\n // - quit trying to capture, proceed with shutdown\n // - a second independent error happened while waiting for first error to capture\n // - want to avoid causing premature shutdown before first error capture finishes\n // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff\n // so let's instead just delay a bit before we proceed with our action here\n // in case 1, we just wait a bit unnecessarily but ultimately do the same thing\n // in case 2, the delay hopefully made us wait long enough for the capture to finish\n // two potential nonideal outcomes:\n // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError\n // 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\n // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError)\n // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish\n caughtSecondError = true;\n setTimeout(() => {\n if (!calledFatalError) {\n // it was probably case 1, let's treat err as the sendErr and call onFatalError\n calledFatalError = true;\n onFatalError(firstError, error);\n } else {\n // it was probably case 2, our first error finished capturing while we waited, cool, do nothing\n }\n }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc\n }\n };\n }\n}\n", "import { getCurrentHub, Scope } from '@sentry/core';\nimport { Integration } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\n\nimport { logAndExitProcess } from './utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\n/** Global Promise Rejection handler */\nexport class OnUnhandledRejection implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'OnUnhandledRejection';\n\n /**\n * @inheritDoc\n */\n public name: string = OnUnhandledRejection.id;\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n } = { mode: 'warn' },\n ) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this));\n }\n\n /**\n * Send an exception with reason\n * @param reason string\n * @param promise promise\n */\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any\n public sendUnhandledPromise(reason: any, promise: any): void {\n const hub = getCurrentHub();\n\n if (!hub.getIntegration(OnUnhandledRejection)) {\n this._handleRejection(reason);\n return;\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n const context = (promise.domain && promise.domain.sentryContext) || {};\n\n hub.withScope((scope: Scope) => {\n scope.setExtra('unhandledPromiseRejection', true);\n\n // Preserve backwards compatibility with raven-node for now\n if (context.user) {\n scope.setUser(context.user);\n }\n if (context.tags) {\n scope.setTags(context.tags);\n }\n if (context.extra) {\n scope.setExtras(context.extra);\n }\n\n hub.captureException(reason, {\n originalException: promise,\n data: { mechanism: { handled: false, type: 'onunhandledrejection' } },\n });\n });\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n this._handleRejection(reason);\n }\n\n /**\n * Handler for `mode` option\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _handleRejection(reason: any): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (this._options.mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.error(reason && reason.stack ? reason.stack : reason);\n });\n } else if (this._options.mode === 'strict') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n }\n}\n", "import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { Event, EventHint, Exception, ExtendedError, Integration } from '@sentry/types';\nimport { isInstanceOf, SyncPromise } from '@sentry/utils';\n\nimport { getExceptionFromError } from '../parsers';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nexport class LinkedErrors implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'LinkedErrors';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = LinkedErrors.id;\n\n /**\n * @inheritDoc\n */\n private readonly _key: string;\n\n /**\n * @inheritDoc\n */\n private readonly _limit: number;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { key?: string; limit?: number } = {}) {\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(LinkedErrors);\n if (self) {\n const handler = self._handler && self._handler.bind(self);\n return typeof handler === 'function' ? handler(event, hint) : event;\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n private _handler(event: Event, hint?: EventHint): PromiseLike<Event> {\n if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return SyncPromise.resolve(event);\n }\n\n return new SyncPromise<Event>(resolve => {\n void this._walkErrorTree(hint.originalException as Error, this._key)\n .then((linkedErrors: Exception[]) => {\n if (event && event.exception && event.exception.values) {\n event.exception.values = [...linkedErrors, ...event.exception.values];\n }\n resolve(event);\n })\n .then(null, () => {\n resolve(event);\n });\n });\n }\n\n /**\n * @inheritDoc\n */\n private _walkErrorTree(error: ExtendedError, key: string, stack: Exception[] = []): PromiseLike<Exception[]> {\n if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) {\n return SyncPromise.resolve(stack);\n }\n return new SyncPromise<Exception[]>((resolve, reject) => {\n void getExceptionFromError(error[key])\n .then((exception: Exception) => {\n void this._walkErrorTree(error[key], key, [exception, ...stack])\n .then(resolve)\n .then(null, () => {\n reject();\n });\n })\n .then(null, () => {\n reject();\n });\n });\n }\n}\n", "import { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { existsSync, readFileSync } from 'fs';\nimport { dirname, join } from 'path';\n\nlet moduleCache: { [key: string]: string };\n\n/** Extract information about paths */\nfunction getPaths(): string[] {\n try {\n return require.cache ? Object.keys(require.cache as Record<string, unknown>) : [];\n } catch (e) {\n return [];\n }\n}\n\n/** Extract information about package.json modules */\nfunction collectModules(): {\n [name: string]: string;\n} {\n const mainPaths = (require.main && require.main.paths) || [];\n const paths = getPaths();\n const infos: {\n [name: string]: string;\n } = {};\n const seen: {\n [path: string]: boolean;\n } = {};\n\n paths.forEach(path => {\n let dir = path;\n\n /** Traverse directories upward in the search of package.json file */\n const updir = (): void | (() => void) => {\n const orig = dir;\n dir = dirname(orig);\n\n if (!dir || orig === dir || seen[orig]) {\n return undefined;\n }\n if (mainPaths.indexOf(dir) < 0) {\n return updir();\n }\n\n const pkgfile = join(orig, 'package.json');\n seen[orig] = true;\n\n if (!existsSync(pkgfile)) {\n return updir();\n }\n\n try {\n const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as {\n name: string;\n version: string;\n };\n infos[info.name] = info.version;\n } catch (_oO) {\n // no-empty\n }\n };\n\n updir();\n });\n\n return infos;\n}\n\n/** Add node modules / packages to the event */\nexport class Modules implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Modules';\n\n /**\n * @inheritDoc\n */\n public name: string = Modules.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n if (!getCurrentHub().getIntegration(Modules)) {\n return event;\n }\n return {\n ...event,\n modules: this._getModules(),\n };\n });\n }\n\n /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */\n private _getModules(): { [key: string]: string } {\n if (!moduleCache) {\n moduleCache = collectModules();\n }\n return moduleCache;\n }\n}\n", "export { Console } from './console';\nexport { Http } from './http';\nexport { OnUncaughtException } from './onuncaughtexception';\nexport { OnUnhandledRejection } from './onunhandledrejection';\nexport { LinkedErrors } from './linkederrors';\nexport { Modules } from './modules';\n", "import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';\nimport { getMainCarrier, setHubOnCarrier } from '@sentry/hub';\nimport { SessionStatus } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\nimport * as domain from 'domain';\n\nimport { NodeClient } from './client';\nimport { Console, Http, LinkedErrors, OnUncaughtException, OnUnhandledRejection } from './integrations';\nimport { NodeOptions } from './types';\n\nexport const defaultIntegrations = [\n // Common\n new CoreIntegrations.InboundFilters(),\n new CoreIntegrations.FunctionToString(),\n // Native Wrappers\n new Console(),\n new Http(),\n // Global Handlers\n new OnUncaughtException(),\n new OnUnhandledRejection(),\n // Misc\n new LinkedErrors(),\n];\n\n/**\n * The Sentry Node SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible in the\n * main entry module. To set context information or send manual events, use the\n * provided methods.\n *\n * @example\n * ```\n *\n * const { init } = require('@sentry/node');\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { configureScope } = require('@sentry/node');\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\n * });\n * ```\n *\n * @example\n * ```\n *\n * const { addBreadcrumb } = require('@sentry/node');\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * const Sentry = require('@sentry/node');\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link NodeOptions} for documentation on configuration options.\n */\nexport function init(options: NodeOptions = {}): void {\n const carrier = getMainCarrier();\n const autoloadedIntegrations = carrier.__SENTRY__?.integrations || [];\n\n options.defaultIntegrations =\n options.defaultIntegrations === false\n ? []\n : [\n ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations),\n ...autoloadedIntegrations,\n ];\n\n if (options.dsn === undefined && process.env.SENTRY_DSN) {\n options.dsn = process.env.SENTRY_DSN;\n }\n\n if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) {\n const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE);\n if (isFinite(tracesSampleRate)) {\n options.tracesSampleRate = tracesSampleRate;\n }\n }\n\n if (options.release === undefined) {\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n options.release = detectedRelease;\n } else {\n // If release is not provided, then we should disable autoSessionTracking\n options.autoSessionTracking = false;\n }\n }\n\n if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) {\n options.environment = process.env.SENTRY_ENVIRONMENT;\n }\n\n if (options.autoSessionTracking === undefined && options.dsn !== undefined) {\n options.autoSessionTracking = true;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if ((domain as any).active) {\n setHubOnCarrier(carrier, getCurrentHub());\n }\n\n initAndBind(NodeClient, options);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nexport function lastEventId(): string | undefined {\n return getCurrentHub().lastEventId();\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise<boolean> {\n const client = getCurrentHub().getClient<NodeClient>();\n if (client) {\n return client.flush(timeout);\n }\n logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise<boolean> {\n const client = getCurrentHub().getClient<NodeClient>();\n if (client) {\n return client.close(timeout);\n }\n logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client\n */\nexport function isAutoSessionTrackingEnabled(client?: NodeClient): boolean {\n if (client === undefined) {\n return false;\n }\n const clientOptions: NodeOptions = client && client.getOptions();\n if (clientOptions && clientOptions.autoSessionTracking !== undefined) {\n return clientOptions.autoSessionTracking;\n }\n return false;\n}\n\n/**\n * Returns a release dynamically from environment variables.\n */\nexport function getSentryRelease(fallback?: string): string | undefined {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n const global = getGlobalObject();\n if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) {\n return global.SENTRY_RELEASE.id;\n }\n\n return (\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env.GITHUB_SHA ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env.COMMIT_REF ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.VERCEL_GITHUB_COMMIT_SHA ||\n process.env.VERCEL_GITLAB_COMMIT_SHA ||\n process.env.VERCEL_BITBUCKET_COMMIT_SHA ||\n // Zeit (now known as Vercel)\n process.env.ZEIT_GITHUB_COMMIT_SHA ||\n process.env.ZEIT_GITLAB_COMMIT_SHA ||\n process.env.ZEIT_BITBUCKET_COMMIT_SHA ||\n fallback\n );\n}\n\n/**\n * Enable automatic Session Tracking for the node process.\n */\nfunction startSessionTracking(): void {\n const hub = getCurrentHub();\n hub.startSession();\n // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because\n // The 'beforeExit' event is not emitted for conditions causing explicit termination,\n // such as calling process.exit() or uncaught exceptions.\n // Ref: https://nodejs.org/api/process.html#process_event_beforeexit\n process.on('beforeExit', () => {\n const session = hub.getScope()?.getSession();\n const terminalStates = [SessionStatus.Exited, SessionStatus.Crashed];\n // Only call endSession, if the Session exists on Scope and SessionStatus is not a\n // Terminal Status i.e. Exited or Crashed because\n // \"When a session is moved away from ok it must not be updated anymore.\"\n // Ref: https://develop.sentry.dev/sdk/sessions/\n if (session && !terminalStates.includes(session.status)) hub.endSession();\n });\n}\n", "import * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Recursively read the contents of a directory.\n *\n * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this\n * directory.\n * @returns Array holding all relative paths\n */\nexport function deepReadDirSync(targetDir: string): string[] {\n const targetDirAbsPath = path.resolve(targetDir);\n\n if (!fs.existsSync(targetDirAbsPath)) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`);\n }\n\n if (!fs.statSync(targetDirAbsPath).isDirectory()) {\n throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`);\n }\n\n // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it\n // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve\n // the difference between `targetDirAbsPath` and `currentDirAbsPath`.\n const deepReadCurrentDir = (currentDirAbsPath: string): string[] => {\n return fs.readdirSync(currentDirAbsPath).reduce((absPaths: string[], itemName: string) => {\n const itemAbsPath = path.join(currentDirAbsPath, itemName);\n\n if (fs.statSync(itemAbsPath).isDirectory()) {\n return [...absPaths, ...deepReadCurrentDir(itemAbsPath)];\n }\n\n return [...absPaths, itemAbsPath];\n }, []);\n };\n\n return deepReadCurrentDir(targetDirAbsPath).map(absPath => path.relative(targetDirAbsPath, absPath));\n}\n", "/** The status of an Span. */\n// eslint-disable-next-line import/export\nexport enum SpanStatus {\n /** The operation completed successfully. */\n Ok = 'ok',\n /** Deadline expired before operation could complete. */\n DeadlineExceeded = 'deadline_exceeded',\n /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */\n Unauthenticated = 'unauthenticated',\n /** 403 Forbidden */\n PermissionDenied = 'permission_denied',\n /** 404 Not Found. Some requested entity (file or directory) was not found. */\n NotFound = 'not_found',\n /** 429 Too Many Requests */\n ResourceExhausted = 'resource_exhausted',\n /** Client specified an invalid argument. 4xx. */\n InvalidArgument = 'invalid_argument',\n /** 501 Not Implemented */\n Unimplemented = 'unimplemented',\n /** 503 Service Unavailable */\n Unavailable = 'unavailable',\n /** Other/generic 5xx. */\n InternalError = 'internal_error',\n /** Unknown. Any non-standard HTTP status code. */\n UnknownError = 'unknown_error',\n /** The operation was cancelled (typically by the user). */\n Cancelled = 'cancelled',\n /** Already exists (409) */\n AlreadyExists = 'already_exists',\n /** Operation was rejected because the system is not in a state required for the operation's */\n FailedPrecondition = 'failed_precondition',\n /** The operation was aborted, typically due to a concurrency issue. */\n Aborted = 'aborted',\n /** Operation was attempted past the valid range. */\n OutOfRange = 'out_of_range',\n /** Unrecoverable data loss or corruption */\n DataLoss = 'data_loss',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace, import/export\nexport namespace SpanStatus {\n /**\n * Converts a HTTP status code into a {@link SpanStatus}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or {@link SpanStatus.UnknownError}.\n */\n export function fromHttpCode(httpStatus: number): SpanStatus {\n if (httpStatus < 400 && httpStatus >= 100) {\n return SpanStatus.Ok;\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return SpanStatus.Unauthenticated;\n case 403:\n return SpanStatus.PermissionDenied;\n case 404:\n return SpanStatus.NotFound;\n case 409:\n return SpanStatus.AlreadyExists;\n case 413:\n return SpanStatus.FailedPrecondition;\n case 429:\n return SpanStatus.ResourceExhausted;\n default:\n return SpanStatus.InvalidArgument;\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return SpanStatus.Unimplemented;\n case 503:\n return SpanStatus.Unavailable;\n case 504:\n return SpanStatus.DeadlineExceeded;\n default:\n return SpanStatus.InternalError;\n }\n }\n\n return SpanStatus.UnknownError;\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport { Options, TraceparentData, Transaction } from '@sentry/types';\n\nexport const TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nexport function hasTracingEnabled(\n options: Options | undefined = getCurrentHub()\n .getClient()\n ?.getOptions(),\n): boolean {\n return !!options && ('tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nexport function extractTraceparentData(traceparent: string): TraceparentData | undefined {\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (matches) {\n let parentSampled: boolean | undefined;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n }\n return undefined;\n}\n\n/** Grabs active transaction off scope, if any */\nexport function getActiveTransaction<T extends Transaction>(hub: Hub = getCurrentHub()): T | undefined {\n return hub?.getScope()?.getTransaction() as T | undefined;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nexport function msToSec(time: number): number {\n return time / 1000;\n}\n\n/**\n * Converts from seconds to milliseconds\n * @param time time in seconds\n */\nexport function secToMs(time: number): number {\n return time * 1000;\n}\n\n// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\n", "import { addInstrumentationHandler, logger } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation(): void {\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'error',\n });\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'unhandledrejection',\n });\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback(): void {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n logger.log(`[Tracing] Transaction: ${SpanStatus.InternalError} -> Global error occured`);\n activeTransaction.setStatus(SpanStatus.InternalError);\n }\n}\n", "// Store finish reasons in tuple to save on bundle size\n// Readonly type should enforce that this is not mutated.\nexport const FINISH_REASON_TAG = 'finishReason';\n\nexport const IDLE_TRANSACTION_FINISH_REASONS = ['heartbeatFailed', 'idleTimeout', 'documentHidden'] as const;\n", "/* eslint-disable max-lines */\nimport { Primitive, Span as SpanInterface, SpanContext, Transaction } from '@sentry/types';\nimport { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils';\n\nimport { SpanStatus } from './spanstatus';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nexport class SpanRecorder {\n public spans: Span[] = [];\n\n private readonly _maxlen: number;\n\n public constructor(maxlen: number = 1000) {\n this._maxlen = maxlen;\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n public add(span: Span): void {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nexport class Span implements SpanInterface {\n /**\n * @inheritDoc\n */\n public traceId: string = uuid4();\n\n /**\n * @inheritDoc\n */\n public spanId: string = uuid4().substring(16);\n\n /**\n * @inheritDoc\n */\n public parentSpanId?: string;\n\n /**\n * Internal keeper of the status\n */\n public status?: SpanStatus | string;\n\n /**\n * @inheritDoc\n */\n public sampled?: boolean;\n\n /**\n * Timestamp in seconds when the span was created.\n */\n public startTimestamp: number = timestampWithMs();\n\n /**\n * Timestamp in seconds when the span ended.\n */\n public endTimestamp?: number;\n\n /**\n * @inheritDoc\n */\n public op?: string;\n\n /**\n * @inheritDoc\n */\n public description?: string;\n\n /**\n * @inheritDoc\n */\n public tags: { [key: string]: Primitive } = {};\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public data: { [key: string]: any } = {};\n\n /**\n * List of spans that were finalized\n */\n public spanRecorder?: SpanRecorder;\n\n /**\n * @inheritDoc\n */\n public transaction?: Transaction;\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(spanContext?: SpanContext) {\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n\n /**\n * @inheritDoc\n * @deprecated\n */\n public child(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): Span {\n return this.startChild(spanContext);\n }\n\n /**\n * @inheritDoc\n */\n public startChild(\n spanContext?: Pick<SpanContext, Exclude<keyof SpanContext, 'spanId' | 'sampled' | 'traceId' | 'parentSpanId'>>,\n ): Span {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n public setData(key: string, value: any): this {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setStatus(value: SpanStatus): this {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setHttpStatus(httpStatus: number): this {\n this.setTag('http.status_code', String(httpStatus));\n const spanStatus = SpanStatus.fromHttpCode(httpStatus);\n if (spanStatus !== SpanStatus.UnknownError) {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public isSuccess(): boolean {\n return this.status === SpanStatus.Ok;\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): void {\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n }\n\n /**\n * @inheritDoc\n */\n public toTraceparent(): string {\n let sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return `${this.traceId}-${this.spanId}${sampledString}`;\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): SpanContext {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(spanContext: SpanContext): this {\n this.data = spanContext.data ?? {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId ?? this.spanId;\n this.startTimestamp = spanContext.startTimestamp ?? this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags ?? {};\n this.traceId = spanContext.traceId ?? this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getTraceContext(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n status?: string;\n tags?: { [key: string]: Primitive };\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n public toJSON(): {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data?: { [key: string]: any };\n description?: string;\n op?: string;\n parent_span_id?: string;\n span_id: string;\n start_timestamp: number;\n status?: string;\n tags?: { [key: string]: Primitive };\n timestamp?: number;\n trace_id: string;\n } {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n }\n}\n", "import { getCurrentHub, Hub } from '@sentry/hub';\nimport {\n Event,\n Measurements,\n Outcome,\n Transaction as TransactionInterface,\n TransactionContext,\n TransactionMetadata,\n} from '@sentry/types';\nimport { dropUndefinedKeys, isInstanceOf, logger } from '@sentry/utils';\n\nimport { Span as SpanClass, SpanRecorder } from './span';\n\n/** JSDoc */\nexport class Transaction extends SpanClass implements TransactionInterface {\n public name: string;\n\n public metadata: TransactionMetadata;\n\n private _measurements: Measurements = {};\n\n /**\n * The reference to the current hub.\n */\n private readonly _hub: Hub = (getCurrentHub() as unknown) as Hub;\n\n private _trimEnd?: boolean;\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n public constructor(transactionContext: TransactionContext, hub?: Hub) {\n super(transactionContext);\n\n if (isInstanceOf(hub, Hub)) {\n this._hub = hub as Hub;\n }\n\n this.name = transactionContext.name || '';\n\n this.metadata = transactionContext.metadata || {};\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n }\n\n /**\n * JSDoc\n */\n public setName(name: string): void {\n this.name = name;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n public initSpanRecorder(maxlen: number = 1000): void {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Set observed measurements for this transaction.\n * @hidden\n */\n public setMeasurements(measurements: Measurements): void {\n this._measurements = { ...measurements };\n }\n\n /**\n * Set metadata for this transaction.\n * @hidden\n */\n public setMetadata(newMetadata: TransactionMetadata): void {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n public finish(endTimestamp?: number): string | undefined {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');\n this.name = '<unlabeled transaction>';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n this._hub\n .getClient()\n ?.getTransport?.()\n .recordLostEvent?.(Outcome.SampleRate, 'transaction');\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const transaction: Event = {\n contexts: {\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n debug_meta: this.metadata,\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2));\n transaction.measurements = this._measurements;\n }\n\n logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n public toContext(): TransactionContext {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n public updateWithContext(transactionContext: TransactionContext): this {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name ?? '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { TransactionContext } from '@sentry/types';\nimport { logger, timestampWithMs } from '@sentry/utils';\n\nimport { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from './constants';\nimport { Span, SpanRecorder } from './span';\nimport { SpanStatus } from './spanstatus';\nimport { Transaction } from './transaction';\n\nexport const DEFAULT_IDLE_TIMEOUT = 1000;\nexport const HEARTBEAT_INTERVAL = 5000;\n\n/**\n * @inheritDoc\n */\nexport class IdleTransactionSpanRecorder extends SpanRecorder {\n public constructor(\n private readonly _pushActivity: (id: string) => void,\n private readonly _popActivity: (id: string) => void,\n public transactionSpanId: string = '',\n maxlen?: number,\n ) {\n super(maxlen);\n }\n\n /**\n * @inheritDoc\n */\n public add(span: Span): void {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp?: number) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\nexport type BeforeFinishCallback = (transactionSpan: IdleTransaction, endTimestamp: number) => void;\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nexport class IdleTransaction extends Transaction {\n // Activities store a list of active spans\n public activities: Record<string, boolean> = {};\n\n // Track state of activities in previous heartbeat\n private _prevHeartbeatString: string | undefined;\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n private _heartbeatCounter: number = 0;\n\n // We should not use heartbeat if we finished a transaction\n private _finished: boolean = false;\n\n private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = [];\n\n /**\n * If a transaction is created and no activities are added, we want to make sure that\n * it times out properly. This is cleared and not used when activities are added.\n */\n private _initTimeout: ReturnType<typeof setTimeout> | undefined;\n\n public constructor(\n transactionContext: TransactionContext,\n private readonly _idleHub?: Hub,\n /**\n * The time to wait in ms until the idle transaction will be finished.\n * @default 1000\n */\n private readonly _idleTimeout: number = DEFAULT_IDLE_TIMEOUT,\n // If an idle transaction should be put itself on and off the scope automatically.\n private readonly _onScope: boolean = false,\n ) {\n super(transactionContext, _idleHub);\n\n if (_idleHub && _onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._initTimeout = setTimeout(() => {\n if (!this._finished) {\n this.finish();\n }\n }, this._idleTimeout);\n }\n\n /** {@inheritDoc} */\n public finish(endTimestamp: number = timestampWithMs()): string | undefined {\n this._finished = true;\n this.activities = {};\n\n if (this.spanRecorder) {\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus(SpanStatus.Cancelled);\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n logger.log(\n '[Tracing] discarding Span since it happened after Transaction was finished',\n JSON.stringify(span, undefined, 2),\n );\n }\n return keepSpan;\n });\n\n logger.log('[Tracing] flushing IdleTransaction');\n } else {\n logger.log('[Tracing] No active IdleTransaction');\n }\n\n // this._onScope is true if the transaction was previously on the scope.\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n public registerBeforeFinishCallback(callback: BeforeFinishCallback): void {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public initSpanRecorder(maxlen?: number): void {\n if (!this.spanRecorder) {\n const pushActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id: string): void => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n private _pushActivity(spanId: string): void {\n if (this._initTimeout) {\n clearTimeout(this._initTimeout);\n this._initTimeout = undefined;\n }\n logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n private _popActivity(spanId: string): void {\n if (this.activities[spanId]) {\n logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const timeout = this._idleTimeout;\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n const end = timestampWithMs() + timeout / 1000;\n\n setTimeout(() => {\n if (!this._finished) {\n this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[1]);\n this.finish(end);\n }\n }, timeout);\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n private _beat(): void {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter += 1;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n logger.log(`[Tracing] Transaction finished because of no change for 3 heart beats`);\n this.setStatus(SpanStatus.DeadlineExceeded);\n this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]);\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n private _pingHeartbeat(): void {\n logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, HEARTBEAT_INTERVAL);\n }\n}\n\n/**\n * Reset active transaction on scope\n */\nfunction clearActiveTransaction(hub?: Hub): void {\n if (hub) {\n const scope = hub.getScope();\n if (scope) {\n const transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n }\n}\n", "import { getMainCarrier, Hub } from '@sentry/hub';\nimport {\n CustomSamplingContext,\n Integration,\n IntegrationClass,\n Options,\n SamplingContext,\n TransactionContext,\n TransactionSamplingMethod,\n} from '@sentry/types';\nimport { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils';\n\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\nimport { hasTracingEnabled } from './utils';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders(this: Hub): { [key: string]: string } {\n const scope = this.getScope();\n if (scope) {\n const span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param hub: The hub off of which to read config options\n * @param transaction: The transaction needing a sampling decision\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample<T extends Transaction>(transaction: T, options: Options, samplingContext: SamplingContext): T {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Explicit },\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Sampler,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Inheritance },\n });\n } else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Rate,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n logger.warn(`[Tracing] Discarding transaction because of invalid sample rate.`);\n transaction.sampled = false;\n return transaction;\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate as number | boolean);\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate: unknown): boolean {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n this: Hub,\n transactionContext: TransactionContext,\n customSamplingContext?: CustomSamplingContext,\n): Transaction {\n const options = this.getClient()?.getOptions() || {};\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(\n hub: Hub,\n transactionContext: TransactionContext,\n idleTimeout?: number,\n onScope?: boolean,\n customSamplingContext?: CustomSamplingContext,\n): IdleTransaction {\n const options = hub.getClient()?.getOptions() || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, onScope);\n transaction = sample(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments?.maxSpans as number);\n }\n return transaction;\n}\n\n/**\n * @private\n */\nexport function _addTracingExtensions(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations(): void {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n\n const packageToIntegrationMapping: Record<string, () => Integration> = {\n mongodb() {\n const integration = dynamicRequire(module, './integrations/node/mongo') as {\n Mongo: IntegrationClass<Integration>;\n };\n return new integration.Mongo();\n },\n mongoose() {\n const integration = dynamicRequire(module, './integrations/node/mongo') as {\n Mongo: IntegrationClass<Integration>;\n };\n return new integration.Mongo({ mongoose: true });\n },\n mysql() {\n const integration = dynamicRequire(module, './integrations/node/mysql') as {\n Mysql: IntegrationClass<Integration>;\n };\n return new integration.Mysql();\n },\n pg() {\n const integration = dynamicRequire(module, './integrations/node/postgres') as {\n Postgres: IntegrationClass<Integration>;\n };\n return new integration.Postgres();\n },\n };\n\n const mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(moduleName => !!loadModule(moduleName))\n .map(pkg => {\n try {\n return packageToIntegrationMapping[pkg]();\n } catch (e) {\n return undefined;\n }\n })\n .filter(p => p) as Integration[];\n\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = [...(carrier.__SENTRY__.integrations || []), ...mappedPackages];\n }\n}\n\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nexport function addExtensionMethods(): void {\n _addTracingExtensions();\n\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n\n // If an error happens globally, we should make sure transaction status is set to error.\n registerErrorInstrumentation();\n}\n", "import { Integration, Transaction } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\ntype Method =\n | 'all'\n | 'get'\n | 'post'\n | 'put'\n | 'delete'\n | 'patch'\n | 'options'\n | 'head'\n | 'checkout'\n | 'copy'\n | 'lock'\n | 'merge'\n | 'mkactivity'\n | 'mkcol'\n | 'move'\n | 'm-search'\n | 'notify'\n | 'purge'\n | 'report'\n | 'search'\n | 'subscribe'\n | 'trace'\n | 'unlock'\n | 'unsubscribe'\n | 'use';\n\ntype Router = {\n [method in Method]: (...args: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any\n};\n\ninterface ExpressResponse {\n once(name: string, callback: () => void): void;\n}\n\n/**\n * Internal helper for `__sentry_transaction`\n * @hidden\n */\ninterface SentryTracingResponse {\n __sentry_transaction?: Transaction;\n}\n\n/**\n * Express integration\n *\n * Provides an request and error handler for Express framework as well as tracing capabilities\n */\nexport class Express implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Express';\n\n /**\n * @inheritDoc\n */\n public name: string = Express.id;\n\n /**\n * Express App instance\n */\n private readonly _router?: Router;\n private readonly _methods?: Method[];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { app?: Router; router?: Router; methods?: Method[] } = {}) {\n this._router = options.router || options.app;\n this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use');\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(): void {\n if (!this._router) {\n logger.error('ExpressIntegration is missing an Express instance');\n return;\n }\n instrumentMiddlewares(this._router, this._methods);\n }\n}\n\n/**\n * Wraps original middleware function in a tracing call, which stores the info about the call as a span,\n * and finishes it once the middleware is done invoking.\n *\n * Express middlewares have 3 various forms, thus we have to take care of all of them:\n * // sync\n * app.use(function (req, res) { ... })\n * // async\n * app.use(function (req, res, next) { ... })\n * // error handler\n * app.use(function (err, req, res, next) { ... })\n *\n * They all internally delegate to the `router[method]` of the given application instance.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any\nfunction wrap(fn: Function, method: Method): (...args: any[]) => void {\n const arity = fn.length;\n\n switch (arity) {\n case 2: {\n return function(this: NodeJS.Global, req: unknown, res: ExpressResponse & SentryTracingResponse): void {\n const transaction = res.__sentry_transaction;\n if (transaction) {\n const span = transaction.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n res.once('finish', () => {\n span.finish();\n });\n }\n return fn.call(this, req, res);\n };\n }\n case 3: {\n return function(\n this: NodeJS.Global,\n req: unknown,\n res: ExpressResponse & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n const span = transaction?.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n fn.call(this, req, res, function(this: NodeJS.Global, ...args: unknown[]): void {\n span?.finish();\n next.call(this, ...args);\n });\n };\n }\n case 4: {\n return function(\n this: NodeJS.Global,\n err: Error,\n req: Request,\n res: Response & SentryTracingResponse,\n next: () => void,\n ): void {\n const transaction = res.__sentry_transaction;\n const span = transaction?.startChild({\n description: fn.name,\n op: `express.middleware.${method}`,\n });\n fn.call(this, err, req, res, function(this: NodeJS.Global, ...args: unknown[]): void {\n span?.finish();\n next.call(this, ...args);\n });\n };\n }\n default: {\n throw new Error(`Express middleware takes 2-4 arguments. Got: ${arity}`);\n }\n }\n}\n\n/**\n * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use`\n * and wraps every function, as well as array of functions with a call to our `wrap` method.\n * We have to take care of the arrays as well as iterate over all of the arguments,\n * as `app.use` can accept middlewares in few various forms.\n *\n * app.use([<path>], <fn>)\n * app.use([<path>], <fn>, ...<fn>)\n * app.use([<path>], ...<fn>[])\n */\nfunction wrapMiddlewareArgs(args: unknown[], method: Method): unknown[] {\n return args.map((arg: unknown) => {\n if (typeof arg === 'function') {\n return wrap(arg, method);\n }\n\n if (Array.isArray(arg)) {\n return arg.map((a: unknown) => {\n if (typeof a === 'function') {\n return wrap(a, method);\n }\n return a;\n });\n }\n\n return arg;\n });\n}\n\n/**\n * Patches original router to utilize our tracing functionality\n */\nfunction patchMiddleware(router: Router, method: Method): Router {\n const originalCallback = router[method];\n\n router[method] = function(...args: unknown[]): void {\n return originalCallback.call(this, ...wrapMiddlewareArgs(args, method));\n };\n\n return router;\n}\n\n/**\n * Patches original router methods\n */\nfunction instrumentMiddlewares(router: Router, methods: Method[] = []): void {\n methods.forEach((method: Method) => patchMiddleware(router, method));\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\ninterface PgClient {\n prototype: {\n query: () => void | Promise<unknown>;\n };\n}\n\ninterface PgOptions {\n usePgNative?: boolean;\n}\n\n/** Tracing integration for node-postgres package */\nexport class Postgres implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Postgres';\n\n /**\n * @inheritDoc\n */\n public name: string = Postgres.id;\n\n private _usePgNative: boolean;\n\n public constructor(options: PgOptions = {}) {\n this._usePgNative = !!options.usePgNative;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const pkg = loadModule<{ Client: PgClient; native: { Client: PgClient } }>('pg');\n\n if (!pkg) {\n logger.error('Postgres Integration was unable to require `pg` package.');\n return;\n }\n\n if (this._usePgNative && !pkg.native?.Client) {\n logger.error(`Postgres Integration was unable to access 'pg-native' bindings.`);\n return;\n }\n\n const { Client } = this._usePgNative ? pkg.native : pkg;\n\n /**\n * function (query, callback) => void\n * function (query, params, callback) => void\n * function (query) => Promise\n * function (query, params) => Promise\n * function (pg.Cursor) => pg.Cursor\n */\n fill(Client.prototype, 'query', function(orig: () => void | Promise<unknown>) {\n return function(this: unknown, config: unknown, values: unknown, callback: unknown) {\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n const span = parentSpan?.startChild({\n description: typeof config === 'string' ? config : (config as { text: string }).text,\n op: `db`,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, config, values, function(err: Error, result: unknown) {\n span?.finish();\n callback(err, result);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, config, function(err: Error, result: unknown) {\n span?.finish();\n values(err, result);\n });\n }\n\n const rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config);\n\n if (isThenable(rv)) {\n return (rv as Promise<unknown>).then((res: unknown) => {\n span?.finish();\n return res;\n });\n }\n\n span?.finish();\n return rv;\n };\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration } from '@sentry/types';\nimport { fill, loadModule, logger } from '@sentry/utils';\n\ninterface MysqlConnection {\n createQuery: () => void;\n}\n\n/** Tracing integration for node-mysql package */\nexport class Mysql implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mysql';\n\n /**\n * @inheritDoc\n */\n public name: string = Mysql.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const pkg = loadModule<MysqlConnection>('mysql/lib/Connection.js');\n\n if (!pkg) {\n logger.error('Mysql Integration was unable to require `mysql` package.');\n return;\n }\n\n // The original function will have one of these signatures:\n // function (callback) => void\n // function (options, callback) => void\n // function (options, values, callback) => void\n fill(pkg, 'createQuery', function(orig: () => void) {\n return function(this: unknown, options: unknown, values: unknown, callback: unknown) {\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n const span = parentSpan?.startChild({\n description: typeof options === 'string' ? options : (options as { sql: string }).sql,\n op: `db`,\n });\n\n if (typeof callback === 'function') {\n return orig.call(this, options, values, function(err: Error, result: unknown, fields: unknown) {\n span?.finish();\n callback(err, result, fields);\n });\n }\n\n if (typeof values === 'function') {\n return orig.call(this, options, function(err: Error, result: unknown, fields: unknown) {\n span?.finish();\n values(err, result, fields);\n });\n }\n\n return orig.call(this, options, values, callback);\n };\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration, SpanContext } from '@sentry/types';\nimport { fill, isThenable, loadModule, logger } from '@sentry/utils';\n\n// This allows us to use the same array for both defaults options and the type itself.\n// (note `as const` at the end to make it a union of string literal types (i.e. \"a\" | \"b\" | ... )\n// and not just a string[])\ntype Operation = typeof OPERATIONS[number];\nconst OPERATIONS = [\n 'aggregate', // aggregate(pipeline, options, callback)\n 'bulkWrite', // bulkWrite(operations, options, callback)\n 'countDocuments', // countDocuments(query, options, callback)\n 'createIndex', // createIndex(fieldOrSpec, options, callback)\n 'createIndexes', // createIndexes(indexSpecs, options, callback)\n 'deleteMany', // deleteMany(filter, options, callback)\n 'deleteOne', // deleteOne(filter, options, callback)\n 'distinct', // distinct(key, query, options, callback)\n 'drop', // drop(options, callback)\n 'dropIndex', // dropIndex(indexName, options, callback)\n 'dropIndexes', // dropIndexes(options, callback)\n 'estimatedDocumentCount', // estimatedDocumentCount(options, callback)\n 'find', // find(query, options, callback)\n 'findOne', // findOne(query, options, callback)\n 'findOneAndDelete', // findOneAndDelete(filter, options, callback)\n 'findOneAndReplace', // findOneAndReplace(filter, replacement, options, callback)\n 'findOneAndUpdate', // findOneAndUpdate(filter, update, options, callback)\n 'indexes', // indexes(options, callback)\n 'indexExists', // indexExists(indexes, options, callback)\n 'indexInformation', // indexInformation(options, callback)\n 'initializeOrderedBulkOp', // initializeOrderedBulkOp(options, callback)\n 'insertMany', // insertMany(docs, options, callback)\n 'insertOne', // insertOne(doc, options, callback)\n 'isCapped', // isCapped(options, callback)\n 'mapReduce', // mapReduce(map, reduce, options, callback)\n 'options', // options(options, callback)\n 'parallelCollectionScan', // parallelCollectionScan(options, callback)\n 'rename', // rename(newName, options, callback)\n 'replaceOne', // replaceOne(filter, doc, options, callback)\n 'stats', // stats(options, callback)\n 'updateMany', // updateMany(filter, update, options, callback)\n 'updateOne', // updateOne(filter, update, options, callback)\n] as const;\n\n// All of the operations above take `options` and `callback` as their final parameters, but some of them\n// take additional parameters as well. For those operations, this is a map of\n// { <operation name>: [<names of additional parameters>] }, as a way to know what to call the operation's\n// positional arguments when we add them to the span's `data` object later\nconst OPERATION_SIGNATURES: {\n [op in Operation]?: string[];\n} = {\n // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well\n // see https://github.com/getsentry/sentry-javascript/pull/3102\n bulkWrite: ['operations'],\n countDocuments: ['query'],\n createIndex: ['fieldOrSpec'],\n createIndexes: ['indexSpecs'],\n deleteMany: ['filter'],\n deleteOne: ['filter'],\n distinct: ['key', 'query'],\n dropIndex: ['indexName'],\n find: ['query'],\n findOne: ['query'],\n findOneAndDelete: ['filter'],\n findOneAndReplace: ['filter', 'replacement'],\n findOneAndUpdate: ['filter', 'update'],\n indexExists: ['indexes'],\n insertMany: ['docs'],\n insertOne: ['doc'],\n mapReduce: ['map', 'reduce'],\n rename: ['newName'],\n replaceOne: ['filter', 'doc'],\n updateMany: ['filter', 'update'],\n updateOne: ['filter', 'update'],\n};\n\ninterface MongoCollection {\n collectionName: string;\n dbName: string;\n namespace: string;\n prototype: {\n [operation in Operation]: (...args: unknown[]) => unknown;\n };\n}\n\ninterface MongoOptions {\n operations?: Operation[];\n describeOperations?: boolean | Operation[];\n useMongoose?: boolean;\n}\n\n/** Tracing integration for mongo package */\nexport class Mongo implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Mongo';\n\n /**\n * @inheritDoc\n */\n public name: string = Mongo.id;\n\n private _operations: Operation[];\n private _describeOperations?: boolean | Operation[];\n private _useMongoose: boolean;\n\n /**\n * @inheritDoc\n */\n public constructor(options: MongoOptions = {}) {\n this._operations = Array.isArray(options.operations)\n ? options.operations\n : ((OPERATIONS as unknown) as Operation[]);\n this._describeOperations = 'describeOperations' in options ? options.describeOperations : true;\n this._useMongoose = !!options.useMongoose;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n const moduleName = this._useMongoose ? 'mongoose' : 'mongodb';\n const pkg = loadModule<{ Collection: MongoCollection }>(moduleName);\n\n if (!pkg) {\n logger.error(`Mongo Integration was unable to require \\`${moduleName}\\` package.`);\n return;\n }\n\n this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub);\n }\n\n /**\n * Patches original collection methods\n */\n private _instrumentOperations(collection: MongoCollection, operations: Operation[], getCurrentHub: () => Hub): void {\n operations.forEach((operation: Operation) => this._patchOperation(collection, operation, getCurrentHub));\n }\n\n /**\n * Patches original collection to utilize our tracing functionality\n */\n private _patchOperation(collection: MongoCollection, operation: Operation, getCurrentHub: () => Hub): void {\n if (!(operation in collection.prototype)) return;\n\n const getSpanContext = this._getSpanContextFromOperationArguments.bind(this);\n\n fill(collection.prototype, operation, function(orig: () => void | Promise<unknown>) {\n return function(this: unknown, ...args: unknown[]) {\n const lastArg = args[args.length - 1];\n const scope = getCurrentHub().getScope();\n const parentSpan = scope?.getSpan();\n\n // Check if the operation was passed a callback. (mapReduce requires a different check, as\n // its (non-callback) arguments can also be functions.)\n if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) {\n const span = parentSpan?.startChild(getSpanContext(this, operation, args));\n const maybePromise = orig.call(this, ...args) as Promise<unknown>;\n\n if (isThenable(maybePromise)) {\n return maybePromise.then((res: unknown) => {\n span?.finish();\n return res;\n });\n } else {\n span?.finish();\n return maybePromise;\n }\n }\n\n const span = parentSpan?.startChild(getSpanContext(this, operation, args.slice(0, -1)));\n return orig.call(this, ...args.slice(0, -1), function(err: Error, result: unknown) {\n span?.finish();\n lastArg(err, result);\n });\n };\n });\n }\n\n /**\n * Form a SpanContext based on the user input to a given operation.\n */\n private _getSpanContextFromOperationArguments(\n collection: MongoCollection,\n operation: Operation,\n args: unknown[],\n ): SpanContext {\n const data: { [key: string]: string } = {\n collectionName: collection.collectionName,\n dbName: collection.dbName,\n namespace: collection.namespace,\n };\n const spanContext: SpanContext = {\n op: `db`,\n description: operation,\n data,\n };\n\n // If the operation takes no arguments besides `options` and `callback`, or if argument\n // collection is disabled for this operation, just return early.\n const signature = OPERATION_SIGNATURES[operation];\n const shouldDescribe = Array.isArray(this._describeOperations)\n ? this._describeOperations.includes(operation)\n : this._describeOperations;\n\n if (!signature || !shouldDescribe) {\n return spanContext;\n }\n\n try {\n // Special case for `mapReduce`, as the only one accepting functions as arguments.\n if (operation === 'mapReduce') {\n const [map, reduce] = args as { name?: string }[];\n data[signature[0]] = typeof map === 'string' ? map : map.name || '<anonymous>';\n data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || '<anonymous>';\n } else {\n for (let i = 0; i < signature.length; i++) {\n data[signature[i]] = JSON.stringify(args[i]);\n }\n }\n } catch (_oO) {\n // no-empty\n }\n\n return spanContext;\n }\n}\n", "import { getGlobalObject, logger } from '@sentry/utils';\n\nimport { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants';\nimport { IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction } from '../utils';\n\nconst global = getGlobalObject<Window>();\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nexport function registerBackgroundTabDetection(): void {\n if (global && global.document) {\n global.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() as IdleTransaction;\n if (global.document.hidden && activeTransaction) {\n logger.log(\n `[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background, op: ${activeTransaction.op}`,\n );\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!activeTransaction.status) {\n activeTransaction.setStatus(SpanStatus.Cancelled);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]);\n activeTransaction.finish();\n }\n });\n } else {\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric, ReportHandler } from '../types';\n\nexport const bindReporter = (\n callback: ReportHandler,\n metric: Metric,\n reportAllChanges?: boolean,\n): ((forceReport?: boolean) => void) => {\n let prevValue: number;\n return (forceReport?: boolean) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n metric.delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (metric.delta || prevValue === undefined) {\n prevValue = metric.value;\n callback(metric);\n }\n }\n }\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nexport const generateUniqueID = (): string => {\n return `v2-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Metric } from '../types';\nimport { generateUniqueID } from './generateUniqueID';\n\nexport const initMetric = (name: Metric['name'], value?: number): Metric => {\n return {\n name,\n value: value ?? -1,\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface PerformanceEntryHandler {\n (entry: PerformanceEntry): void;\n}\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nexport const observe = (type: string, callback: PerformanceEntryHandler): PerformanceObserver | undefined => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n // More extensive feature detect needed for Firefox due to:\n // https://github.com/GoogleChrome/web-vitals/issues/142\n if (type === 'first-input' && !('PerformanceEventTiming' in self)) {\n return;\n }\n\n const po: PerformanceObserver = new PerformanceObserver(l => l.getEntries().map(callback));\n\n po.observe({ type, buffered: true });\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nexport interface OnHiddenCallback {\n (event: Event): void;\n}\n\nexport const onHidden = (cb: OnHiddenCallback, once?: boolean): void => {\n const onHiddenOrPageHide = (event: Event): void => {\n if (event.type === 'pagehide' || getGlobalObject<Window>().document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/layout-instability/#sec-layout-shift\nexport interface LayoutShift extends PerformanceEntry {\n value: number;\n hadRecentInput: boolean;\n sources: Array<LayoutShiftAttribution>;\n toJSON(): Record<string, unknown>;\n}\n\nexport interface LayoutShiftAttribution {\n node?: Node;\n previousRect: DOMRectReadOnly;\n currentRect: DOMRectReadOnly;\n}\n\nexport const getCLS = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const metric = initMetric('CLS', 0);\n let report: ReturnType<typeof bindReporter>;\n\n let sessionValue = 0;\n let sessionEntries: PerformanceEntry[] = [];\n\n const entryHandler = (entry: LayoutShift): void => {\n // Only count layout shifts without recent user input.\n // TODO: Figure out why entry can be undefined\n if (entry && !entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n if (report) {\n report();\n }\n }\n }\n };\n\n const po = observe('layout-shift', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n report(true);\n });\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobalObject } from '@sentry/utils';\n\nimport { onHidden } from './onHidden';\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = (): number => {\n return getGlobalObject<Window>().document.visibilityState === 'hidden' ? 0 : Infinity;\n};\n\nconst trackChanges = (): void => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nexport const getVisibilityWatcher = (): {\n readonly firstHiddenTime: number;\n} => {\n if (firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { PerformanceEventTiming, ReportHandler } from './types';\n\nexport const getFID = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n let report: ReturnType<typeof bindReporter>;\n\n const entryHandler = (entry: PerformanceEventTiming): void => {\n // Only report if the page wasn't hidden prior to the first input.\n if (report && entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const po = observe('first-input', entryHandler as PerformanceEntryHandler);\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n onHidden(() => {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n }, true);\n }\n};\n", "/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { bindReporter } from './lib/bindReporter';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher';\nimport { initMetric } from './lib/initMetric';\nimport { observe, PerformanceEntryHandler } from './lib/observe';\nimport { onHidden } from './lib/onHidden';\nimport { ReportHandler } from './types';\n\n// https://wicg.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface\nexport interface LargestContentfulPaint extends PerformanceEntry {\n renderTime: DOMHighResTimeStamp;\n loadTime: DOMHighResTimeStamp;\n size: number;\n id: string;\n url: string;\n element?: Element;\n toJSON(): Record<string, string>;\n}\n\nconst reportedMetricIDs: Record<string, boolean> = {};\n\nexport const getLCP = (onReport: ReportHandler, reportAllChanges?: boolean): void => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report: ReturnType<typeof bindReporter>;\n\n const entryHandler = (entry: PerformanceEntry): void => {\n // The startTime attribute returns the value of the renderTime if it is not 0,\n // and the value of the loadTime otherwise.\n const value = entry.startTime;\n\n // If the page was hidden prior to paint time of the entry,\n // ignore it and mark the metric as final, otherwise add the entry.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries.push(entry);\n }\n\n if (report) {\n report();\n }\n };\n\n const po = observe('largest-contentful-paint', entryHandler);\n\n if (po) {\n report = bindReporter(onReport, metric, reportAllChanges);\n\n const stopListening = (): void => {\n if (!reportedMetricIDs[metric.id]) {\n po.takeRecords().map(entryHandler as PerformanceEntryHandler);\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n };\n\n // Stop listening after input. Note: while scrolling is an input that\n // stop LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n }\n};\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Measurements, SpanContext } from '@sentry/types';\nimport { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNodeEnv, logger } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { Transaction } from '../transaction';\nimport { msToSec } from '../utils';\nimport { getCLS, LayoutShift } from './web-vitals/getCLS';\nimport { getFID } from './web-vitals/getFID';\nimport { getLCP, LargestContentfulPaint } from './web-vitals/getLCP';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher';\nimport { NavigatorDeviceMemory, NavigatorNetworkInformation } from './web-vitals/types';\n\nconst global = getGlobalObject<Window>();\n\n/** Class tracking metrics */\nexport class MetricsInstrumentation {\n private _measurements: Measurements = {};\n\n private _performanceCursor: number = 0;\n private _lcpEntry: LargestContentfulPaint | undefined;\n private _clsEntry: LayoutShift | undefined;\n\n public constructor(private _reportAllChanges: boolean = false) {\n if (!isNodeEnv() && global?.performance && global?.document) {\n if (global.performance.mark) {\n global.performance.mark('sentry-tracing-init');\n }\n\n this._trackCLS();\n this._trackLCP();\n this._trackFID();\n }\n }\n\n /** Add performance related spans to a transaction */\n public addPerformanceEntries(transaction: Transaction): void {\n if (!global || !global.performance || !global.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n logger.log('[Tracing] Adding & adjusting spans using Performance API');\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n let entryScriptSrc: string | undefined;\n\n if (global.document && global.document.scripts) {\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < global.document.scripts.length; i++) {\n // We go through all scripts on the page and look for 'data-entry'\n // We remember the name and measure the time between this script finished loading and\n // our mark 'sentry-tracing-init'\n if (global.document.scripts[i].dataset.entry === 'true') {\n entryScriptSrc = global.document.scripts[i].src;\n break;\n }\n }\n }\n\n let entryScriptStartTimestamp: number | undefined;\n let tracingInitMarkStartTime: number | undefined;\n let responseStartTimestamp: number | undefined;\n let requestStartTimestamp: number | undefined;\n\n global.performance\n .getEntries()\n .slice(this._performanceCursor)\n .forEach((entry: Record<string, any>) => {\n const startTime = msToSec(entry.startTime as number);\n const duration = msToSec(entry.duration as number);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart as number);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart as number);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n const startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);\n if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') {\n tracingInitMarkStartTime = startTimestamp;\n }\n\n // capture web vitals\n\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FP');\n this._measurements['fp'] = { value: entry.startTime };\n this._measurements['mark.fp'] = { value: startTimestamp };\n }\n\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n logger.log('[Measurements] Adding FCP');\n this._measurements['fcp'] = { value: entry.startTime };\n this._measurements['mark.fcp'] = { value: startTimestamp };\n }\n\n break;\n }\n case 'resource': {\n const resourceName = (entry.name as string).replace(global.location.origin, '');\n const endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);\n // We remember the entry script end time to calculate the difference to the first init mark\n if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) {\n entryScriptStartTimestamp = endTimestamp;\n }\n break;\n }\n default:\n // Ignore other entry types.\n }\n });\n\n if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) {\n _startChild(transaction, {\n description: 'evaluation',\n endTimestamp: tracingInitMarkStartTime,\n op: 'script',\n startTimestamp: entryScriptStartTimestamp,\n });\n }\n\n this._performanceCursor = Math.max(performance.getEntries().length - 1, 0);\n\n this._trackNavigator(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // normalize applicable web vital values to be relative to transaction.startTimestamp\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n logger.log('[Measurements] Adding TTFB');\n this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!this._measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n\n const oldValue = this._measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n\n const delta = normalizedValue - oldValue;\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n\n this._measurements[name].value = normalizedValue;\n });\n\n if (this._measurements['mark.fid'] && this._measurements['fid']) {\n // create span for FID\n\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: this._measurements['mark.fid'].value + msToSec(this._measurements['fid'].value),\n op: 'web.vitals',\n startTimestamp: this._measurements['mark.fid'].value,\n });\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n if (!('fcp' in this._measurements)) {\n delete this._measurements.cls;\n }\n\n transaction.setMeasurements(this._measurements);\n this._tagMetricInfo(transaction);\n\n transaction.setTag('sentry_reportAllChanges', this._reportAllChanges);\n }\n }\n\n /** Add LCP / CLS data to transaction to allow debugging */\n private _tagMetricInfo(transaction: Transaction): void {\n if (this._lcpEntry) {\n logger.log('[Measurements] Adding LCP Data');\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (this._lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(this._lcpEntry.element));\n }\n\n if (this._lcpEntry.id) {\n transaction.setTag('lcp.id', this._lcpEntry.id);\n }\n\n if (this._lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', this._lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (this._clsEntry && this._clsEntry.sources) {\n logger.log('[Measurements] Adding CLS Data');\n this._clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n }\n\n /** Starts tracking the Cumulative Layout Shift on the current page. */\n private _trackCLS(): void {\n // See:\n // https://web.dev/evolving-cls/\n // https://web.dev/cls-web-tooling/\n getCLS(metric => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n logger.log('[Measurements] Adding CLS');\n this._measurements['cls'] = { value: metric.value };\n this._clsEntry = entry as LayoutShift;\n });\n }\n\n /**\n * Capture the information of the user agent.\n */\n private _trackNavigator(transaction: Transaction): void {\n const navigator = global.navigator as null | (Navigator & NavigatorNetworkInformation & NavigatorDeviceMemory);\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n this._measurements['connection.rtt'] = { value: connection.rtt as number };\n }\n\n if (isMeasurementValue(connection.downlink)) {\n this._measurements['connection.downlink'] = { value: connection.downlink as number };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n transaction.setTag('deviceMemory', String(navigator.deviceMemory));\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n }\n\n /** Starts tracking the Largest Contentful Paint on the current page. */\n private _trackLCP(): void {\n getLCP(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding LCP');\n this._measurements['lcp'] = { value: metric.value };\n this._measurements['mark.lcp'] = { value: timeOrigin + startTime };\n this._lcpEntry = entry as LargestContentfulPaint;\n }, this._reportAllChanges);\n }\n\n /** Starts tracking the First Input Delay on the current page. */\n private _trackFID(): void {\n getFID(metric => {\n const entry = metric.entries.pop();\n\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin as number);\n const startTime = msToSec(entry.startTime as number);\n logger.log('[Measurements] Adding FID');\n this._measurements['fid'] = { value: metric.value };\n this._measurements['mark.fid'] = { value: timeOrigin + startTime };\n });\n }\n}\n\n/** Instrument navigation entries */\nfunction addNavigationSpans(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n addPerformanceNavigationTiming({ transaction, entry, event: 'unloadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'redirect', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domContentLoadedEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'loadEvent', timeOrigin });\n addPerformanceNavigationTiming({ transaction, entry, event: 'connect', timeOrigin });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'secureConnection',\n timeOrigin,\n eventEnd: 'connectEnd',\n description: 'TLS/SSL',\n });\n addPerformanceNavigationTiming({\n transaction,\n entry,\n event: 'fetch',\n timeOrigin,\n eventEnd: 'domainLookupStart',\n description: 'cache',\n });\n addPerformanceNavigationTiming({ transaction, entry, event: 'domainLookup', timeOrigin, description: 'DNS' });\n addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create measure related spans */\nfunction addMeasureSpans(\n transaction: Transaction,\n entry: Record<string, any>,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name as string,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType as string,\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\nexport interface ResourceEntry extends Record<string, unknown> {\n initiatorType?: string;\n transferSize?: number;\n encodedBodySize?: number;\n decodedBodySize?: number;\n}\n\n/** Create resource-related spans */\nexport function addResourceSpans(\n transaction: Transaction,\n entry: ResourceEntry,\n resourceName: string,\n startTime: number,\n duration: number,\n timeOrigin: number,\n): number | undefined {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return undefined;\n }\n\n const data: Record<string, any> = {};\n if ('transferSize' in entry) {\n data['Transfer Size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['Encoded Body Size'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['Decoded Body Size'] = entry.decodedBodySize;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource',\n startTimestamp,\n data,\n });\n\n return endTimestamp;\n}\n\n/** Create performance navigation related spans */\nfunction addPerformanceNavigationTiming(props: {\n transaction: Transaction;\n entry: Record<string, any>;\n event: string;\n timeOrigin: number;\n eventEnd?: string;\n description?: string;\n}): void {\n const { transaction, entry, event, timeOrigin, eventEnd, description } = props;\n\n const end = eventEnd ? (entry[eventEnd] as number | undefined) : (entry[`${event}End`] as number | undefined);\n const start = entry[`${event}Start`] as number | undefined;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n description: description ?? event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\nfunction addRequest(transaction: Transaction, entry: Record<string, any>, timeOrigin: number): void {\n _startChild(transaction, {\n op: 'browser',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n\n _startChild(transaction, {\n op: 'browser',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart as number),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd as number),\n });\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nexport function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value: any): boolean {\n return typeof value === 'number' && isFinite(value);\n}\n", "import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils';\n\nimport { Span } from '../span';\nimport { SpanStatus } from '../spanstatus';\nimport { getActiveTransaction, hasTracingEnabled } from '../utils';\n\nexport const DEFAULT_TRACING_ORIGINS = ['localhost', /^\\//];\n\n/** Options for Request Instrumentation */\nexport interface RequestInstrumentationOptions {\n /**\n * List of strings / regex where the integration should create Spans out of. Additionally this will be used\n * to define which outgoing requests the `sentry-trace` header will be attached to.\n *\n * Default: ['localhost', /^\\//] {@see DEFAULT_TRACING_ORIGINS}\n */\n tracingOrigins: Array<string | RegExp>;\n\n /**\n * Flag to disable patching all together for fetch requests.\n *\n * Default: true\n */\n traceFetch: boolean;\n\n /**\n * Flag to disable patching all together for xhr requests.\n *\n * Default: true\n */\n traceXHR: boolean;\n\n /**\n * This function will be called before creating a span for a request with the given url.\n * Return false if you don't want a span for the given url.\n *\n * By default it uses the `tracingOrigins` options as a url match.\n */\n shouldCreateSpanForRequest?(url: string): boolean;\n}\n\n/** Data returned from fetch callback */\nexport interface FetchData {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[]; // the arguments passed to the fetch call itself\n fetchData?: {\n method: string;\n url: string;\n // span_id\n __span?: string;\n };\n\n // TODO Should this be unknown instead? If we vendor types, make it a Response\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n response?: any;\n error?: unknown;\n\n startTimestamp: number;\n endTimestamp?: number;\n}\n\n/** Data returned from XHR request */\nexport interface XHRData {\n xhr?: {\n __sentry_xhr__?: {\n method: string;\n url: string;\n status_code: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data: Record<string, any>;\n };\n __sentry_xhr_span_id__?: string;\n setRequestHeader?: (key: string, val: string) => void;\n __sentry_own_request__?: boolean;\n };\n startTimestamp: number;\n endTimestamp?: number;\n}\n\nexport const defaultRequestInstrumentationOptions: RequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n tracingOrigins: DEFAULT_TRACING_ORIGINS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nexport function instrumentOutgoingRequests(_options?: Partial<RequestInstrumentationOptions>): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest } = {\n ...defaultRequestInstrumentationOptions,\n ..._options,\n };\n\n // We should cache url -> decision so that we don't have to compute\n // regexp everytime we create a request.\n const urlMap: Record<string, boolean> = {};\n\n const defaultShouldCreateSpan = (url: string): boolean => {\n if (urlMap[url]) {\n return urlMap[url];\n }\n const origins = tracingOrigins;\n urlMap[url] =\n origins.some((origin: string | RegExp) => isMatchingPattern(url, origin)) &&\n !isMatchingPattern(url, 'sentry_key');\n return urlMap[url];\n };\n\n // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves\n // That's why we filter out already unwanted Spans from tracingOrigins\n let shouldCreateSpan = defaultShouldCreateSpan;\n if (typeof shouldCreateSpanForRequest === 'function') {\n shouldCreateSpan = (url: string) => {\n return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url);\n };\n }\n\n const spans: Record<string, Span> = {};\n\n if (traceFetch) {\n addInstrumentationHandler({\n callback: (handlerData: FetchData) => {\n fetchCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'fetch',\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler({\n callback: (handlerData: XHRData) => {\n xhrCallback(handlerData, shouldCreateSpan, spans);\n },\n type: 'xhr',\n });\n }\n}\n\n/**\n * Create and track fetch request spans\n */\nexport function fetchCallback(\n handlerData: FetchData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record<string, Span>,\n): void {\n if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {\n return;\n }\n\n if (handlerData.endTimestamp && handlerData.fetchData.__span) {\n const span = spans[handlerData.fetchData.__span];\n if (span) {\n if (handlerData.response) {\n // TODO (kmclb) remove this once types PR goes through\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n span.setHttpStatus(handlerData.response.status);\n } else if (handlerData.error) {\n span.setStatus(SpanStatus.InternalError);\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.fetchData.__span];\n }\n return;\n }\n\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...handlerData.fetchData,\n type: 'fetch',\n },\n description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`,\n op: 'http.client',\n });\n\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n\n const request = (handlerData.args[0] = handlerData.args[0] as string | Request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {});\n let headers = options.headers;\n if (isInstanceOf(request, Request)) {\n headers = (request as Request).headers;\n }\n if (headers) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (typeof headers.append === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n headers.append('sentry-trace', span.toTraceparent());\n } else if (Array.isArray(headers)) {\n headers = [...headers, ['sentry-trace', span.toTraceparent()]];\n } else {\n headers = { ...headers, 'sentry-trace': span.toTraceparent() };\n }\n } else {\n headers = { 'sentry-trace': span.toTraceparent() };\n }\n options.headers = headers;\n }\n}\n\n/**\n * Create and track xhr request spans\n */\nexport function xhrCallback(\n handlerData: XHRData,\n shouldCreateSpan: (url: string) => boolean,\n spans: Record<string, Span>,\n): void {\n if (\n !hasTracingEnabled() ||\n handlerData.xhr?.__sentry_own_request__ ||\n !(handlerData.xhr?.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))\n ) {\n return;\n }\n\n const xhr = handlerData.xhr.__sentry_xhr__;\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) {\n const span = spans[handlerData.xhr.__sentry_xhr_span_id__];\n if (span) {\n span.setHttpStatus(xhr.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[handlerData.xhr.__sentry_xhr_span_id__];\n }\n return;\n }\n\n // if not, create a new span to track it\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const span = activeTransaction.startChild({\n data: {\n ...xhr.data,\n type: 'xhr',\n method: xhr.method,\n url: xhr.url,\n },\n description: `${xhr.method} ${xhr.url}`,\n op: 'http.client',\n });\n\n handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[handlerData.xhr.__sentry_xhr_span_id__] = span;\n\n if (handlerData.xhr.setRequestHeader) {\n try {\n handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent());\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n }\n }\n}\n", "import { Transaction, TransactionContext } from '@sentry/types';\nimport { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils';\n\nconst global = getGlobalObject<Window>();\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nexport function instrumentRoutingWithDefaults<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad: boolean = true,\n startTransactionOnLocationChange: boolean = true,\n): void {\n if (!global || !global.location) {\n logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl: string | undefined = global.location.href;\n\n let activeTransaction: T | undefined;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'pageload' });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler({\n callback: ({ to, from }: { to: string; from?: string }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'navigation' });\n }\n },\n type: 'history',\n });\n }\n}\n", "import { Hub } from '@sentry/hub';\nimport { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\nimport { startIdleTransaction } from '../hubextensions';\nimport { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction';\nimport { SpanStatus } from '../spanstatus';\nimport { extractTraceparentData, secToMs } from '../utils';\nimport { registerBackgroundTabDetection } from './backgroundtab';\nimport { MetricsInstrumentation } from './metrics';\nimport {\n defaultRequestInstrumentationOptions,\n instrumentOutgoingRequests,\n RequestInstrumentationOptions,\n} from './request';\nimport { instrumentRoutingWithDefaults } from './router';\n\nexport const DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;\n\n/** Options for Browser Tracing integration */\nexport interface BrowserTracingOptions extends RequestInstrumentationOptions {\n /**\n * The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of\n * the last finished span as the endtime for the transaction.\n * Time is in ms.\n *\n * Default: 1000\n */\n idleTimeout: number;\n\n /**\n * Flag to enable/disable creation of `navigation` transaction on history changes.\n *\n * Default: true\n */\n startTransactionOnLocationChange: boolean;\n\n /**\n * Flag to enable/disable creation of `pageload` transaction on first pageload.\n *\n * Default: true\n */\n startTransactionOnPageLoad: boolean;\n\n /**\n * The maximum duration of a transaction before it will be marked as \"deadline_exceeded\".\n * If you never want to mark a transaction set it to 0.\n * Time is in seconds.\n *\n * Default: 600\n */\n maxTransactionDuration: number;\n\n /**\n * Flag Transactions where tabs moved to background with \"cancelled\". Browser background tab timing is\n * not suited towards doing precise measurements of operations. By default, we recommend that this option\n * be enabled as background transactions can mess up your statistics in nondeterministic ways.\n *\n * Default: true\n */\n markBackgroundTransactions: boolean;\n\n /**\n * _metricOptions allows the user to send options to change how metrics are collected.\n *\n * _metricOptions is currently experimental.\n *\n * Default: undefined\n */\n _metricOptions?: Partial<{ _reportAllChanges: boolean }>;\n\n /**\n * beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction\n * context data, or drop the transaction entirely (by setting `sampled = false` in the context).\n *\n * Note: For legacy reasons, transactions can also be dropped by returning `undefined`.\n *\n * @param context: The context data which will be passed to `startTransaction` by default\n *\n * @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.\n */\n beforeNavigate?(context: TransactionContext): TransactionContext | undefined;\n\n /**\n * Instrumentation that creates routing change transactions. By default creates\n * pageload and navigation transactions.\n */\n routingInstrumentation<T extends Transaction>(\n customStartTransaction: (context: TransactionContext) => T | undefined,\n startTransactionOnPageLoad?: boolean,\n startTransactionOnLocationChange?: boolean,\n ): void;\n}\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n idleTimeout: DEFAULT_IDLE_TIMEOUT,\n markBackgroundTransactions: true,\n maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library. This integration uses {@see IdleTransaction} to create transactions.\n */\nexport class BrowserTracing implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'BrowserTracing';\n\n /** Browser Tracing integration options */\n public options: BrowserTracingOptions;\n\n /**\n * @inheritDoc\n */\n public name: string = BrowserTracing.id;\n\n private _getCurrentHub?: () => Hub;\n\n private readonly _metrics: MetricsInstrumentation;\n\n private readonly _emitOptionsWarning: boolean = false;\n\n /** Store configured idle timeout so that it can be added as a tag to transactions */\n private _configuredIdleTimeout: BrowserTracingOptions['idleTimeout'] | undefined = undefined;\n\n public constructor(_options?: Partial<BrowserTracingOptions>) {\n let tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;\n // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances\n if (_options) {\n this._configuredIdleTimeout = _options.idleTimeout;\n if (_options.tracingOrigins && Array.isArray(_options.tracingOrigins) && _options.tracingOrigins.length !== 0) {\n tracingOrigins = _options.tracingOrigins;\n } else {\n this._emitOptionsWarning = true;\n }\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n tracingOrigins,\n };\n\n const { _metricOptions } = this.options;\n this._metrics = new MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges);\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this._getCurrentHub = getCurrentHub;\n\n if (this._emitOptionsWarning) {\n logger.warn(\n '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.',\n );\n logger.warn(\n `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`,\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n tracingOrigins,\n shouldCreateSpanForRequest,\n } = this.options;\n\n instrumentRouting(\n (context: TransactionContext) => this._createRouteTransaction(context),\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n instrumentOutgoingRequests({ traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest });\n }\n\n /** Create routing idle transaction. */\n private _createRouteTransaction(context: TransactionContext): Transaction | undefined {\n if (!this._getCurrentHub) {\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;\n\n const parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined;\n\n const expandedContext = {\n ...context,\n ...parentContextFromHeader,\n trimEnd: true,\n };\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n if (finalContext.sampled === false) {\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const hub = this._getCurrentHub();\n const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location };\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n true,\n { location }, // for use in the tracesSampler\n );\n idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {\n this._metrics.addPerformanceEntries(transaction);\n adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);\n });\n\n idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout);\n\n return idleTransaction as Transaction;\n }\n}\n\n/**\n * Gets transaction context from a sentry-trace meta.\n *\n * @returns Transaction context data from the header or undefined if there's no header or the header is malformed\n */\nexport function getHeaderContext(): Partial<TransactionContext> | undefined {\n const header = getMetaContent('sentry-trace');\n if (header) {\n return extractTraceparentData(header);\n }\n\n return undefined;\n}\n\n/** Returns the value of a meta tag */\nexport function getMetaContent(metaName: string): string | null {\n const el = getGlobalObject<Window>().document.querySelector(`meta[name=${metaName}]`);\n return el ? el.getAttribute('content') : null;\n}\n\n/** Adjusts transaction value based on max transaction duration */\nfunction adjustTransactionDuration(maxDuration: number, transaction: IdleTransaction, endTimestamp: number): void {\n const diff = endTimestamp - transaction.startTimestamp;\n const isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0);\n if (isOutdatedTransaction) {\n transaction.setStatus(SpanStatus.DeadlineExceeded);\n transaction.setTag('maxTransactionDurationExceeded', 'true');\n }\n}\n", "export { BrowserTracing } from './browsertracing';\nexport {\n instrumentOutgoingRequests,\n RequestInstrumentationOptions,\n defaultRequestInstrumentationOptions,\n} from './request';\n", "export { Express } from './node/express';\nexport { Postgres } from './node/postgres';\nexport { Mysql } from './node/mysql';\nexport { Mongo } from './node/mongo';\n\n// TODO(v7): Remove this export\n// Please see `src/index.ts` for more details.\nexport { BrowserTracing } from '../browser';\n", "import { addExtensionMethods } from './hubextensions';\nimport * as Integrations from './integrations';\n\nexport { Integrations };\n\n// This is already exported as part of `Integrations` above (and for the moment will remain so for\n// backwards compatibility), but that interferes with treeshaking, so we also export it separately\n// here.\n//\n// Previously we expected users to import tracing integrations like\n//\n// import { Integrations } from '@sentry/tracing';\n// const instance = new Integrations.BrowserTracing();\n//\n// This makes the integrations unable to be treeshaken though. To address this, we now have\n// this individual export. We now expect users to consume BrowserTracing like so:\n//\n// import { BrowserTracing } from '@sentry/tracing';\n// const instance = new BrowserTracing();\n//\n// For an example of of the new usage of BrowserTracing, see @sentry/nextjs index.client.ts\nexport { BrowserTracing } from './browser';\n\nexport { Span } from './span';\nexport { Transaction } from './transaction';\nexport {\n // TODO deprecate old name in v7\n instrumentOutgoingRequests as registerRequestInstrumentation,\n RequestInstrumentationOptions,\n defaultRequestInstrumentationOptions,\n} from './browser';\nexport { SpanStatus } from './spanstatus';\nexport { IdleTransaction } from './idletransaction';\nexport { startIdleTransaction } from './hubextensions';\n\n// We are patching the global object with our hub extension methods\naddExtensionMethods();\n\nexport { addExtensionMethods };\n\nexport {\n extractTraceparentData,\n getActiveTransaction,\n hasTracingEnabled,\n stripUrlQueryAndFragment,\n TRACEPARENT_REGEXP,\n} from './utils';\n", "/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar decode = decodeURIComponent;\nvar encode = encodeURIComponent;\nvar pairSplitRegExp = /; */;\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var pairs = str.split(pairSplitRegExp);\n var dec = opt.decode || decode;\n\n for (var i = 0; i < pairs.length; i++) {\n var pair = pairs[i];\n var eq_idx = pair.indexOf('=');\n\n // skip things that don't look like key=value\n if (eq_idx < 0) {\n continue;\n }\n\n var key = pair.substr(0, eq_idx).trim()\n var val = pair.substr(++eq_idx, pair.length).trim();\n\n // quoted values\n if ('\"' == val[0]) {\n val = val.slice(1, -1);\n }\n\n // only assign once\n if (undefined == obj[key]) {\n obj[key] = tryDecode(val, dec);\n }\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n if (typeof opt.expires.toUTCString !== 'function') {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { captureException, getCurrentHub, startTransaction, withScope } from '@sentry/core';\nimport { extractTraceparentData, Span } from '@sentry/tracing';\nimport { Event, ExtractedNodeRequestData, RequestSessionStatus, Transaction } from '@sentry/types';\nimport { isPlainObject, isString, logger, normalize, stripUrlQueryAndFragment } from '@sentry/utils';\nimport * as cookie from 'cookie';\nimport * as domain from 'domain';\nimport * as http from 'http';\nimport * as os from 'os';\nimport * as url from 'url';\n\nimport { NodeClient } from './client';\nimport { flush, isAutoSessionTrackingEnabled } from './sdk';\n\nexport interface ExpressRequest {\n baseUrl?: string;\n connection?: {\n remoteAddress?: string;\n };\n ip?: string;\n method?: string;\n originalUrl?: string;\n route?: {\n path: string;\n stack: [\n {\n name: string;\n },\n ];\n };\n query?: {\n // It can be: undefined | string | string[] | ParsedQs | ParsedQs[] (from `qs` package), but we dont want to pull it.\n [key: string]: unknown;\n };\n url?: string;\n user?: {\n [key: string]: any;\n };\n}\n\n/**\n * Express-compatible tracing handler.\n * @see Exposed as `Handlers.tracingHandler`\n */\nexport function tracingHandler(): (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n) => void {\n return function sentryTracingMiddleware(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n ): void {\n // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision)\n let traceparentData;\n if (req.headers && isString(req.headers['sentry-trace'])) {\n traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string);\n }\n\n const transaction = startTransaction(\n {\n name: extractExpressTransactionName(req, { path: true, method: true }),\n op: 'http.server',\n ...traceparentData,\n },\n // extra context passed to the tracesSampler\n { request: extractRequestData(req) },\n );\n\n // We put the transaction on the scope so users can attach children to it\n getCurrentHub().configureScope(scope => {\n scope.setSpan(transaction);\n });\n\n // We also set __sentry_transaction on the response so people can grab the transaction there to add\n // spans to it later.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res as any).__sentry_transaction = transaction;\n\n res.once('finish', () => {\n // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction\n // closes\n setImmediate(() => {\n addExpressReqToTransaction(transaction, req);\n transaction.setHttpStatus(res.statusCode);\n transaction.finish();\n });\n });\n\n next();\n };\n}\n\n/**\n * Set parameterized as transaction name e.g.: `GET /users/:id`\n * Also adds more context data on the transaction from the request\n */\nfunction addExpressReqToTransaction(transaction: Transaction | undefined, req: ExpressRequest): void {\n if (!transaction) return;\n transaction.name = extractExpressTransactionName(req, { path: true, method: true });\n transaction.setData('url', req.originalUrl);\n transaction.setData('baseUrl', req.baseUrl);\n transaction.setData('query', req.query);\n}\n\n/**\n * Extracts complete generalized path from the request object and uses it to construct transaction name.\n *\n * eg. GET /mountpoint/user/:id\n *\n * @param req The ExpressRequest object\n * @param options What to include in the transaction name (method, path, or both)\n *\n * @returns The fully constructed transaction name\n */\nfunction extractExpressTransactionName(\n req: ExpressRequest,\n options: { path?: boolean; method?: boolean } = {},\n): string {\n const method = req.method?.toUpperCase();\n\n let path = '';\n if (req.route) {\n path = `${req.baseUrl || ''}${req.route.path}`;\n } else if (req.originalUrl || req.url) {\n path = stripUrlQueryAndFragment(req.originalUrl || req.url || '');\n }\n\n let info = '';\n if (options.method && method) {\n info += method;\n }\n if (options.method && options.path) {\n info += ` `;\n }\n if (options.path && path) {\n info += path;\n }\n\n return info;\n}\n\ntype TransactionNamingScheme = 'path' | 'methodPath' | 'handler';\n\n/** JSDoc */\nfunction extractTransaction(req: ExpressRequest, type: boolean | TransactionNamingScheme): string {\n switch (type) {\n case 'path': {\n return extractExpressTransactionName(req, { path: true });\n }\n case 'handler': {\n return req.route?.stack[0].name || '<anonymous>';\n }\n case 'methodPath':\n default: {\n return extractExpressTransactionName(req, { path: true, method: true });\n }\n }\n}\n\n/** Default user keys that'll be used to extract data from the request */\nconst DEFAULT_USER_KEYS = ['id', 'username', 'email'];\n\n/** JSDoc */\nfunction extractUserData(\n user: {\n [key: string]: any;\n },\n keys: boolean | string[],\n): { [key: string]: any } {\n const extractedUser: { [key: string]: any } = {};\n const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;\n\n attributes.forEach(key => {\n if (user && key in user) {\n extractedUser[key] = user[key];\n }\n });\n\n return extractedUser;\n}\n\n/** Default request keys that'll be used to extract data from the request */\nconst DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];\n\n/**\n * Normalizes data from the request object, accounting for framework differences.\n *\n * @param req The request object from which to extract data\n * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not\n * provided.\n * @returns An object containing normalized request data\n */\nexport function extractRequestData(\n req: { [key: string]: any },\n keys: string[] = DEFAULT_REQUEST_KEYS,\n): ExtractedNodeRequestData {\n const requestData: { [key: string]: any } = {};\n\n // headers:\n // node, express, nextjs: req.headers\n // koa: req.header\n const headers = (req.headers || req.header || {}) as {\n host?: string;\n cookie?: string;\n };\n // method:\n // node, express, koa, nextjs: req.method\n const method = req.method;\n // host:\n // express: req.hostname in > 4 and req.host in < 4\n // koa: req.host\n // node, nextjs: req.headers.host\n const host = req.hostname || req.host || headers.host || '<no host>';\n // protocol:\n // node, nextjs: <n/a>\n // express, koa: req.protocol\n const protocol =\n req.protocol === 'https' || req.secure || ((req.socket || {}) as { encrypted?: boolean }).encrypted\n ? 'https'\n : 'http';\n // url (including path and query string):\n // node, express: req.originalUrl\n // koa, nextjs: req.url\n const originalUrl = (req.originalUrl || req.url || '') as string;\n // absolute url\n const absoluteUrl = `${protocol}://${host}${originalUrl}`;\n\n keys.forEach(key => {\n switch (key) {\n case 'headers':\n requestData.headers = headers;\n break;\n case 'method':\n requestData.method = method;\n break;\n case 'url':\n requestData.url = absoluteUrl;\n break;\n case 'cookies':\n // cookies:\n // node, express, koa: req.headers.cookie\n // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.cookies = req.cookies || cookie.parse(headers.cookie || '');\n break;\n case 'query_string':\n // query string:\n // node: req.url (raw)\n // express, koa, nextjs: req.query\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n requestData.query_string = req.query || url.parse(originalUrl || '', false).query;\n break;\n case 'data':\n if (method === 'GET' || method === 'HEAD') {\n break;\n }\n // body data:\n // express, koa, nextjs: req.body\n //\n // when using node by itself, you have to read the incoming stream(see\n // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know\n // where they're going to store the final result, so they'll have to capture this data themselves\n if (req.body !== undefined) {\n requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));\n }\n break;\n default:\n if ({}.hasOwnProperty.call(req, key)) {\n requestData[key] = (req as { [key: string]: any })[key];\n }\n }\n });\n\n return requestData;\n}\n\n/**\n * Options deciding what parts of the request to use when enhancing an event\n */\nexport interface ParseRequestOptions {\n ip?: boolean;\n request?: boolean | string[];\n serverName?: boolean;\n transaction?: boolean | TransactionNamingScheme;\n user?: boolean | string[];\n version?: boolean;\n}\n\n/**\n * Enriches passed event with request data.\n *\n * @param event Will be mutated and enriched with req data\n * @param req Request object\n * @param options object containing flags to enable functionality\n * @hidden\n */\nexport function parseRequest(event: Event, req: ExpressRequest, options?: ParseRequestOptions): Event {\n // eslint-disable-next-line no-param-reassign\n options = {\n ip: false,\n request: true,\n serverName: true,\n transaction: true,\n user: true,\n version: true,\n ...options,\n };\n\n if (options.version) {\n event.contexts = {\n ...event.contexts,\n runtime: {\n name: 'node',\n version: global.process.version,\n },\n };\n }\n\n if (options.request) {\n // if the option value is `true`, use the default set of keys by not passing anything to `extractRequestData()`\n const extractedRequestData = Array.isArray(options.request)\n ? extractRequestData(req, options.request)\n : extractRequestData(req);\n event.request = {\n ...event.request,\n ...extractedRequestData,\n };\n }\n\n if (options.serverName && !event.server_name) {\n event.server_name = global.process.env.SENTRY_NAME || os.hostname();\n }\n\n if (options.user) {\n const extractedUser = req.user && isPlainObject(req.user) ? extractUserData(req.user, options.user) : {};\n\n if (Object.keys(extractedUser)) {\n event.user = {\n ...event.user,\n ...extractedUser,\n };\n }\n }\n\n // client ip:\n // node, nextjs: req.connection.remoteAddress\n // express, koa: req.ip\n if (options.ip) {\n const ip = req.ip || (req.connection && req.connection.remoteAddress);\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n\n if (options.transaction && !event.transaction) {\n // TODO do we even need this anymore?\n // TODO make this work for nextjs\n event.transaction = extractTransaction(req, options.transaction);\n }\n\n return event;\n}\n\nexport type RequestHandlerOptions = ParseRequestOptions & {\n flushTimeout?: number;\n};\n\n/**\n * Express compatible request handler.\n * @see Exposed as `Handlers.requestHandler`\n */\nexport function requestHandler(\n options?: RequestHandlerOptions,\n): (req: http.IncomingMessage, res: http.ServerResponse, next: (error?: any) => void) => void {\n const currentHub = getCurrentHub();\n const client = currentHub.getClient<NodeClient>();\n // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the\n // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode\n if (client && isAutoSessionTrackingEnabled(client)) {\n client.initSessionFlusher();\n\n // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode\n const scope = currentHub.getScope();\n if (scope && scope.getSession()) {\n scope.setSession();\n }\n }\n return function sentryRequestMiddleware(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error?: any) => void,\n ): void {\n if (options && options.flushTimeout && options.flushTimeout > 0) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _end = res.end;\n res.end = function(chunk?: any | (() => void), encoding?: string | (() => void), cb?: () => void): void {\n void flush(options.flushTimeout)\n .then(() => {\n _end.call(this, chunk, encoding, cb);\n })\n .then(null, e => {\n logger.error(e);\n });\n };\n }\n const local = domain.create();\n local.add(req);\n local.add(res);\n local.on('error', next);\n\n local.run(() => {\n const currentHub = getCurrentHub();\n\n currentHub.configureScope(scope => {\n scope.addEventProcessor((event: Event) => parseRequest(event, req, options));\n const client = currentHub.getClient<NodeClient>();\n if (isAutoSessionTrackingEnabled(client)) {\n const scope = currentHub.getScope();\n if (scope) {\n // Set `status` of `RequestSession` to Ok, at the beginning of the request\n scope.setRequestSession({ status: RequestSessionStatus.Ok });\n }\n }\n });\n\n res.once('finish', () => {\n const client = currentHub.getClient<NodeClient>();\n if (isAutoSessionTrackingEnabled(client)) {\n setImmediate(() => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (client && (client as any)._captureRequestSession) {\n // Calling _captureRequestSession to capture request session at the end of the request by incrementing\n // the correct SessionAggregates bucket i.e. crashed, errored or exited\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (client as any)._captureRequestSession();\n }\n });\n }\n });\n next();\n });\n };\n}\n\n/** JSDoc */\ninterface MiddlewareError extends Error {\n status?: number | string;\n statusCode?: number | string;\n status_code?: number | string;\n output?: {\n statusCode?: number | string;\n };\n}\n\n/** JSDoc */\nfunction getStatusCodeFromResponse(error: MiddlewareError): number {\n const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);\n return statusCode ? parseInt(statusCode as string, 10) : 500;\n}\n\n/** Returns true if response code is internal server error */\nfunction defaultShouldHandleError(error: MiddlewareError): boolean {\n const status = getStatusCodeFromResponse(error);\n return status >= 500;\n}\n\n/**\n * Express compatible error handler.\n * @see Exposed as `Handlers.errorHandler`\n */\nexport function errorHandler(options?: {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(error: MiddlewareError): boolean;\n}): (\n error: MiddlewareError,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n) => void {\n return function sentryErrorMiddleware(\n error: MiddlewareError,\n _req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n ): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;\n\n if (shouldHandleError(error)) {\n withScope(_scope => {\n // For some reason we need to set the transaction on the scope again\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const transaction = (res as any).__sentry_transaction as Span;\n if (transaction && _scope.getSpan() === undefined) {\n _scope.setSpan(transaction);\n }\n\n const client = getCurrentHub().getClient<NodeClient>();\n if (client && isAutoSessionTrackingEnabled(client)) {\n // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the\n // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only\n // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be\n // running in SessionAggregates mode\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const isSessionAggregatesMode = (client as any)._sessionFlusher !== undefined;\n if (isSessionAggregatesMode) {\n const requestSession = _scope.getRequestSession();\n // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a\n // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within\n // the bounds of a request, and if so the status is updated\n if (requestSession && requestSession.status !== undefined)\n requestSession.status = RequestSessionStatus.Crashed;\n }\n }\n\n const eventId = captureException(error);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (res as any).sentry = eventId;\n next(error);\n });\n\n return;\n }\n\n next(error);\n };\n}\n", "export {\n Breadcrumb,\n BreadcrumbHint,\n Request,\n SdkInfo,\n Event,\n EventHint,\n Exception,\n Response,\n Severity,\n StackFrame,\n Stacktrace,\n Status,\n Thread,\n User,\n} from '@sentry/types';\n\nexport {\n addGlobalEventProcessor,\n addBreadcrumb,\n captureException,\n captureEvent,\n captureMessage,\n configureScope,\n getHubFromCarrier,\n getCurrentHub,\n Hub,\n makeMain,\n Scope,\n startTransaction,\n SDK_VERSION,\n setContext,\n setExtra,\n setExtras,\n setTag,\n setTags,\n setUser,\n withScope,\n} from '@sentry/core';\n\nexport { NodeOptions } from './types';\nexport { NodeBackend } from './backend';\nexport { NodeClient } from './client';\nexport { defaultIntegrations, init, lastEventId, flush, close, getSentryRelease } from './sdk';\nexport { deepReadDirSync } from './utils';\nexport { SDK_NAME } from './version';\n\nimport { Integrations as CoreIntegrations } from '@sentry/core';\nimport { getMainCarrier } from '@sentry/hub';\nimport * as domain from 'domain';\n\nimport * as Handlers from './handlers';\nimport * as NodeIntegrations from './integrations';\nimport * as Transports from './transports';\n\nconst INTEGRATIONS = {\n ...CoreIntegrations,\n ...NodeIntegrations,\n};\n\nexport { INTEGRATIONS as Integrations, Transports, Handlers };\n\n// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like\n// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`.\nconst carrier = getMainCarrier();\nif (carrier.__SENTRY__) {\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain;\n}\n", "import { Event, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, logger } from '@sentry/utils';\n\n// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js\nconst angularPattern = /^\\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\\] (.*?)\\n?(\\S+)$/;\n\n/**\n * AngularJS integration\n *\n * Provides an $exceptionHandler for AngularJS\n */\nexport class Angular implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'AngularJS';\n\n /**\n * moduleName used in Angular's DI resolution algorithm\n */\n public static moduleName: string = 'ngSentry';\n\n /**\n * @inheritDoc\n */\n public name: string = Angular.id;\n\n /**\n * Angular's instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _angular: any;\n\n /**\n * ngSentry module instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly _module: any;\n\n /**\n * Returns current hub.\n */\n private _getCurrentHub?: () => Hub;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options: { angular?: any } = {}) {\n logger.log('You are still using the Angular integration, consider moving to @sentry/angular');\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this._angular = options.angular || getGlobalObject<any>().angular;\n\n if (!this._angular) {\n logger.error('AngularIntegration is missing an Angular instance');\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._module = this._angular.module(Angular.moduleName, []);\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._module) {\n return;\n }\n\n this._getCurrentHub = getCurrentHub;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this._module.config([\n '$provide',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ($provide: any): void => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n $provide.decorator('$exceptionHandler', ['$delegate', this._$exceptionHandlerDecorator.bind(this)]);\n },\n ]);\n }\n\n /**\n * Angular's exceptionHandler for Sentry integration\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _$exceptionHandlerDecorator($delegate: any): any {\n return (exception: Error, cause?: string): void => {\n const hub = this._getCurrentHub && this._getCurrentHub();\n\n if (hub && hub.getIntegration(Angular)) {\n hub.withScope(scope => {\n if (cause) {\n scope.setExtra('cause', cause);\n }\n\n scope.addEventProcessor((event: Event) => {\n const ex = event.exception && event.exception.values && event.exception.values[0];\n\n if (ex) {\n const matches = angularPattern.exec(ex.value || '');\n\n if (matches) {\n // This type now becomes something like: $rootScope:inprog\n ex.type = matches[1];\n ex.value = matches[2];\n event.message = `${ex.type}: ${ex.value}`;\n // auto set a new tag specifically for the angular error url\n event.extra = {\n ...event.extra,\n angularDocs: matches[3].substr(0, 250),\n };\n }\n }\n\n return event;\n });\n\n hub.captureException(exception);\n });\n }\n $delegate(exception, cause);\n };\n }\n}\n", "import { EventProcessor, Hub, Integration, Severity } from '@sentry/types';\nimport { fill, getGlobalObject, safeJoin } from '@sentry/utils';\n\nconst global = getGlobalObject<Window | NodeJS.Global>();\n\n/** Send Console API calls as Sentry Events */\nexport class CaptureConsole implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'CaptureConsole';\n\n /**\n * @inheritDoc\n */\n public name: string = CaptureConsole.id;\n\n /**\n * @inheritDoc\n */\n private readonly _levels: string[] = ['log', 'info', 'warn', 'error', 'debug', 'assert'];\n\n /**\n * @inheritDoc\n */\n public constructor(options: { levels?: string[] } = {}) {\n if (options.levels) {\n this._levels = options.levels;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!('console' in global)) {\n return;\n }\n\n this._levels.forEach((level: string) => {\n if (!(level in global.console)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fill(global.console, level, (originalConsoleLevel: () => any) => (...args: any[]): void => {\n const hub = getCurrentHub();\n\n if (hub.getIntegration(CaptureConsole)) {\n hub.withScope(scope => {\n scope.setLevel(Severity.fromString(level));\n scope.setExtra('arguments', args);\n scope.addEventProcessor(event => {\n event.logger = 'console';\n return event;\n });\n\n let message = safeJoin(args, ' ');\n if (level === 'assert') {\n if (args[0] === false) {\n message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n hub.captureMessage(message);\n }\n } else if (level === 'error' && args[0] instanceof Error) {\n hub.captureException(args[0]);\n } else {\n hub.captureMessage(message);\n }\n });\n }\n\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, global.console, args);\n }\n });\n });\n }\n}\n", "import { Event, EventHint, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\n\n/** JSDoc */\ninterface DebugOptions {\n stringify?: boolean;\n debugger?: boolean;\n}\n\n/** JSDoc */\nexport class Debug implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Debug';\n\n /**\n * @inheritDoc\n */\n public name: string = Debug.id;\n\n /** JSDoc */\n private readonly _options: DebugOptions;\n\n /**\n * @inheritDoc\n */\n public constructor(options?: DebugOptions) {\n this._options = {\n debugger: false,\n stringify: false,\n ...options,\n };\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(Debug);\n if (self) {\n if (self._options.debugger) {\n // eslint-disable-next-line no-debugger\n debugger;\n }\n\n /* eslint-disable no-console */\n consoleSandbox(() => {\n if (self._options.stringify) {\n console.log(JSON.stringify(event, null, 2));\n if (hint) {\n console.log(JSON.stringify(hint, null, 2));\n }\n } else {\n console.log(event);\n if (hint) {\n console.log(hint);\n }\n }\n });\n /* eslint-enable no-console */\n }\n return event;\n });\n }\n}\n", "import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types';\nimport { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nexport class Dedupe implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Dedupe';\n\n /**\n * @inheritDoc\n */\n public name: string = Dedupe.id;\n\n /**\n * @inheritDoc\n */\n private _previousEvent?: Event;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((currentEvent: Event) => {\n const self = getCurrentHub().getIntegration(Dedupe);\n if (self) {\n // Juuust in case something goes wrong\n try {\n if (self._shouldDropEvent(currentEvent, self._previousEvent)) {\n logger.warn(`Event dropped due to being a duplicate of previously captured event.`);\n return null;\n }\n } catch (_oO) {\n return (self._previousEvent = currentEvent);\n }\n\n return (self._previousEvent = currentEvent);\n }\n return currentEvent;\n });\n }\n\n /** JSDoc */\n private _shouldDropEvent(currentEvent: Event, previousEvent?: Event): boolean {\n if (!previousEvent) {\n return false;\n }\n\n if (this._isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (this._isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n }\n\n /** JSDoc */\n private _isSameMessageEvent(currentEvent: Event, previousEvent: Event): boolean {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _getFramesFromEvent(event: Event): StackFrame[] | undefined {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-ignore Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n } else if (event.stacktrace) {\n return event.stacktrace.frames;\n }\n return undefined;\n }\n\n /** JSDoc */\n private _isSameStacktrace(currentEvent: Event, previousEvent: Event): boolean {\n let currentFrames = this._getFramesFromEvent(currentEvent);\n let previousFrames = this._getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames as StackFrame[];\n previousFrames = previousFrames as StackFrame[];\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n const frameA = previousFrames[i];\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /** JSDoc */\n private _getExceptionFromEvent(event: Event): Exception | undefined {\n return event.exception && event.exception.values && event.exception.values[0];\n }\n\n /** JSDoc */\n private _isSameExceptionEvent(currentEvent: Event, previousEvent: Event): boolean {\n const previousException = this._getExceptionFromEvent(previousEvent);\n const currentException = this._getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!this._isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!this._isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n }\n\n /** JSDoc */\n private _isSameFingerprint(currentEvent: Event, previousEvent: Event): boolean {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint as string[];\n previousFingerprint = previousFingerprint as string[];\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n }\n}\n", "import { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, isInstanceOf, logger } from '@sentry/utils';\n\n/** JSDoc */\nexport class Ember implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Ember';\n\n /**\n * @inheritDoc\n */\n public name: string = Ember.id;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n private readonly _Ember: any;\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public constructor(options: { Ember?: any } = {}) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n this._Ember = options.Ember || getGlobalObject<any>().Ember;\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._Ember) {\n logger.error('EmberIntegration is missing an Ember instance');\n return;\n }\n\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n const oldOnError = this._Ember.onerror;\n\n this._Ember.onerror = (error: Error): void => {\n if (getCurrentHub().getIntegration(Ember)) {\n getCurrentHub().captureException(error, { originalException: error });\n }\n\n if (typeof oldOnError === 'function') {\n oldOnError.call(this._Ember, error);\n } else if (this._Ember.testing) {\n throw error;\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._Ember.RSVP.on('error', (reason: unknown): void => {\n if (getCurrentHub().getIntegration(Ember)) {\n getCurrentHub().withScope(scope => {\n if (isInstanceOf(reason, Error)) {\n scope.setExtra('context', 'Unhandled Promise error detected');\n getCurrentHub().captureException(reason, { originalException: reason as Error });\n } else {\n scope.setExtra('reason', reason);\n getCurrentHub().captureMessage('Unhandled Promise error detected');\n }\n });\n }\n });\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n", "import { Event, EventHint, EventProcessor, ExtendedError, Hub, Integration } from '@sentry/types';\nimport { isError, isPlainObject, logger, normalize } from '@sentry/utils';\n\n/** JSDoc */\ninterface ExtraErrorDataOptions {\n depth?: number;\n}\n\n/** Patch toString calls to return proper name for wrapped functions */\nexport class ExtraErrorData implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'ExtraErrorData';\n\n /**\n * @inheritDoc\n */\n public name: string = ExtraErrorData.id;\n\n /**\n * @inheritDoc\n */\n public constructor(private readonly _options: ExtraErrorDataOptions = { depth: 3 }) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor((event: Event, hint?: EventHint) => {\n const self = getCurrentHub().getIntegration(ExtraErrorData);\n if (!self) {\n return event;\n }\n return self.enhanceEventWithErrorData(event, hint);\n });\n }\n\n /**\n * Attaches extracted information from the Error object to extra field in the Event\n */\n public enhanceEventWithErrorData(event: Event, hint?: EventHint): Event {\n if (!hint || !hint.originalException || !isError(hint.originalException)) {\n return event;\n }\n const name = (hint.originalException as ExtendedError).name || hint.originalException.constructor.name;\n\n const errorData = this._extractErrorData(hint.originalException as ExtendedError);\n\n if (errorData) {\n let contexts = {\n ...event.contexts,\n };\n\n const normalizedErrorData = normalize(errorData, this._options.depth);\n if (isPlainObject(normalizedErrorData)) {\n contexts = {\n ...event.contexts,\n [name]: {\n ...normalizedErrorData,\n },\n };\n }\n\n return {\n ...event,\n contexts,\n };\n }\n\n return event;\n }\n\n /**\n * Extract extra information from the Error object\n */\n private _extractErrorData(error: ExtendedError): Record<string, unknown> | null {\n // We are trying to enhance already existing event, so no harm done if it won't succeed\n try {\n const nativeKeys = [\n 'name',\n 'message',\n 'stack',\n 'line',\n 'column',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'toJSON',\n ];\n\n const extraErrorInfo: Record<string, unknown> = {};\n\n // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n for (const key of Object.keys(error)) {\n if (nativeKeys.indexOf(key) !== -1) {\n continue;\n }\n const value = error[key];\n extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;\n }\n\n // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n if (typeof error.toJSON === 'function') {\n const serializedError = error.toJSON() as Record<string, unknown>;\n\n for (const key of Object.keys(serializedError)) {\n const value = serializedError[key];\n extraErrorInfo[key] = isError(value) ? (value as Error).toString() : value;\n }\n }\n\n return extraErrorInfo;\n } catch (oO) {\n logger.error('Unable to extract extra data from the Error object:', oO);\n }\n\n return null;\n }\n}\n", "/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\n{\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\nimport { Event, EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, logger, normalize, uuid4 } from '@sentry/utils';\nimport localForage from 'localforage';\n\ntype LocalForage = {\n setItem<T>(key: string, value: T, callback?: (err: any, value: T) => void): Promise<T>;\n iterate<T, U>(\n iteratee: (value: T, key: string, iterationNumber: number) => U,\n callback?: (err: any, result: U) => void,\n ): Promise<U>;\n removeItem(key: string, callback?: (err: any) => void): Promise<void>;\n};\n\n/**\n * cache offline errors and send when connected\n */\nexport class Offline implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Offline';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = Offline.id;\n\n /**\n * the global instance\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public global: any;\n\n /**\n * the current hub instance\n */\n public hub?: Hub;\n\n /**\n * maximum number of events to store while offline\n */\n public maxStoredEvents: number;\n\n /**\n * event cache\n */\n public offlineEventStore: LocalForage;\n\n /**\n * @inheritDoc\n */\n public constructor(options: { maxStoredEvents?: number } = {}) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.global = getGlobalObject<any>();\n this.maxStoredEvents = options.maxStoredEvents || 30; // set a reasonable default\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n this.offlineEventStore = localForage.createInstance({\n name: 'sentry/offlineEventStore',\n });\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n this.hub = getCurrentHub();\n\n if ('addEventListener' in this.global) {\n this.global.addEventListener('online', () => {\n void this._sendEvents().catch(() => {\n logger.warn('could not send cached events');\n });\n });\n }\n\n addGlobalEventProcessor((event: Event) => {\n if (this.hub && this.hub.getIntegration(Offline)) {\n // cache if we are positively offline\n if ('navigator' in this.global && 'onLine' in this.global.navigator && !this.global.navigator.onLine) {\n void this._cacheEvent(event)\n .then((_event: Event): Promise<void> => this._enforceMaxEvents())\n .catch((_error): void => {\n logger.warn('could not cache event while offline');\n });\n\n // return null on success or failure, because being offline will still result in an error\n return null;\n }\n }\n\n return event;\n });\n\n // if online now, send any events stored in a previous offline session\n if ('navigator' in this.global && 'onLine' in this.global.navigator && this.global.navigator.onLine) {\n void this._sendEvents().catch(() => {\n logger.warn('could not send cached events');\n });\n }\n }\n\n /**\n * cache an event to send later\n * @param event an event\n */\n private async _cacheEvent(event: Event): Promise<Event> {\n return this.offlineEventStore.setItem<Event>(uuid4(), normalize(event));\n }\n\n /**\n * purge excess events if necessary\n */\n private async _enforceMaxEvents(): Promise<void> {\n const events: Array<{ event: Event; cacheKey: string }> = [];\n\n return this.offlineEventStore\n .iterate<Event, void>((event: Event, cacheKey: string, _index: number): void => {\n // aggregate events\n events.push({ cacheKey, event });\n })\n .then(\n (): Promise<void> =>\n // this promise resolves when the iteration is finished\n this._purgeEvents(\n // purge all events past maxStoredEvents in reverse chronological order\n events\n .sort((a, b) => (b.event.timestamp || 0) - (a.event.timestamp || 0))\n .slice(this.maxStoredEvents < events.length ? this.maxStoredEvents : events.length)\n .map(event => event.cacheKey),\n ),\n )\n .catch((_error): void => {\n logger.warn('could not enforce max events');\n });\n }\n\n /**\n * purge event from cache\n */\n private async _purgeEvent(cacheKey: string): Promise<void> {\n return this.offlineEventStore.removeItem(cacheKey);\n }\n\n /**\n * purge events from cache\n */\n private async _purgeEvents(cacheKeys: string[]): Promise<void> {\n // trail with .then to ensure the return type as void and not void|void[]\n return Promise.all(cacheKeys.map(cacheKey => this._purgeEvent(cacheKey))).then();\n }\n\n /**\n * send all events\n */\n private async _sendEvents(): Promise<void> {\n return this.offlineEventStore.iterate<Event, void>((event: Event, cacheKey: string, _index: number): void => {\n if (this.hub) {\n this.hub.captureEvent(event);\n\n void this._purgeEvent(cacheKey).catch((_error): void => {\n logger.warn('could not purge event from cache');\n });\n } else {\n logger.warn('no hub found - could not send cached event');\n }\n });\n }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { EventProcessor, Hub, Integration } from '@sentry/types';\nimport { getGlobalObject, supportsReportingObserver } from '@sentry/utils';\n\n/** JSDoc */\ninterface Report {\n [key: string]: any;\n type: ReportTypes;\n url: string;\n body?: ReportBody;\n}\n\n/** JSDoc */\nconst enum ReportTypes {\n /** JSDoc */\n Crash = 'crash',\n /** JSDoc */\n Deprecation = 'deprecation',\n /** JSDoc */\n Intervention = 'intervention',\n}\n\n/** JSDoc */\ntype ReportBody = CrashReportBody | DeprecationReportBody | InterventionReportBody;\n\n/** JSDoc */\ninterface CrashReportBody {\n [key: string]: any;\n crashId: string;\n reason?: string;\n}\n\n/** JSDoc */\ninterface DeprecationReportBody {\n [key: string]: any;\n id: string;\n anticipatedRemoval?: Date;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\n/** JSDoc */\ninterface InterventionReportBody {\n [key: string]: any;\n id: string;\n message: string;\n sourceFile?: string;\n lineNumber?: number;\n columnNumber?: number;\n}\n\n/** Reporting API integration - https://w3c.github.io/reporting/ */\nexport class ReportingObserver implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'ReportingObserver';\n\n /**\n * @inheritDoc\n */\n public readonly name: string = ReportingObserver.id;\n\n /**\n * Returns current hub.\n */\n private _getCurrentHub?: () => Hub;\n\n /**\n * @inheritDoc\n */\n public constructor(\n private readonly _options: {\n types?: ReportTypes[];\n } = {\n types: [ReportTypes.Crash, ReportTypes.Deprecation, ReportTypes.Intervention],\n },\n ) {}\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!supportsReportingObserver()) {\n return;\n }\n\n this._getCurrentHub = getCurrentHub;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const observer = new (getGlobalObject<any>().ReportingObserver)(this.handler.bind(this), {\n buffered: true,\n types: this._options.types,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n observer.observe();\n }\n\n /**\n * @inheritDoc\n */\n public handler(reports: Report[]): void {\n const hub = this._getCurrentHub && this._getCurrentHub();\n if (!hub || !hub.getIntegration(ReportingObserver)) {\n return;\n }\n for (const report of reports) {\n hub.withScope(scope => {\n scope.setExtra('url', report.url);\n\n const label = `ReportingObserver [${report.type}]`;\n let details = 'No details available';\n\n if (report.body) {\n // Object.keys doesn't work on ReportBody, as all properties are inheirted\n const plainBody: {\n [key: string]: any;\n } = {};\n\n // eslint-disable-next-line guard-for-in\n for (const prop in report.body) {\n plainBody[prop] = report.body[prop];\n }\n\n scope.setExtra('body', plainBody);\n\n if (report.type === ReportTypes.Crash) {\n const body = report.body as CrashReportBody;\n // A fancy way to create a message out of crashId OR reason OR both OR fallback\n details = [body.crashId || '', body.reason || ''].join(' ').trim() || details;\n } else {\n const body = report.body as DeprecationReportBody | InterventionReportBody;\n details = body.message || details;\n }\n }\n\n hub.captureMessage(`${label}: ${details}`);\n });\n }\n }\n}\n", "import { Event, EventProcessor, Hub, Integration, StackFrame, Stacktrace } from '@sentry/types';\nimport { basename, relative } from '@sentry/utils';\n\ntype StackFrameIteratee = (frame: StackFrame) => StackFrame;\n\n/** Rewrite event frames paths */\nexport class RewriteFrames implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'RewriteFrames';\n\n /**\n * @inheritDoc\n */\n public name: string = RewriteFrames.id;\n\n /**\n * @inheritDoc\n */\n private readonly _root?: string;\n\n /**\n * @inheritDoc\n */\n private readonly _prefix: string = 'app:///';\n\n /**\n * @inheritDoc\n */\n public constructor(options: { root?: string; prefix?: string; iteratee?: StackFrameIteratee } = {}) {\n if (options.root) {\n this._root = options.root;\n }\n if (options.prefix) {\n this._prefix = options.prefix;\n }\n if (options.iteratee) {\n this._iteratee = options.iteratee;\n }\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(RewriteFrames);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /** JSDoc */\n public process(originalEvent: Event): Event {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = this._processExceptionsEvent(processedEvent);\n }\n\n if (originalEvent.stacktrace) {\n processedEvent = this._processStacktraceEvent(processedEvent);\n }\n\n return processedEvent;\n }\n\n /**\n * @inheritDoc\n */\n private readonly _iteratee: StackFrameIteratee = (frame: StackFrame) => {\n if (!frame.filename) {\n return frame;\n }\n // Check if the frame filename begins with `/` or a Windows-style prefix such as `C:\\`\n const isWindowsFrame = /^[A-Z]:\\\\/.test(frame.filename);\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = this._root ? relative(this._root, filename) : basename(filename);\n frame.filename = `${this._prefix}${base}`;\n }\n return frame;\n };\n\n /** JSDoc */\n private _processExceptionsEvent(event: Event): Event {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception!.values!.map(value => ({\n ...value,\n stacktrace: this._processStacktrace(value.stacktrace),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n private _processStacktraceEvent(event: Event): Event {\n try {\n return {\n ...event,\n stacktrace: this._processStacktrace(event.stacktrace),\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n private _processStacktrace(stacktrace?: Stacktrace): Stacktrace {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => this._iteratee(f)),\n };\n }\n}\n", "import { Event, EventProcessor, Hub, Integration } from '@sentry/types';\n\n/** This function adds duration since Sentry was initialized till the time event was sent */\nexport class SessionTiming implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'SessionTiming';\n\n /**\n * @inheritDoc\n */\n public name: string = SessionTiming.id;\n\n /** Exact time Client was initialized expressed in milliseconds since Unix Epoch. */\n protected readonly _startTime: number = Date.now();\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(SessionTiming);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n public process(event: Event): Event {\n const now = Date.now();\n\n return {\n ...event,\n extra: {\n ...event.extra,\n ['session:start']: this._startTime,\n ['session:duration']: now - this._startTime,\n ['session:end']: now,\n },\n };\n }\n}\n", "import { Event, EventProcessor, Hub, Integration, StackFrame } from '@sentry/types';\n\n/** Add node transaction to the event */\nexport class Transaction implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Transaction';\n\n /**\n * @inheritDoc\n */\n public name: string = Transaction.id;\n\n /**\n * @inheritDoc\n */\n public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n addGlobalEventProcessor(event => {\n const self = getCurrentHub().getIntegration(Transaction);\n if (self) {\n return self.process(event);\n }\n return event;\n });\n }\n\n /**\n * @inheritDoc\n */\n public process(event: Event): Event {\n const frames = this._getFramesFromEvent(event);\n\n // use for loop so we don't have to reverse whole frames array\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame.in_app === true) {\n event.transaction = this._getTransaction(frame);\n break;\n }\n }\n\n return event;\n }\n\n /** JSDoc */\n private _getFramesFromEvent(event: Event): StackFrame[] {\n const exception = event.exception && event.exception.values && event.exception.values[0];\n return (exception && exception.stacktrace && exception.stacktrace.frames) || [];\n }\n\n /** JSDoc */\n private _getTransaction(frame: StackFrame): string {\n return frame.module || frame.function ? `${frame.module || '?'}/${frame.function || '?'}` : '<unknown>';\n }\n}\n", "/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { EventProcessor, Hub, Integration, IntegrationClass, Scope, Span, Transaction } from '@sentry/types';\nimport { basename, getGlobalObject, logger, timestampWithMs } from '@sentry/utils';\n\n/**\n * Used to extract Tracing integration from the current client,\n * without the need to import `Tracing` itself from the @sentry/apm package.\n * @deprecated as @sentry/tracing should be used over @sentry/apm.\n */\nconst TRACING_GETTER = ({\n id: 'Tracing',\n} as any) as IntegrationClass<Integration>;\n\n/**\n * Used to extract BrowserTracing integration from @sentry/tracing\n */\nconst BROWSER_TRACING_GETTER = ({\n id: 'BrowserTracing',\n} as any) as IntegrationClass<Integration>;\n\nconst VUE_OP = 'ui.vue';\n\n/** Global Vue object limited to the methods/attributes we require */\ninterface VueInstance {\n config: {\n errorHandler?(error: Error, vm?: ViewModel, info?: string): void;\n };\n util?: {\n warn(...input: any): void;\n };\n mixin(hooks: { [key: string]: () => void }): void;\n}\n\n/** Representation of Vue component internals */\ninterface ViewModel {\n [key: string]: any;\n // eslint-disable-next-line @typescript-eslint/ban-types\n $root: object;\n $options: {\n [key: string]: any;\n name?: string;\n propsData?: { [key: string]: any };\n _componentTag?: string;\n __file?: string;\n $_sentryPerfHook?: boolean;\n };\n $once(hook: string, cb: () => void): void;\n}\n\n/** Vue Integration configuration */\ninterface IntegrationOptions {\n /** Vue instance to be used inside the integration */\n Vue: VueInstance;\n\n /**\n * When set to `false`, Sentry will suppress reporting of all props data\n * from your Vue components for privacy concerns.\n */\n attachProps: boolean;\n /**\n * When set to `true`, original Vue's `logError` will be called as well.\n * https://github.com/vuejs/vue/blob/c2b1cfe9ccd08835f2d99f6ce60f67b4de55187f/src/core/util/error.js#L38-L48\n */\n logErrors: boolean;\n\n /**\n * When set to `true`, enables tracking of components lifecycle performance.\n * It requires `Tracing` integration to be also enabled.\n */\n tracing: boolean;\n\n /** {@link TracingOptions} */\n tracingOptions: TracingOptions;\n}\n\n/** Vue specific configuration for Tracing Integration */\ninterface TracingOptions {\n /**\n * Decides whether to track components by hooking into its lifecycle methods.\n * Can be either set to `boolean` to enable/disable tracking for all of them.\n * Or to an array of specific component names (case-sensitive).\n */\n trackComponents: boolean | string[];\n /** How long to wait until the tracked root activity is marked as finished and sent of to Sentry */\n timeout: number;\n /**\n * List of hooks to keep track of during component lifecycle.\n * Available hooks: 'activate' | 'create' | 'destroy' | 'mount' | 'update'\n * Based on https://vuejs.org/v2/api/#Options-Lifecycle-Hooks\n */\n hooks: Operation[];\n}\n\n/** Optional metadata attached to Sentry Event */\ninterface Metadata {\n [key: string]: any;\n componentName?: string;\n propsData?: { [key: string]: any };\n lifecycleHook?: string;\n}\n\n// https://vuejs.org/v2/api/#Options-Lifecycle-Hooks\ntype Hook =\n | 'activated'\n | 'beforeCreate'\n | 'beforeDestroy'\n | 'beforeMount'\n | 'beforeUpdate'\n | 'created'\n | 'deactivated'\n | 'destroyed'\n | 'mounted'\n | 'updated';\n\ntype Operation = 'activate' | 'create' | 'destroy' | 'mount' | 'update';\n\n// Mappings from operation to corresponding lifecycle hook.\nconst HOOKS: { [key in Operation]: Hook[] } = {\n activate: ['activated', 'deactivated'],\n create: ['beforeCreate', 'created'],\n destroy: ['beforeDestroy', 'destroyed'],\n mount: ['beforeMount', 'mounted'],\n update: ['beforeUpdate', 'updated'],\n};\n\nconst COMPONENT_NAME_REGEXP = /(?:^|[-_/])(\\w)/g;\nconst ROOT_COMPONENT_NAME = 'root';\nconst ANONYMOUS_COMPONENT_NAME = 'anonymous component';\n\n/** JSDoc */\nexport class Vue implements Integration {\n /**\n * @inheritDoc\n */\n public static id: string = 'Vue';\n\n /**\n * @inheritDoc\n */\n public name: string = Vue.id;\n\n private readonly _options: IntegrationOptions;\n\n /**\n * Cache holding already processed component names\n */\n private readonly _componentsCache: { [key: string]: string } = {};\n private _rootSpan?: Span;\n private _rootSpanTimer?: ReturnType<typeof setTimeout>;\n private _tracingActivity?: number;\n\n /**\n * @inheritDoc\n */\n public constructor(\n options: Partial<Omit<IntegrationOptions, 'tracingOptions'> & { tracingOptions: Partial<TracingOptions> }>,\n ) {\n logger.log('You are still using the Vue.js integration, consider moving to @sentry/vue');\n this._options = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n Vue: getGlobalObject<any>().Vue,\n attachProps: true,\n logErrors: false,\n tracing: false,\n ...options,\n tracingOptions: {\n hooks: ['mount', 'update'],\n timeout: 2000,\n trackComponents: false,\n ...options.tracingOptions,\n },\n };\n }\n\n /**\n * @inheritDoc\n */\n public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void {\n if (!this._options.Vue) {\n logger.error('Vue integration is missing a Vue instance');\n return;\n }\n\n this._attachErrorHandler(getCurrentHub);\n\n if (this._options.tracing) {\n this._startTracing(getCurrentHub);\n }\n }\n\n /**\n * Extract component name from the ViewModel\n */\n private _getComponentName(vm: ViewModel): string {\n // Such level of granularity is most likely not necessary, but better safe than sorry. \u2014 Kamil\n if (!vm) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n if (vm.$root === vm) {\n return ROOT_COMPONENT_NAME;\n }\n\n if (!vm.$options) {\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n if (vm.$options.name) {\n return vm.$options.name;\n }\n\n if (vm.$options._componentTag) {\n return vm.$options._componentTag;\n }\n\n // injected by vue-loader\n if (vm.$options.__file) {\n const unifiedFile = vm.$options.__file.replace(/^[a-zA-Z]:/, '').replace(/\\\\/g, '/');\n const filename = basename(unifiedFile, '.vue');\n return (\n this._componentsCache[filename] ||\n (this._componentsCache[filename] = filename.replace(COMPONENT_NAME_REGEXP, (_, c: string) =>\n c ? c.toUpperCase() : '',\n ))\n );\n }\n\n return ANONYMOUS_COMPONENT_NAME;\n }\n\n /** Keep it as attribute function, to keep correct `this` binding inside the hooks callbacks */\n // eslint-disable-next-line @typescript-eslint/typedef\n private readonly _applyTracingHooks = (vm: ViewModel, getCurrentHub: () => Hub): void => {\n // Don't attach twice, just in case\n if (vm.$options.$_sentryPerfHook) {\n return;\n }\n vm.$options.$_sentryPerfHook = true;\n\n const name = this._getComponentName(vm);\n const rootMount = name === ROOT_COMPONENT_NAME;\n const spans: { [key: string]: Span } = {};\n\n // Render hook starts after once event is emitted,\n // but it ends before the second event of the same type.\n //\n // Because of this, we start measuring inside the first event,\n // but finish it before it triggers, to skip the event emitter timing itself.\n const rootHandler = (hook: Hook): void => {\n const now = timestampWithMs();\n\n // On the first handler call (before), it'll be undefined, as `$once` will add it in the future.\n // However, on the second call (after), it'll be already in place.\n if (this._rootSpan) {\n this._finishRootSpan(now, getCurrentHub);\n } else {\n vm.$once(`hook:${hook}`, () => {\n // Create an activity on the first event call. There'll be no second call, as rootSpan will be in place,\n // thus new event handler won't be attached.\n\n // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.\n // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line deprecation/deprecation\n const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);\n if (tracingIntegration) {\n this._tracingActivity = (tracingIntegration as any).constructor.pushActivity('Vue Application Render');\n const transaction = (tracingIntegration as any).constructor.getTransaction();\n if (transaction) {\n this._rootSpan = transaction.startChild({\n description: 'Application Render',\n op: VUE_OP,\n });\n }\n // Use functionality from @sentry/tracing\n } else {\n const activeTransaction = getActiveTransaction(getCurrentHub());\n if (activeTransaction) {\n this._rootSpan = activeTransaction.startChild({\n description: 'Application Render',\n op: VUE_OP,\n });\n }\n }\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n });\n }\n };\n\n const childHandler = (hook: Hook, operation: Operation): void => {\n // Skip components that we don't want to track to minimize the noise and give a more granular control to the user\n const shouldTrack = Array.isArray(this._options.tracingOptions.trackComponents)\n ? this._options.tracingOptions.trackComponents.indexOf(name) > -1\n : this._options.tracingOptions.trackComponents;\n\n if (!this._rootSpan || !shouldTrack) {\n return;\n }\n\n const now = timestampWithMs();\n const span = spans[operation];\n\n // On the first handler call (before), it'll be undefined, as `$once` will add it in the future.\n // However, on the second call (after), it'll be already in place.\n if (span) {\n span.finish();\n this._finishRootSpan(now, getCurrentHub);\n } else {\n vm.$once(`hook:${hook}`, () => {\n if (this._rootSpan) {\n spans[operation] = this._rootSpan.startChild({\n description: `Vue <${name}>`,\n op: `${VUE_OP}.${operation}`,\n });\n }\n });\n }\n };\n\n // Each component has it's own scope, so all activities are only related to one of them\n this._options.tracingOptions.hooks.forEach(operation => {\n // Retrieve corresponding hooks from Vue lifecycle.\n // eg. mount => ['beforeMount', 'mounted']\n const internalHooks = HOOKS[operation];\n\n if (!internalHooks) {\n logger.warn(`Unknown hook: ${operation}`);\n return;\n }\n\n internalHooks.forEach(internalHook => {\n const handler = rootMount\n ? rootHandler.bind(this, internalHook)\n : childHandler.bind(this, internalHook, operation);\n const currentValue = vm.$options[internalHook];\n\n if (Array.isArray(currentValue)) {\n vm.$options[internalHook] = [handler, ...currentValue];\n } else if (typeof currentValue === 'function') {\n vm.$options[internalHook] = [handler, currentValue];\n } else {\n vm.$options[internalHook] = [handler];\n }\n });\n });\n };\n\n /** Finish top-level span and activity with a debounce configured using `timeout` option */\n private _finishRootSpan(timestamp: number, getCurrentHub: () => Hub): void {\n if (this._rootSpanTimer) {\n clearTimeout(this._rootSpanTimer);\n }\n\n this._rootSpanTimer = setTimeout(() => {\n if (this._tracingActivity) {\n // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency.\n // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods.\n // eslint-disable-next-line deprecation/deprecation\n const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER);\n if (tracingIntegration) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (tracingIntegration as any).constructor.popActivity(this._tracingActivity);\n }\n }\n\n // We should always finish the span, only should pop activity if using @sentry/apm\n if (this._rootSpan) {\n this._rootSpan.finish(timestamp);\n }\n }, this._options.tracingOptions.timeout);\n }\n\n /** Inject configured tracing hooks into Vue's component lifecycles */\n private _startTracing(getCurrentHub: () => Hub): void {\n const applyTracingHooks = this._applyTracingHooks;\n\n this._options.Vue.mixin({\n beforeCreate(this: ViewModel): void {\n // eslint-disable-next-line deprecation/deprecation\n if (getCurrentHub().getIntegration(TRACING_GETTER) || getCurrentHub().getIntegration(BROWSER_TRACING_GETTER)) {\n // `this` points to currently rendered component\n applyTracingHooks(this, getCurrentHub);\n } else {\n logger.error('Vue integration has tracing enabled, but Tracing integration is not configured');\n }\n },\n });\n }\n\n /** Inject Sentry's handler into owns Vue's error handler */\n private _attachErrorHandler(getCurrentHub: () => Hub): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const currentErrorHandler = this._options.Vue.config.errorHandler;\n\n this._options.Vue.config.errorHandler = (error: Error, vm?: ViewModel, info?: string): void => {\n const metadata: Metadata = {};\n\n if (vm) {\n try {\n metadata.componentName = this._getComponentName(vm);\n\n if (this._options.attachProps) {\n metadata.propsData = vm.$options.propsData;\n }\n } catch (_oO) {\n logger.warn('Unable to extract metadata from Vue component.');\n }\n }\n\n if (info) {\n metadata.lifecycleHook = info;\n }\n\n if (getCurrentHub().getIntegration(Vue)) {\n // Capture exception in the next event loop, to make sure that all breadcrumbs are recorded in time.\n setTimeout(() => {\n getCurrentHub().withScope(scope => {\n scope.setContext('vue', metadata);\n getCurrentHub().captureException(error);\n });\n });\n }\n\n if (typeof currentErrorHandler === 'function') {\n currentErrorHandler.call(this._options.Vue, error, vm, info);\n }\n\n if (this._options.logErrors) {\n if (this._options.Vue.util) {\n this._options.Vue.util.warn(`Error in ${info}: \"${error && error.toString()}\"`, vm);\n }\n // eslint-disable-next-line no-console\n console.error(error);\n }\n };\n }\n}\n\ninterface HubType extends Hub {\n getScope?(): Scope | undefined;\n}\n\n/** Grabs active transaction off scope */\nexport function getActiveTransaction<T extends Transaction>(hub: HubType): T | undefined {\n if (hub && hub.getScope) {\n const scope = hub.getScope() as Scope;\n if (scope) {\n return scope.getTransaction() as T | undefined;\n }\n }\n\n return undefined;\n}\n", "export { Angular } from './angular';\nexport { CaptureConsole } from './captureconsole';\nexport { Debug } from './debug';\nexport { Dedupe } from './dedupe';\nexport { Ember } from './ember';\nexport { ExtraErrorData } from './extraerrordata';\nexport { Offline } from './offline';\nexport { ReportingObserver } from './reportingobserver';\nexport { RewriteFrames } from './rewriteframes';\nexport { SessionTiming } from './sessiontiming';\nexport { Transaction } from './transaction';\nexport { Vue } from './vue';\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');\n\n/**\n * Encode an integer in the range of 0 to 63 to a single base 64 digit.\n */\nexports.encode = function (number) {\n if (0 <= number && number < intToCharMap.length) {\n return intToCharMap[number];\n }\n throw new TypeError(\"Must be between 0 and 63: \" + number);\n};\n\n/**\n * Decode a single base 64 character code digit to an integer. Returns -1 on\n * failure.\n */\nexports.decode = function (charCode) {\n var bigA = 65; // 'A'\n var bigZ = 90; // 'Z'\n\n var littleA = 97; // 'a'\n var littleZ = 122; // 'z'\n\n var zero = 48; // '0'\n var nine = 57; // '9'\n\n var plus = 43; // '+'\n var slash = 47; // '/'\n\n var littleOffset = 26;\n var numberOffset = 52;\n\n // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ\n if (bigA <= charCode && charCode <= bigZ) {\n return (charCode - bigA);\n }\n\n // 26 - 51: abcdefghijklmnopqrstuvwxyz\n if (littleA <= charCode && charCode <= littleZ) {\n return (charCode - littleA + littleOffset);\n }\n\n // 52 - 61: 0123456789\n if (zero <= charCode && charCode <= nine) {\n return (charCode - zero + numberOffset);\n }\n\n // 62: +\n if (charCode == plus) {\n return 62;\n }\n\n // 63: /\n if (charCode == slash) {\n return 63;\n }\n\n // Invalid base64 digit.\n return -1;\n};\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * Based on the Base 64 VLQ implementation in Closure Compiler:\n * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java\n *\n * Copyright 2011 The Closure Compiler Authors. All rights reserved.\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nvar base64 = require('./base64');\n\n// A single base 64 digit can contain 6 bits of data. For the base 64 variable\n// length quantities we use in the source map spec, the first bit is the sign,\n// the next four bits are the actual value, and the 6th bit is the\n// continuation bit. The continuation bit tells us whether there are more\n// digits in this value following this digit.\n//\n// Continuation\n// | Sign\n// | |\n// V V\n// 101011\n\nvar VLQ_BASE_SHIFT = 5;\n\n// binary: 100000\nvar VLQ_BASE = 1 << VLQ_BASE_SHIFT;\n\n// binary: 011111\nvar VLQ_BASE_MASK = VLQ_BASE - 1;\n\n// binary: 100000\nvar VLQ_CONTINUATION_BIT = VLQ_BASE;\n\n/**\n * Converts from a two-complement value to a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)\n * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)\n */\nfunction toVLQSigned(aValue) {\n return aValue < 0\n ? ((-aValue) << 1) + 1\n : (aValue << 1) + 0;\n}\n\n/**\n * Converts to a two-complement value from a value where the sign bit is\n * placed in the least significant bit. For example, as decimals:\n * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1\n * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2\n */\nfunction fromVLQSigned(aValue) {\n var isNegative = (aValue & 1) === 1;\n var shifted = aValue >> 1;\n return isNegative\n ? -shifted\n : shifted;\n}\n\n/**\n * Returns the base 64 VLQ encoded value.\n */\nexports.encode = function base64VLQ_encode(aValue) {\n var encoded = \"\";\n var digit;\n\n var vlq = toVLQSigned(aValue);\n\n do {\n digit = vlq & VLQ_BASE_MASK;\n vlq >>>= VLQ_BASE_SHIFT;\n if (vlq > 0) {\n // There are still more digits in this value, so we must make sure the\n // continuation bit is marked.\n digit |= VLQ_CONTINUATION_BIT;\n }\n encoded += base64.encode(digit);\n } while (vlq > 0);\n\n return encoded;\n};\n\n/**\n * Decodes the next base 64 VLQ value from the given string and returns the\n * value and the rest of the string via the out parameter.\n */\nexports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {\n var strLen = aStr.length;\n var result = 0;\n var shift = 0;\n var continuation, digit;\n\n do {\n if (aIndex >= strLen) {\n throw new Error(\"Expected more digits in base 64 VLQ value.\");\n }\n\n digit = base64.decode(aStr.charCodeAt(aIndex++));\n if (digit === -1) {\n throw new Error(\"Invalid base64 digit: \" + aStr.charAt(aIndex - 1));\n }\n\n continuation = !!(digit & VLQ_CONTINUATION_BIT);\n digit &= VLQ_BASE_MASK;\n result = result + (digit << shift);\n shift += VLQ_BASE_SHIFT;\n } while (continuation);\n\n aOutParam.value = fromVLQSigned(result);\n aOutParam.rest = aIndex;\n};\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/**\n * This is a helper function for getting values from parameter/options\n * objects.\n *\n * @param args The object we are extracting values from\n * @param name The name of the property we are getting.\n * @param defaultValue An optional value to return if the property is missing\n * from the object. If this is not specified and the property is missing, an\n * error will be thrown.\n */\nfunction getArg(aArgs, aName, aDefaultValue) {\n if (aName in aArgs) {\n return aArgs[aName];\n } else if (arguments.length === 3) {\n return aDefaultValue;\n } else {\n throw new Error('\"' + aName + '\" is a required argument.');\n }\n}\nexports.getArg = getArg;\n\nvar urlRegexp = /^(?:([\\w+\\-.]+):)?\\/\\/(?:(\\w+:\\w+)@)?([\\w.-]*)(?::(\\d+))?(.*)$/;\nvar dataUrlRegexp = /^data:.+\\,.+$/;\n\nfunction urlParse(aUrl) {\n var match = aUrl.match(urlRegexp);\n if (!match) {\n return null;\n }\n return {\n scheme: match[1],\n auth: match[2],\n host: match[3],\n port: match[4],\n path: match[5]\n };\n}\nexports.urlParse = urlParse;\n\nfunction urlGenerate(aParsedUrl) {\n var url = '';\n if (aParsedUrl.scheme) {\n url += aParsedUrl.scheme + ':';\n }\n url += '//';\n if (aParsedUrl.auth) {\n url += aParsedUrl.auth + '@';\n }\n if (aParsedUrl.host) {\n url += aParsedUrl.host;\n }\n if (aParsedUrl.port) {\n url += \":\" + aParsedUrl.port\n }\n if (aParsedUrl.path) {\n url += aParsedUrl.path;\n }\n return url;\n}\nexports.urlGenerate = urlGenerate;\n\n/**\n * Normalizes a path, or the path portion of a URL:\n *\n * - Replaces consecutive slashes with one slash.\n * - Removes unnecessary '.' parts.\n * - Removes unnecessary '<dir>/..' parts.\n *\n * Based on code in the Node.js 'path' core module.\n *\n * @param aPath The path or url to normalize.\n */\nfunction normalize(aPath) {\n var path = aPath;\n var url = urlParse(aPath);\n if (url) {\n if (!url.path) {\n return aPath;\n }\n path = url.path;\n }\n var isAbsolute = exports.isAbsolute(path);\n\n var parts = path.split(/\\/+/);\n for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {\n part = parts[i];\n if (part === '.') {\n parts.splice(i, 1);\n } else if (part === '..') {\n up++;\n } else if (up > 0) {\n if (part === '') {\n // The first part is blank if the path is absolute. Trying to go\n // above the root is a no-op. Therefore we can remove all '..' parts\n // directly after the root.\n parts.splice(i + 1, up);\n up = 0;\n } else {\n parts.splice(i, 2);\n up--;\n }\n }\n }\n path = parts.join('/');\n\n if (path === '') {\n path = isAbsolute ? '/' : '.';\n }\n\n if (url) {\n url.path = path;\n return urlGenerate(url);\n }\n return path;\n}\nexports.normalize = normalize;\n\n/**\n * Joins two paths/URLs.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be joined with the root.\n *\n * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a\n * scheme-relative URL: Then the scheme of aRoot, if any, is prepended\n * first.\n * - Otherwise aPath is a path. If aRoot is a URL, then its path portion\n * is updated with the result and aRoot is returned. Otherwise the result\n * is returned.\n * - If aPath is absolute, the result is aPath.\n * - Otherwise the two paths are joined with a slash.\n * - Joining for example 'http://' and 'www.example.com' is also supported.\n */\nfunction join(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n if (aPath === \"\") {\n aPath = \".\";\n }\n var aPathUrl = urlParse(aPath);\n var aRootUrl = urlParse(aRoot);\n if (aRootUrl) {\n aRoot = aRootUrl.path || '/';\n }\n\n // `join(foo, '//www.example.org')`\n if (aPathUrl && !aPathUrl.scheme) {\n if (aRootUrl) {\n aPathUrl.scheme = aRootUrl.scheme;\n }\n return urlGenerate(aPathUrl);\n }\n\n if (aPathUrl || aPath.match(dataUrlRegexp)) {\n return aPath;\n }\n\n // `join('http://', 'www.example.com')`\n if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {\n aRootUrl.host = aPath;\n return urlGenerate(aRootUrl);\n }\n\n var joined = aPath.charAt(0) === '/'\n ? aPath\n : normalize(aRoot.replace(/\\/+$/, '') + '/' + aPath);\n\n if (aRootUrl) {\n aRootUrl.path = joined;\n return urlGenerate(aRootUrl);\n }\n return joined;\n}\nexports.join = join;\n\nexports.isAbsolute = function (aPath) {\n return aPath.charAt(0) === '/' || urlRegexp.test(aPath);\n};\n\n/**\n * Make a path relative to a URL or another path.\n *\n * @param aRoot The root path or URL.\n * @param aPath The path or URL to be made relative to aRoot.\n */\nfunction relative(aRoot, aPath) {\n if (aRoot === \"\") {\n aRoot = \".\";\n }\n\n aRoot = aRoot.replace(/\\/$/, '');\n\n // It is possible for the path to be above the root. In this case, simply\n // checking whether the root is a prefix of the path won't work. Instead, we\n // need to remove components from the root one by one, until either we find\n // a prefix that fits, or we run out of components to remove.\n var level = 0;\n while (aPath.indexOf(aRoot + '/') !== 0) {\n var index = aRoot.lastIndexOf(\"/\");\n if (index < 0) {\n return aPath;\n }\n\n // If the only part of the root that is left is the scheme (i.e. http://,\n // file:///, etc.), one or more slashes (/), or simply nothing at all, we\n // have exhausted all components, so the path is not relative to the root.\n aRoot = aRoot.slice(0, index);\n if (aRoot.match(/^([^\\/]+:\\/)?\\/*$/)) {\n return aPath;\n }\n\n ++level;\n }\n\n // Make sure we add a \"../\" for each component we removed from the root.\n return Array(level + 1).join(\"../\") + aPath.substr(aRoot.length + 1);\n}\nexports.relative = relative;\n\nvar supportsNullProto = (function () {\n var obj = Object.create(null);\n return !('__proto__' in obj);\n}());\n\nfunction identity (s) {\n return s;\n}\n\n/**\n * Because behavior goes wacky when you set `__proto__` on objects, we\n * have to prefix all the strings in our set with an arbitrary character.\n *\n * See https://github.com/mozilla/source-map/pull/31 and\n * https://github.com/mozilla/source-map/issues/30\n *\n * @param String aStr\n */\nfunction toSetString(aStr) {\n if (isProtoString(aStr)) {\n return '$' + aStr;\n }\n\n return aStr;\n}\nexports.toSetString = supportsNullProto ? identity : toSetString;\n\nfunction fromSetString(aStr) {\n if (isProtoString(aStr)) {\n return aStr.slice(1);\n }\n\n return aStr;\n}\nexports.fromSetString = supportsNullProto ? identity : fromSetString;\n\nfunction isProtoString(s) {\n if (!s) {\n return false;\n }\n\n var length = s.length;\n\n if (length < 9 /* \"__proto__\".length */) {\n return false;\n }\n\n if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||\n s.charCodeAt(length - 2) !== 95 /* '_' */ ||\n s.charCodeAt(length - 3) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 4) !== 116 /* 't' */ ||\n s.charCodeAt(length - 5) !== 111 /* 'o' */ ||\n s.charCodeAt(length - 6) !== 114 /* 'r' */ ||\n s.charCodeAt(length - 7) !== 112 /* 'p' */ ||\n s.charCodeAt(length - 8) !== 95 /* '_' */ ||\n s.charCodeAt(length - 9) !== 95 /* '_' */) {\n return false;\n }\n\n for (var i = length - 10; i >= 0; i--) {\n if (s.charCodeAt(i) !== 36 /* '$' */) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Comparator between two mappings where the original positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same original source/line/column, but different generated\n * line and column the same. Useful when searching for a mapping with a\n * stubbed out mapping.\n */\nfunction compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {\n var cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0 || onlyCompareOriginal) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByOriginalPositions = compareByOriginalPositions;\n\n/**\n * Comparator between two mappings with deflated source and name indices where\n * the generated positions are compared.\n *\n * Optionally pass in `true` as `onlyCompareGenerated` to consider two\n * mappings with the same generated line and column, but different\n * source/name/original line and column the same. Useful when searching for a\n * mapping with a stubbed out mapping.\n */\nfunction compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0 || onlyCompareGenerated) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;\n\nfunction strcmp(aStr1, aStr2) {\n if (aStr1 === aStr2) {\n return 0;\n }\n\n if (aStr1 === null) {\n return 1; // aStr2 !== null\n }\n\n if (aStr2 === null) {\n return -1; // aStr1 !== null\n }\n\n if (aStr1 > aStr2) {\n return 1;\n }\n\n return -1;\n}\n\n/**\n * Comparator between two mappings with inflated source and name strings where\n * the generated positions are compared.\n */\nfunction compareByGeneratedPositionsInflated(mappingA, mappingB) {\n var cmp = mappingA.generatedLine - mappingB.generatedLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.generatedColumn - mappingB.generatedColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = strcmp(mappingA.source, mappingB.source);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalLine - mappingB.originalLine;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = mappingA.originalColumn - mappingB.originalColumn;\n if (cmp !== 0) {\n return cmp;\n }\n\n return strcmp(mappingA.name, mappingB.name);\n}\nexports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;\n\n/**\n * Strip any JSON XSSI avoidance prefix from the string (as documented\n * in the source maps specification), and then parse the string as\n * JSON.\n */\nfunction parseSourceMapInput(str) {\n return JSON.parse(str.replace(/^\\)]}'[^\\n]*\\n/, ''));\n}\nexports.parseSourceMapInput = parseSourceMapInput;\n\n/**\n * Compute the URL of a source given the the source root, the source's\n * URL, and the source map's URL.\n */\nfunction computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {\n sourceURL = sourceURL || '';\n\n if (sourceRoot) {\n // This follows what Chrome does.\n if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {\n sourceRoot += '/';\n }\n // The spec says:\n // Line 4: An optional source root, useful for relocating source\n // files on a server or removing repeated values in the\n // \u201Csources\u201D entry. This value is prepended to the individual\n // entries in the \u201Csource\u201D field.\n sourceURL = sourceRoot + sourceURL;\n }\n\n // Historically, SourceMapConsumer did not take the sourceMapURL as\n // a parameter. This mode is still somewhat supported, which is why\n // this code block is conditional. However, it's preferable to pass\n // the source map URL to SourceMapConsumer, so that this function\n // can implement the source URL resolution algorithm as outlined in\n // the spec. This block is basically the equivalent of:\n // new URL(sourceURL, sourceMapURL).toString()\n // ... except it avoids using URL, which wasn't available in the\n // older releases of node still supported by this library.\n //\n // The spec says:\n // If the sources are not absolute URLs after prepending of the\n // \u201CsourceRoot\u201D, the sources are resolved relative to the\n // SourceMap (like resolving script src in a html document).\n if (sourceMapURL) {\n var parsed = urlParse(sourceMapURL);\n if (!parsed) {\n throw new Error(\"sourceMapURL could not be parsed\");\n }\n if (parsed.path) {\n // Strip the last path component, but keep the \"/\".\n var index = parsed.path.lastIndexOf('/');\n if (index >= 0) {\n parsed.path = parsed.path.substring(0, index + 1);\n }\n }\n sourceURL = join(urlGenerate(parsed), sourceURL);\n }\n\n return normalize(sourceURL);\n}\nexports.computeSourceURL = computeSourceURL;\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar has = Object.prototype.hasOwnProperty;\nvar hasNativeMap = typeof Map !== \"undefined\";\n\n/**\n * A data structure which is a combination of an array and a set. Adding a new\n * member is O(1), testing for membership is O(1), and finding the index of an\n * element is O(1). Removing elements from the set is not supported. Only\n * strings are supported for membership.\n */\nfunction ArraySet() {\n this._array = [];\n this._set = hasNativeMap ? new Map() : Object.create(null);\n}\n\n/**\n * Static method for creating ArraySet instances from an existing array.\n */\nArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {\n var set = new ArraySet();\n for (var i = 0, len = aArray.length; i < len; i++) {\n set.add(aArray[i], aAllowDuplicates);\n }\n return set;\n};\n\n/**\n * Return how many unique items are in this ArraySet. If duplicates have been\n * added, than those do not count towards the size.\n *\n * @returns Number\n */\nArraySet.prototype.size = function ArraySet_size() {\n return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;\n};\n\n/**\n * Add the given string to this set.\n *\n * @param String aStr\n */\nArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {\n var sStr = hasNativeMap ? aStr : util.toSetString(aStr);\n var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);\n var idx = this._array.length;\n if (!isDuplicate || aAllowDuplicates) {\n this._array.push(aStr);\n }\n if (!isDuplicate) {\n if (hasNativeMap) {\n this._set.set(aStr, idx);\n } else {\n this._set[sStr] = idx;\n }\n }\n};\n\n/**\n * Is the given string a member of this set?\n *\n * @param String aStr\n */\nArraySet.prototype.has = function ArraySet_has(aStr) {\n if (hasNativeMap) {\n return this._set.has(aStr);\n } else {\n var sStr = util.toSetString(aStr);\n return has.call(this._set, sStr);\n }\n};\n\n/**\n * What is the index of the given string in the array?\n *\n * @param String aStr\n */\nArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {\n if (hasNativeMap) {\n var idx = this._set.get(aStr);\n if (idx >= 0) {\n return idx;\n }\n } else {\n var sStr = util.toSetString(aStr);\n if (has.call(this._set, sStr)) {\n return this._set[sStr];\n }\n }\n\n throw new Error('\"' + aStr + '\" is not in the set.');\n};\n\n/**\n * What is the element at the given index?\n *\n * @param Number aIdx\n */\nArraySet.prototype.at = function ArraySet_at(aIdx) {\n if (aIdx >= 0 && aIdx < this._array.length) {\n return this._array[aIdx];\n }\n throw new Error('No element indexed by ' + aIdx);\n};\n\n/**\n * Returns the array representation of this set (which has the proper indices\n * indicated by indexOf). Note that this is a copy of the internal array used\n * for storing the members so that no one can mess with internal state.\n */\nArraySet.prototype.toArray = function ArraySet_toArray() {\n return this._array.slice();\n};\n\nexports.ArraySet = ArraySet;\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2014 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\n\n/**\n * Determine whether mappingB is after mappingA with respect to generated\n * position.\n */\nfunction generatedPositionAfter(mappingA, mappingB) {\n // Optimized for most common case\n var lineA = mappingA.generatedLine;\n var lineB = mappingB.generatedLine;\n var columnA = mappingA.generatedColumn;\n var columnB = mappingB.generatedColumn;\n return lineB > lineA || lineB == lineA && columnB >= columnA ||\n util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;\n}\n\n/**\n * A data structure to provide a sorted view of accumulated mappings in a\n * performance conscious manner. It trades a neglibable overhead in general\n * case for a large speedup in case of mappings being added in order.\n */\nfunction MappingList() {\n this._array = [];\n this._sorted = true;\n // Serves as infimum\n this._last = {generatedLine: -1, generatedColumn: 0};\n}\n\n/**\n * Iterate through internal items. This method takes the same arguments that\n * `Array.prototype.forEach` takes.\n *\n * NOTE: The order of the mappings is NOT guaranteed.\n */\nMappingList.prototype.unsortedForEach =\n function MappingList_forEach(aCallback, aThisArg) {\n this._array.forEach(aCallback, aThisArg);\n };\n\n/**\n * Add the given source mapping.\n *\n * @param Object aMapping\n */\nMappingList.prototype.add = function MappingList_add(aMapping) {\n if (generatedPositionAfter(this._last, aMapping)) {\n this._last = aMapping;\n this._array.push(aMapping);\n } else {\n this._sorted = false;\n this._array.push(aMapping);\n }\n};\n\n/**\n * Returns the flat, sorted array of mappings. The mappings are sorted by\n * generated position.\n *\n * WARNING: This method returns internal data without copying, for\n * performance. The return value must NOT be mutated, and should be treated as\n * an immutable borrow. If you want to take ownership, you must make your own\n * copy.\n */\nMappingList.prototype.toArray = function MappingList_toArray() {\n if (!this._sorted) {\n this._array.sort(util.compareByGeneratedPositionsInflated);\n this._sorted = true;\n }\n return this._array;\n};\n\nexports.MappingList = MappingList;\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar base64VLQ = require('./base64-vlq');\nvar util = require('./util');\nvar ArraySet = require('./array-set').ArraySet;\nvar MappingList = require('./mapping-list').MappingList;\n\n/**\n * An instance of the SourceMapGenerator represents a source map which is\n * being built incrementally. You may pass an object with the following\n * properties:\n *\n * - file: The filename of the generated source.\n * - sourceRoot: A root for all relative URLs in this source map.\n */\nfunction SourceMapGenerator(aArgs) {\n if (!aArgs) {\n aArgs = {};\n }\n this._file = util.getArg(aArgs, 'file', null);\n this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);\n this._skipValidation = util.getArg(aArgs, 'skipValidation', false);\n this._sources = new ArraySet();\n this._names = new ArraySet();\n this._mappings = new MappingList();\n this._sourcesContents = null;\n}\n\nSourceMapGenerator.prototype._version = 3;\n\n/**\n * Creates a new SourceMapGenerator based on a SourceMapConsumer\n *\n * @param aSourceMapConsumer The SourceMap.\n */\nSourceMapGenerator.fromSourceMap =\n function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {\n var sourceRoot = aSourceMapConsumer.sourceRoot;\n var generator = new SourceMapGenerator({\n file: aSourceMapConsumer.file,\n sourceRoot: sourceRoot\n });\n aSourceMapConsumer.eachMapping(function (mapping) {\n var newMapping = {\n generated: {\n line: mapping.generatedLine,\n column: mapping.generatedColumn\n }\n };\n\n if (mapping.source != null) {\n newMapping.source = mapping.source;\n if (sourceRoot != null) {\n newMapping.source = util.relative(sourceRoot, newMapping.source);\n }\n\n newMapping.original = {\n line: mapping.originalLine,\n column: mapping.originalColumn\n };\n\n if (mapping.name != null) {\n newMapping.name = mapping.name;\n }\n }\n\n generator.addMapping(newMapping);\n });\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var sourceRelative = sourceFile;\n if (sourceRoot !== null) {\n sourceRelative = util.relative(sourceRoot, sourceFile);\n }\n\n if (!generator._sources.has(sourceRelative)) {\n generator._sources.add(sourceRelative);\n }\n\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n generator.setSourceContent(sourceFile, content);\n }\n });\n return generator;\n };\n\n/**\n * Add a single mapping from original source line and column to the generated\n * source's line and column for this source map being created. The mapping\n * object should have the following properties:\n *\n * - generated: An object with the generated line and column positions.\n * - original: An object with the original line and column positions.\n * - source: The original source file (relative to the sourceRoot).\n * - name: An optional original token name for this mapping.\n */\nSourceMapGenerator.prototype.addMapping =\n function SourceMapGenerator_addMapping(aArgs) {\n var generated = util.getArg(aArgs, 'generated');\n var original = util.getArg(aArgs, 'original', null);\n var source = util.getArg(aArgs, 'source', null);\n var name = util.getArg(aArgs, 'name', null);\n\n if (!this._skipValidation) {\n this._validateMapping(generated, original, source, name);\n }\n\n if (source != null) {\n source = String(source);\n if (!this._sources.has(source)) {\n this._sources.add(source);\n }\n }\n\n if (name != null) {\n name = String(name);\n if (!this._names.has(name)) {\n this._names.add(name);\n }\n }\n\n this._mappings.add({\n generatedLine: generated.line,\n generatedColumn: generated.column,\n originalLine: original != null && original.line,\n originalColumn: original != null && original.column,\n source: source,\n name: name\n });\n };\n\n/**\n * Set the source content for a source file.\n */\nSourceMapGenerator.prototype.setSourceContent =\n function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {\n var source = aSourceFile;\n if (this._sourceRoot != null) {\n source = util.relative(this._sourceRoot, source);\n }\n\n if (aSourceContent != null) {\n // Add the source content to the _sourcesContents map.\n // Create a new _sourcesContents map if the property is null.\n if (!this._sourcesContents) {\n this._sourcesContents = Object.create(null);\n }\n this._sourcesContents[util.toSetString(source)] = aSourceContent;\n } else if (this._sourcesContents) {\n // Remove the source file from the _sourcesContents map.\n // If the _sourcesContents map is empty, set the property to null.\n delete this._sourcesContents[util.toSetString(source)];\n if (Object.keys(this._sourcesContents).length === 0) {\n this._sourcesContents = null;\n }\n }\n };\n\n/**\n * Applies the mappings of a sub-source-map for a specific source file to the\n * source map being generated. Each mapping to the supplied source file is\n * rewritten using the supplied source map. Note: The resolution for the\n * resulting mappings is the minimium of this map and the supplied map.\n *\n * @param aSourceMapConsumer The source map to be applied.\n * @param aSourceFile Optional. The filename of the source file.\n * If omitted, SourceMapConsumer's file property will be used.\n * @param aSourceMapPath Optional. The dirname of the path to the source map\n * to be applied. If relative, it is relative to the SourceMapConsumer.\n * This parameter is needed when the two source maps aren't in the same\n * directory, and the source map to be applied contains relative source\n * paths. If so, those relative source paths need to be rewritten\n * relative to the SourceMapGenerator.\n */\nSourceMapGenerator.prototype.applySourceMap =\n function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {\n var sourceFile = aSourceFile;\n // If aSourceFile is omitted, we will use the file property of the SourceMap\n if (aSourceFile == null) {\n if (aSourceMapConsumer.file == null) {\n throw new Error(\n 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +\n 'or the source map\\'s \"file\" property. Both were omitted.'\n );\n }\n sourceFile = aSourceMapConsumer.file;\n }\n var sourceRoot = this._sourceRoot;\n // Make \"sourceFile\" relative if an absolute Url is passed.\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n // Applying the SourceMap can add and remove items from the sources and\n // the names array.\n var newSources = new ArraySet();\n var newNames = new ArraySet();\n\n // Find mappings for the \"sourceFile\"\n this._mappings.unsortedForEach(function (mapping) {\n if (mapping.source === sourceFile && mapping.originalLine != null) {\n // Check if it can be mapped by the source map, then update the mapping.\n var original = aSourceMapConsumer.originalPositionFor({\n line: mapping.originalLine,\n column: mapping.originalColumn\n });\n if (original.source != null) {\n // Copy mapping\n mapping.source = original.source;\n if (aSourceMapPath != null) {\n mapping.source = util.join(aSourceMapPath, mapping.source)\n }\n if (sourceRoot != null) {\n mapping.source = util.relative(sourceRoot, mapping.source);\n }\n mapping.originalLine = original.line;\n mapping.originalColumn = original.column;\n if (original.name != null) {\n mapping.name = original.name;\n }\n }\n }\n\n var source = mapping.source;\n if (source != null && !newSources.has(source)) {\n newSources.add(source);\n }\n\n var name = mapping.name;\n if (name != null && !newNames.has(name)) {\n newNames.add(name);\n }\n\n }, this);\n this._sources = newSources;\n this._names = newNames;\n\n // Copy sourcesContents of applied map.\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aSourceMapPath != null) {\n sourceFile = util.join(aSourceMapPath, sourceFile);\n }\n if (sourceRoot != null) {\n sourceFile = util.relative(sourceRoot, sourceFile);\n }\n this.setSourceContent(sourceFile, content);\n }\n }, this);\n };\n\n/**\n * A mapping can have one of the three levels of data:\n *\n * 1. Just the generated position.\n * 2. The Generated position, original position, and original source.\n * 3. Generated and original position, original source, as well as a name\n * token.\n *\n * To maintain consistency, we validate that any new mapping being added falls\n * in to one of these categories.\n */\nSourceMapGenerator.prototype._validateMapping =\n function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,\n aName) {\n // When aOriginal is truthy but has empty values for .line and .column,\n // it is most likely a programmer error. In this case we throw a very\n // specific error message to try to guide them the right way.\n // For example: https://github.com/Polymer/polymer-bundler/pull/519\n if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {\n throw new Error(\n 'original.line and original.column are not numbers -- you probably meant to omit ' +\n 'the original mapping entirely and only map the generated position. If so, pass ' +\n 'null for the original mapping instead of an object with empty or null values.'\n );\n }\n\n if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aGenerated.line > 0 && aGenerated.column >= 0\n && !aOriginal && !aSource && !aName) {\n // Case 1.\n return;\n }\n else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated\n && aOriginal && 'line' in aOriginal && 'column' in aOriginal\n && aGenerated.line > 0 && aGenerated.column >= 0\n && aOriginal.line > 0 && aOriginal.column >= 0\n && aSource) {\n // Cases 2 and 3.\n return;\n }\n else {\n throw new Error('Invalid mapping: ' + JSON.stringify({\n generated: aGenerated,\n source: aSource,\n original: aOriginal,\n name: aName\n }));\n }\n };\n\n/**\n * Serialize the accumulated mappings in to the stream of base 64 VLQs\n * specified by the source map format.\n */\nSourceMapGenerator.prototype._serializeMappings =\n function SourceMapGenerator_serializeMappings() {\n var previousGeneratedColumn = 0;\n var previousGeneratedLine = 1;\n var previousOriginalColumn = 0;\n var previousOriginalLine = 0;\n var previousName = 0;\n var previousSource = 0;\n var result = '';\n var next;\n var mapping;\n var nameIdx;\n var sourceIdx;\n\n var mappings = this._mappings.toArray();\n for (var i = 0, len = mappings.length; i < len; i++) {\n mapping = mappings[i];\n next = ''\n\n if (mapping.generatedLine !== previousGeneratedLine) {\n previousGeneratedColumn = 0;\n while (mapping.generatedLine !== previousGeneratedLine) {\n next += ';';\n previousGeneratedLine++;\n }\n }\n else {\n if (i > 0) {\n if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {\n continue;\n }\n next += ',';\n }\n }\n\n next += base64VLQ.encode(mapping.generatedColumn\n - previousGeneratedColumn);\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (mapping.source != null) {\n sourceIdx = this._sources.indexOf(mapping.source);\n next += base64VLQ.encode(sourceIdx - previousSource);\n previousSource = sourceIdx;\n\n // lines are stored 0-based in SourceMap spec version 3\n next += base64VLQ.encode(mapping.originalLine - 1\n - previousOriginalLine);\n previousOriginalLine = mapping.originalLine - 1;\n\n next += base64VLQ.encode(mapping.originalColumn\n - previousOriginalColumn);\n previousOriginalColumn = mapping.originalColumn;\n\n if (mapping.name != null) {\n nameIdx = this._names.indexOf(mapping.name);\n next += base64VLQ.encode(nameIdx - previousName);\n previousName = nameIdx;\n }\n }\n\n result += next;\n }\n\n return result;\n };\n\nSourceMapGenerator.prototype._generateSourcesContent =\n function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {\n return aSources.map(function (source) {\n if (!this._sourcesContents) {\n return null;\n }\n if (aSourceRoot != null) {\n source = util.relative(aSourceRoot, source);\n }\n var key = util.toSetString(source);\n return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)\n ? this._sourcesContents[key]\n : null;\n }, this);\n };\n\n/**\n * Externalize the source map.\n */\nSourceMapGenerator.prototype.toJSON =\n function SourceMapGenerator_toJSON() {\n var map = {\n version: this._version,\n sources: this._sources.toArray(),\n names: this._names.toArray(),\n mappings: this._serializeMappings()\n };\n if (this._file != null) {\n map.file = this._file;\n }\n if (this._sourceRoot != null) {\n map.sourceRoot = this._sourceRoot;\n }\n if (this._sourcesContents) {\n map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);\n }\n\n return map;\n };\n\n/**\n * Render the source map being generated to a string.\n */\nSourceMapGenerator.prototype.toString =\n function SourceMapGenerator_toString() {\n return JSON.stringify(this.toJSON());\n };\n\nexports.SourceMapGenerator = SourceMapGenerator;\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nexports.GREATEST_LOWER_BOUND = 1;\nexports.LEAST_UPPER_BOUND = 2;\n\n/**\n * Recursive implementation of binary search.\n *\n * @param aLow Indices here and lower do not contain the needle.\n * @param aHigh Indices here and higher do not contain the needle.\n * @param aNeedle The element being searched for.\n * @param aHaystack The non-empty array being searched.\n * @param aCompare Function which takes two elements and returns -1, 0, or 1.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n */\nfunction recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {\n // This function terminates when one of the following is true:\n //\n // 1. We find the exact element we are looking for.\n //\n // 2. We did not find the exact element, but we can return the index of\n // the next-closest element.\n //\n // 3. We did not find the exact element, and there is no next-closest\n // element than the one we are searching for, so we return -1.\n var mid = Math.floor((aHigh - aLow) / 2) + aLow;\n var cmp = aCompare(aNeedle, aHaystack[mid], true);\n if (cmp === 0) {\n // Found the element we are looking for.\n return mid;\n }\n else if (cmp > 0) {\n // Our needle is greater than aHaystack[mid].\n if (aHigh - mid > 1) {\n // The element is in the upper half.\n return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // The exact needle element was not found in this haystack. Determine if\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return aHigh < aHaystack.length ? aHigh : -1;\n } else {\n return mid;\n }\n }\n else {\n // Our needle is less than aHaystack[mid].\n if (mid - aLow > 1) {\n // The element is in the lower half.\n return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);\n }\n\n // we are in termination case (3) or (2) and return the appropriate thing.\n if (aBias == exports.LEAST_UPPER_BOUND) {\n return mid;\n } else {\n return aLow < 0 ? -1 : aLow;\n }\n }\n}\n\n/**\n * This is an implementation of binary search which will always try and return\n * the index of the closest element if there is no exact hit. This is because\n * mappings between original and generated line/col pairs are single points,\n * and there is an implicit region between each of them, so a miss just means\n * that you aren't on the very start of a region.\n *\n * @param aNeedle The element you are looking for.\n * @param aHaystack The array that is being searched.\n * @param aCompare A function which takes the needle and an element in the\n * array and returns -1, 0, or 1 depending on whether the needle is less\n * than, equal to, or greater than the element, respectively.\n * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or\n * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.\n */\nexports.search = function search(aNeedle, aHaystack, aCompare, aBias) {\n if (aHaystack.length === 0) {\n return -1;\n }\n\n var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,\n aCompare, aBias || exports.GREATEST_LOWER_BOUND);\n if (index < 0) {\n return -1;\n }\n\n // We have found either the exact element, or the next-closest element than\n // the one we are searching for. However, there may be more than one such\n // element. Make sure we always return the smallest of these.\n while (index - 1 >= 0) {\n if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {\n break;\n }\n --index;\n }\n\n return index;\n};\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n// It turns out that some (most?) JavaScript engines don't self-host\n// `Array.prototype.sort`. This makes sense because C++ will likely remain\n// faster than JS when doing raw CPU-intensive sorting. However, when using a\n// custom comparator function, calling back and forth between the VM's C++ and\n// JIT'd JS is rather slow *and* loses JIT type information, resulting in\n// worse generated code for the comparator function than would be optimal. In\n// fact, when sorting with a comparator, these costs outweigh the benefits of\n// sorting in C++. By using our own JS-implemented Quick Sort (below), we get\n// a ~3500ms mean speed-up in `bench/bench.html`.\n\n/**\n * Swap the elements indexed by `x` and `y` in the array `ary`.\n *\n * @param {Array} ary\n * The array.\n * @param {Number} x\n * The index of the first item.\n * @param {Number} y\n * The index of the second item.\n */\nfunction swap(ary, x, y) {\n var temp = ary[x];\n ary[x] = ary[y];\n ary[y] = temp;\n}\n\n/**\n * Returns a random integer within the range `low .. high` inclusive.\n *\n * @param {Number} low\n * The lower bound on the range.\n * @param {Number} high\n * The upper bound on the range.\n */\nfunction randomIntInRange(low, high) {\n return Math.round(low + (Math.random() * (high - low)));\n}\n\n/**\n * The Quick Sort algorithm.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n * @param {Number} p\n * Start index of the array\n * @param {Number} r\n * End index of the array\n */\nfunction doQuickSort(ary, comparator, p, r) {\n // If our lower bound is less than our upper bound, we (1) partition the\n // array into two pieces and (2) recurse on each half. If it is not, this is\n // the empty array and our base case.\n\n if (p < r) {\n // (1) Partitioning.\n //\n // The partitioning chooses a pivot between `p` and `r` and moves all\n // elements that are less than or equal to the pivot to the before it, and\n // all the elements that are greater than it after it. The effect is that\n // once partition is done, the pivot is in the exact place it will be when\n // the array is put in sorted order, and it will not need to be moved\n // again. This runs in O(n) time.\n\n // Always choose a random pivot so that an input array which is reverse\n // sorted does not cause O(n^2) running time.\n var pivotIndex = randomIntInRange(p, r);\n var i = p - 1;\n\n swap(ary, pivotIndex, r);\n var pivot = ary[r];\n\n // Immediately after `j` is incremented in this loop, the following hold\n // true:\n //\n // * Every element in `ary[p .. i]` is less than or equal to the pivot.\n //\n // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.\n for (var j = p; j < r; j++) {\n if (comparator(ary[j], pivot) <= 0) {\n i += 1;\n swap(ary, i, j);\n }\n }\n\n swap(ary, i + 1, j);\n var q = i + 1;\n\n // (2) Recurse on each half.\n\n doQuickSort(ary, comparator, p, q - 1);\n doQuickSort(ary, comparator, q + 1, r);\n }\n}\n\n/**\n * Sort the given array in-place with the given comparator function.\n *\n * @param {Array} ary\n * An array to sort.\n * @param {function} comparator\n * Function to use to compare two items.\n */\nexports.quickSort = function (ary, comparator) {\n doQuickSort(ary, comparator, 0, ary.length - 1);\n};\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar util = require('./util');\nvar binarySearch = require('./binary-search');\nvar ArraySet = require('./array-set').ArraySet;\nvar base64VLQ = require('./base64-vlq');\nvar quickSort = require('./quick-sort').quickSort;\n\nfunction SourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n return sourceMap.sections != null\n ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)\n : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);\n}\n\nSourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {\n return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);\n}\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nSourceMapConsumer.prototype._version = 3;\n\n// `__generatedMappings` and `__originalMappings` are arrays that hold the\n// parsed mapping coordinates from the source map's \"mappings\" attribute. They\n// are lazily instantiated, accessed via the `_generatedMappings` and\n// `_originalMappings` getters respectively, and we only parse the mappings\n// and create these arrays once queried for a source location. We jump through\n// these hoops because there can be many thousands of mappings, and parsing\n// them is expensive, so we only want to do it if we must.\n//\n// Each object in the arrays is of the form:\n//\n// {\n// generatedLine: The line number in the generated code,\n// generatedColumn: The column number in the generated code,\n// source: The path to the original source file that generated this\n// chunk of code,\n// originalLine: The line number in the original source that\n// corresponds to this chunk of generated code,\n// originalColumn: The column number in the original source that\n// corresponds to this chunk of generated code,\n// name: The name of the original symbol which generated this chunk of\n// code.\n// }\n//\n// All properties except for `generatedLine` and `generatedColumn` can be\n// `null`.\n//\n// `_generatedMappings` is ordered by the generated positions.\n//\n// `_originalMappings` is ordered by the original positions.\n\nSourceMapConsumer.prototype.__generatedMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__generatedMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__generatedMappings;\n }\n});\n\nSourceMapConsumer.prototype.__originalMappings = null;\nObject.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {\n configurable: true,\n enumerable: true,\n get: function () {\n if (!this.__originalMappings) {\n this._parseMappings(this._mappings, this.sourceRoot);\n }\n\n return this.__originalMappings;\n }\n});\n\nSourceMapConsumer.prototype._charIsMappingSeparator =\n function SourceMapConsumer_charIsMappingSeparator(aStr, index) {\n var c = aStr.charAt(index);\n return c === \";\" || c === \",\";\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n throw new Error(\"Subclasses must implement _parseMappings\");\n };\n\nSourceMapConsumer.GENERATED_ORDER = 1;\nSourceMapConsumer.ORIGINAL_ORDER = 2;\n\nSourceMapConsumer.GREATEST_LOWER_BOUND = 1;\nSourceMapConsumer.LEAST_UPPER_BOUND = 2;\n\n/**\n * Iterate over each mapping between an original source/line/column and a\n * generated line/column in this source map.\n *\n * @param Function aCallback\n * The function that is called with each mapping.\n * @param Object aContext\n * Optional. If specified, this object will be the value of `this` every\n * time that `aCallback` is called.\n * @param aOrder\n * Either `SourceMapConsumer.GENERATED_ORDER` or\n * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to\n * iterate over the mappings sorted by the generated file's line/column\n * order or the original's source/line/column order, respectively. Defaults to\n * `SourceMapConsumer.GENERATED_ORDER`.\n */\nSourceMapConsumer.prototype.eachMapping =\n function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {\n var context = aContext || null;\n var order = aOrder || SourceMapConsumer.GENERATED_ORDER;\n\n var mappings;\n switch (order) {\n case SourceMapConsumer.GENERATED_ORDER:\n mappings = this._generatedMappings;\n break;\n case SourceMapConsumer.ORIGINAL_ORDER:\n mappings = this._originalMappings;\n break;\n default:\n throw new Error(\"Unknown order of iteration.\");\n }\n\n var sourceRoot = this.sourceRoot;\n mappings.map(function (mapping) {\n var source = mapping.source === null ? null : this._sources.at(mapping.source);\n source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);\n return {\n source: source,\n generatedLine: mapping.generatedLine,\n generatedColumn: mapping.generatedColumn,\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: mapping.name === null ? null : this._names.at(mapping.name)\n };\n }, this).forEach(aCallback, context);\n };\n\n/**\n * Returns all generated line and column information for the original source,\n * line, and column provided. If no column is provided, returns all mappings\n * corresponding to a either the line we are searching for or the next\n * closest line that has any mappings. Otherwise, returns all mappings\n * corresponding to the given line and either the column we are searching for\n * or the next closest column that has any offsets.\n *\n * The only argument is an object with the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number is 1-based.\n * - column: Optional. the column number in the original source.\n * The column number is 0-based.\n *\n * and an array of objects is returned, each with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nSourceMapConsumer.prototype.allGeneratedPositionsFor =\n function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {\n var line = util.getArg(aArgs, 'line');\n\n // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping\n // returns the index of the closest mapping less than the needle. By\n // setting needle.originalColumn to 0, we thus find the last mapping for\n // the given line, provided such a mapping exists.\n var needle = {\n source: util.getArg(aArgs, 'source'),\n originalLine: line,\n originalColumn: util.getArg(aArgs, 'column', 0)\n };\n\n needle.source = this._findSourceIndex(needle.source);\n if (needle.source < 0) {\n return [];\n }\n\n var mappings = [];\n\n var index = this._findMapping(needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n binarySearch.LEAST_UPPER_BOUND);\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (aArgs.column === undefined) {\n var originalLine = mapping.originalLine;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we found. Since\n // mappings are sorted, this is guaranteed to find all mappings for\n // the line we found.\n while (mapping && mapping.originalLine === originalLine) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n } else {\n var originalColumn = mapping.originalColumn;\n\n // Iterate until either we run out of mappings, or we run into\n // a mapping for a different line than the one we were searching for.\n // Since mappings are sorted, this is guaranteed to find all mappings for\n // the line we are searching for.\n while (mapping &&\n mapping.originalLine === line &&\n mapping.originalColumn == originalColumn) {\n mappings.push({\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n });\n\n mapping = this._originalMappings[++index];\n }\n }\n }\n\n return mappings;\n };\n\nexports.SourceMapConsumer = SourceMapConsumer;\n\n/**\n * A BasicSourceMapConsumer instance represents a parsed source map which we can\n * query for information about the original file positions by giving it a file\n * position in the generated source.\n *\n * The first parameter is the raw source map (either as a JSON string, or\n * already parsed to an object). According to the spec, source maps have the\n * following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - sources: An array of URLs to the original source files.\n * - names: An array of identifiers which can be referrenced by individual mappings.\n * - sourceRoot: Optional. The URL root from which all sources are relative.\n * - sourcesContent: Optional. An array of contents of the original source files.\n * - mappings: A string of base64 VLQs which contain the actual mappings.\n * - file: Optional. The generated file this source map is associated with.\n *\n * Here is an example source map, taken from the source map spec[0]:\n *\n * {\n * version : 3,\n * file: \"out.js\",\n * sourceRoot : \"\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AA,AB;;ABCDE;\"\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#\n */\nfunction BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sources = util.getArg(sourceMap, 'sources');\n // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which\n // requires the array) to play nice here.\n var names = util.getArg(sourceMap, 'names', []);\n var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);\n var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);\n var mappings = util.getArg(sourceMap, 'mappings');\n var file = util.getArg(sourceMap, 'file', null);\n\n // Once again, Sass deviates from the spec and supplies the version as a\n // string rather than a number, so we use loose equality checking here.\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n if (sourceRoot) {\n sourceRoot = util.normalize(sourceRoot);\n }\n\n sources = sources\n .map(String)\n // Some source maps produce relative source paths like \"./foo.js\" instead of\n // \"foo.js\". Normalize these first so that future comparisons will succeed.\n // See bugzil.la/1090768.\n .map(util.normalize)\n // Always ensure that absolute sources are internally stored relative to\n // the source root, if the source root is absolute. Not doing this would\n // be particularly problematic when the source root is a prefix of the\n // source (valid, but why??). See github issue #199 and bugzil.la/1188982.\n .map(function (source) {\n return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)\n ? util.relative(sourceRoot, source)\n : source;\n });\n\n // Pass `true` below to allow duplicate names and sources. While source maps\n // are intended to be compressed and deduplicated, the TypeScript compiler\n // sometimes generates source maps with duplicates in them. See Github issue\n // #72 and bugzil.la/889492.\n this._names = ArraySet.fromArray(names.map(String), true);\n this._sources = ArraySet.fromArray(sources, true);\n\n this._absoluteSources = this._sources.toArray().map(function (s) {\n return util.computeSourceURL(sourceRoot, s, aSourceMapURL);\n });\n\n this.sourceRoot = sourceRoot;\n this.sourcesContent = sourcesContent;\n this._mappings = mappings;\n this._sourceMapURL = aSourceMapURL;\n this.file = file;\n}\n\nBasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nBasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;\n\n/**\n * Utility function to find the index of a source. Returns -1 if not\n * found.\n */\nBasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n if (this._sources.has(relativeSource)) {\n return this._sources.indexOf(relativeSource);\n }\n\n // Maybe aSource is an absolute URL as returned by |sources|. In\n // this case we can't simply undo the transform.\n var i;\n for (i = 0; i < this._absoluteSources.length; ++i) {\n if (this._absoluteSources[i] == aSource) {\n return i;\n }\n }\n\n return -1;\n};\n\n/**\n * Create a BasicSourceMapConsumer from a SourceMapGenerator.\n *\n * @param SourceMapGenerator aSourceMap\n * The source map that will be consumed.\n * @param String aSourceMapURL\n * The URL at which the source map can be found (optional)\n * @returns BasicSourceMapConsumer\n */\nBasicSourceMapConsumer.fromSourceMap =\n function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {\n var smc = Object.create(BasicSourceMapConsumer.prototype);\n\n var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);\n var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);\n smc.sourceRoot = aSourceMap._sourceRoot;\n smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),\n smc.sourceRoot);\n smc.file = aSourceMap._file;\n smc._sourceMapURL = aSourceMapURL;\n smc._absoluteSources = smc._sources.toArray().map(function (s) {\n return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);\n });\n\n // Because we are modifying the entries (by converting string sources and\n // names to indices into the sources and names ArraySets), we have to make\n // a copy of the entry or else bad things happen. Shared mutable state\n // strikes again! See github issue #191.\n\n var generatedMappings = aSourceMap._mappings.toArray().slice();\n var destGeneratedMappings = smc.__generatedMappings = [];\n var destOriginalMappings = smc.__originalMappings = [];\n\n for (var i = 0, length = generatedMappings.length; i < length; i++) {\n var srcMapping = generatedMappings[i];\n var destMapping = new Mapping;\n destMapping.generatedLine = srcMapping.generatedLine;\n destMapping.generatedColumn = srcMapping.generatedColumn;\n\n if (srcMapping.source) {\n destMapping.source = sources.indexOf(srcMapping.source);\n destMapping.originalLine = srcMapping.originalLine;\n destMapping.originalColumn = srcMapping.originalColumn;\n\n if (srcMapping.name) {\n destMapping.name = names.indexOf(srcMapping.name);\n }\n\n destOriginalMappings.push(destMapping);\n }\n\n destGeneratedMappings.push(destMapping);\n }\n\n quickSort(smc.__originalMappings, util.compareByOriginalPositions);\n\n return smc;\n };\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nBasicSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {\n get: function () {\n return this._absoluteSources.slice();\n }\n});\n\n/**\n * Provide the JIT with a nice shape / hidden class.\n */\nfunction Mapping() {\n this.generatedLine = 0;\n this.generatedColumn = 0;\n this.source = null;\n this.originalLine = null;\n this.originalColumn = null;\n this.name = null;\n}\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nBasicSourceMapConsumer.prototype._parseMappings =\n function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n var generatedLine = 1;\n var previousGeneratedColumn = 0;\n var previousOriginalLine = 0;\n var previousOriginalColumn = 0;\n var previousSource = 0;\n var previousName = 0;\n var length = aStr.length;\n var index = 0;\n var cachedSegments = {};\n var temp = {};\n var originalMappings = [];\n var generatedMappings = [];\n var mapping, str, segment, end, value;\n\n while (index < length) {\n if (aStr.charAt(index) === ';') {\n generatedLine++;\n index++;\n previousGeneratedColumn = 0;\n }\n else if (aStr.charAt(index) === ',') {\n index++;\n }\n else {\n mapping = new Mapping();\n mapping.generatedLine = generatedLine;\n\n // Because each offset is encoded relative to the previous one,\n // many segments often have the same encoding. We can exploit this\n // fact by caching the parsed variable length fields of each segment,\n // allowing us to avoid a second parse if we encounter the same\n // segment again.\n for (end = index; end < length; end++) {\n if (this._charIsMappingSeparator(aStr, end)) {\n break;\n }\n }\n str = aStr.slice(index, end);\n\n segment = cachedSegments[str];\n if (segment) {\n index += str.length;\n } else {\n segment = [];\n while (index < end) {\n base64VLQ.decode(aStr, index, temp);\n value = temp.value;\n index = temp.rest;\n segment.push(value);\n }\n\n if (segment.length === 2) {\n throw new Error('Found a source, but no line and column');\n }\n\n if (segment.length === 3) {\n throw new Error('Found a source and line, but no column');\n }\n\n cachedSegments[str] = segment;\n }\n\n // Generated column.\n mapping.generatedColumn = previousGeneratedColumn + segment[0];\n previousGeneratedColumn = mapping.generatedColumn;\n\n if (segment.length > 1) {\n // Original source.\n mapping.source = previousSource + segment[1];\n previousSource += segment[1];\n\n // Original line.\n mapping.originalLine = previousOriginalLine + segment[2];\n previousOriginalLine = mapping.originalLine;\n // Lines are stored 0-based\n mapping.originalLine += 1;\n\n // Original column.\n mapping.originalColumn = previousOriginalColumn + segment[3];\n previousOriginalColumn = mapping.originalColumn;\n\n if (segment.length > 4) {\n // Original name.\n mapping.name = previousName + segment[4];\n previousName += segment[4];\n }\n }\n\n generatedMappings.push(mapping);\n if (typeof mapping.originalLine === 'number') {\n originalMappings.push(mapping);\n }\n }\n }\n\n quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);\n this.__generatedMappings = generatedMappings;\n\n quickSort(originalMappings, util.compareByOriginalPositions);\n this.__originalMappings = originalMappings;\n };\n\n/**\n * Find the mapping that best matches the hypothetical \"needle\" mapping that\n * we are searching for in the given \"haystack\" of mappings.\n */\nBasicSourceMapConsumer.prototype._findMapping =\n function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,\n aColumnName, aComparator, aBias) {\n // To return the position we are searching for, we must first find the\n // mapping for the given position and then return the opposite position it\n // points to. Because the mappings are sorted, we can use binary search to\n // find the best mapping.\n\n if (aNeedle[aLineName] <= 0) {\n throw new TypeError('Line must be greater than or equal to 1, got '\n + aNeedle[aLineName]);\n }\n if (aNeedle[aColumnName] < 0) {\n throw new TypeError('Column must be greater than or equal to 0, got '\n + aNeedle[aColumnName]);\n }\n\n return binarySearch.search(aNeedle, aMappings, aComparator, aBias);\n };\n\n/**\n * Compute the last column for each generated mapping. The last column is\n * inclusive.\n */\nBasicSourceMapConsumer.prototype.computeColumnSpans =\n function SourceMapConsumer_computeColumnSpans() {\n for (var index = 0; index < this._generatedMappings.length; ++index) {\n var mapping = this._generatedMappings[index];\n\n // Mappings do not contain a field for the last generated columnt. We\n // can come up with an optimistic estimate, however, by assuming that\n // mappings are contiguous (i.e. given two consecutive mappings, the\n // first mapping ends where the second one starts).\n if (index + 1 < this._generatedMappings.length) {\n var nextMapping = this._generatedMappings[index + 1];\n\n if (mapping.generatedLine === nextMapping.generatedLine) {\n mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;\n continue;\n }\n }\n\n // The last mapping for each line spans the entire line.\n mapping.lastGeneratedColumn = Infinity;\n }\n };\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nBasicSourceMapConsumer.prototype.originalPositionFor =\n function SourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._generatedMappings,\n \"generatedLine\",\n \"generatedColumn\",\n util.compareByGeneratedPositionsDeflated,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._generatedMappings[index];\n\n if (mapping.generatedLine === needle.generatedLine) {\n var source = util.getArg(mapping, 'source', null);\n if (source !== null) {\n source = this._sources.at(source);\n source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);\n }\n var name = util.getArg(mapping, 'name', null);\n if (name !== null) {\n name = this._names.at(name);\n }\n return {\n source: source,\n line: util.getArg(mapping, 'originalLine', null),\n column: util.getArg(mapping, 'originalColumn', null),\n name: name\n };\n }\n }\n\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nBasicSourceMapConsumer.prototype.hasContentsOfAllSources =\n function BasicSourceMapConsumer_hasContentsOfAllSources() {\n if (!this.sourcesContent) {\n return false;\n }\n return this.sourcesContent.length >= this._sources.size() &&\n !this.sourcesContent.some(function (sc) { return sc == null; });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nBasicSourceMapConsumer.prototype.sourceContentFor =\n function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n if (!this.sourcesContent) {\n return null;\n }\n\n var index = this._findSourceIndex(aSource);\n if (index >= 0) {\n return this.sourcesContent[index];\n }\n\n var relativeSource = aSource;\n if (this.sourceRoot != null) {\n relativeSource = util.relative(this.sourceRoot, relativeSource);\n }\n\n var url;\n if (this.sourceRoot != null\n && (url = util.urlParse(this.sourceRoot))) {\n // XXX: file:// URIs and absolute paths lead to unexpected behavior for\n // many users. We can help them out when they expect file:// URIs to\n // behave like it would if they were running a local HTTP server. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.\n var fileUriAbsPath = relativeSource.replace(/^file:\\/\\//, \"\");\n if (url.scheme == \"file\"\n && this._sources.has(fileUriAbsPath)) {\n return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]\n }\n\n if ((!url.path || url.path == \"/\")\n && this._sources.has(\"/\" + relativeSource)) {\n return this.sourcesContent[this._sources.indexOf(\"/\" + relativeSource)];\n }\n }\n\n // This function is used recursively from\n // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we\n // don't want to throw if we can't find the source - we just want to\n // return null, so we provide a flag to exit gracefully.\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + relativeSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or\n * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the\n * closest element that is smaller than or greater than the one we are\n * searching for, respectively, if the exact element cannot be found.\n * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based.\n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nBasicSourceMapConsumer.prototype.generatedPositionFor =\n function SourceMapConsumer_generatedPositionFor(aArgs) {\n var source = util.getArg(aArgs, 'source');\n source = this._findSourceIndex(source);\n if (source < 0) {\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n }\n\n var needle = {\n source: source,\n originalLine: util.getArg(aArgs, 'line'),\n originalColumn: util.getArg(aArgs, 'column')\n };\n\n var index = this._findMapping(\n needle,\n this._originalMappings,\n \"originalLine\",\n \"originalColumn\",\n util.compareByOriginalPositions,\n util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)\n );\n\n if (index >= 0) {\n var mapping = this._originalMappings[index];\n\n if (mapping.source === needle.source) {\n return {\n line: util.getArg(mapping, 'generatedLine', null),\n column: util.getArg(mapping, 'generatedColumn', null),\n lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)\n };\n }\n }\n\n return {\n line: null,\n column: null,\n lastColumn: null\n };\n };\n\nexports.BasicSourceMapConsumer = BasicSourceMapConsumer;\n\n/**\n * An IndexedSourceMapConsumer instance represents a parsed source map which\n * we can query for information. It differs from BasicSourceMapConsumer in\n * that it takes \"indexed\" source maps (i.e. ones with a \"sections\" field) as\n * input.\n *\n * The first parameter is a raw source map (either as a JSON string, or already\n * parsed to an object). According to the spec for indexed source maps, they\n * have the following attributes:\n *\n * - version: Which version of the source map spec this map is following.\n * - file: Optional. The generated file this source map is associated with.\n * - sections: A list of section definitions.\n *\n * Each value under the \"sections\" field has two fields:\n * - offset: The offset into the original specified at which this section\n * begins to apply, defined as an object with a \"line\" and \"column\"\n * field.\n * - map: A source map definition. This source map could also be indexed,\n * but doesn't have to be.\n *\n * Instead of the \"map\" field, it's also possible to have a \"url\" field\n * specifying a URL to retrieve a source map from, but that's currently\n * unsupported.\n *\n * Here's an example source map, taken from the source map spec[0], but\n * modified to omit a section which uses the \"url\" field.\n *\n * {\n * version : 3,\n * file: \"app.js\",\n * sections: [{\n * offset: {line:100, column:10},\n * map: {\n * version : 3,\n * file: \"section.js\",\n * sources: [\"foo.js\", \"bar.js\"],\n * names: [\"src\", \"maps\", \"are\", \"fun\"],\n * mappings: \"AAAA,E;;ABCDE;\"\n * }\n * }],\n * }\n *\n * The second parameter, if given, is a string whose value is the URL\n * at which the source map was found. This URL is used to compute the\n * sources array.\n *\n * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt\n */\nfunction IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {\n var sourceMap = aSourceMap;\n if (typeof aSourceMap === 'string') {\n sourceMap = util.parseSourceMapInput(aSourceMap);\n }\n\n var version = util.getArg(sourceMap, 'version');\n var sections = util.getArg(sourceMap, 'sections');\n\n if (version != this._version) {\n throw new Error('Unsupported version: ' + version);\n }\n\n this._sources = new ArraySet();\n this._names = new ArraySet();\n\n var lastOffset = {\n line: -1,\n column: 0\n };\n this._sections = sections.map(function (s) {\n if (s.url) {\n // The url field will require support for asynchronicity.\n // See https://github.com/mozilla/source-map/issues/16\n throw new Error('Support for url field in sections not implemented.');\n }\n var offset = util.getArg(s, 'offset');\n var offsetLine = util.getArg(offset, 'line');\n var offsetColumn = util.getArg(offset, 'column');\n\n if (offsetLine < lastOffset.line ||\n (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {\n throw new Error('Section offsets must be ordered and non-overlapping.');\n }\n lastOffset = offset;\n\n return {\n generatedOffset: {\n // The offset fields are 0-based, but we use 1-based indices when\n // encoding/decoding from VLQ.\n generatedLine: offsetLine + 1,\n generatedColumn: offsetColumn + 1\n },\n consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)\n }\n });\n}\n\nIndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);\nIndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;\n\n/**\n * The version of the source mapping spec that we are consuming.\n */\nIndexedSourceMapConsumer.prototype._version = 3;\n\n/**\n * The list of original sources.\n */\nObject.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {\n get: function () {\n var sources = [];\n for (var i = 0; i < this._sections.length; i++) {\n for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {\n sources.push(this._sections[i].consumer.sources[j]);\n }\n }\n return sources;\n }\n});\n\n/**\n * Returns the original source, line, and column information for the generated\n * source's line and column positions provided. The only argument is an object\n * with the following properties:\n *\n * - line: The line number in the generated source. The line number\n * is 1-based.\n * - column: The column number in the generated source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - source: The original source file, or null.\n * - line: The line number in the original source, or null. The\n * line number is 1-based.\n * - column: The column number in the original source, or null. The\n * column number is 0-based.\n * - name: The original identifier, or null.\n */\nIndexedSourceMapConsumer.prototype.originalPositionFor =\n function IndexedSourceMapConsumer_originalPositionFor(aArgs) {\n var needle = {\n generatedLine: util.getArg(aArgs, 'line'),\n generatedColumn: util.getArg(aArgs, 'column')\n };\n\n // Find the section containing the generated position we're trying to map\n // to an original position.\n var sectionIndex = binarySearch.search(needle, this._sections,\n function(needle, section) {\n var cmp = needle.generatedLine - section.generatedOffset.generatedLine;\n if (cmp) {\n return cmp;\n }\n\n return (needle.generatedColumn -\n section.generatedOffset.generatedColumn);\n });\n var section = this._sections[sectionIndex];\n\n if (!section) {\n return {\n source: null,\n line: null,\n column: null,\n name: null\n };\n }\n\n return section.consumer.originalPositionFor({\n line: needle.generatedLine -\n (section.generatedOffset.generatedLine - 1),\n column: needle.generatedColumn -\n (section.generatedOffset.generatedLine === needle.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n bias: aArgs.bias\n });\n };\n\n/**\n * Return true if we have the source content for every source in the source\n * map, false otherwise.\n */\nIndexedSourceMapConsumer.prototype.hasContentsOfAllSources =\n function IndexedSourceMapConsumer_hasContentsOfAllSources() {\n return this._sections.every(function (s) {\n return s.consumer.hasContentsOfAllSources();\n });\n };\n\n/**\n * Returns the original source content. The only argument is the url of the\n * original source file. Returns null if no original source content is\n * available.\n */\nIndexedSourceMapConsumer.prototype.sourceContentFor =\n function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n var content = section.consumer.sourceContentFor(aSource, true);\n if (content) {\n return content;\n }\n }\n if (nullOnMissing) {\n return null;\n }\n else {\n throw new Error('\"' + aSource + '\" is not in the SourceMap.');\n }\n };\n\n/**\n * Returns the generated line and column information for the original source,\n * line, and column positions provided. The only argument is an object with\n * the following properties:\n *\n * - source: The filename of the original source.\n * - line: The line number in the original source. The line number\n * is 1-based.\n * - column: The column number in the original source. The column\n * number is 0-based.\n *\n * and an object is returned with the following properties:\n *\n * - line: The line number in the generated source, or null. The\n * line number is 1-based. \n * - column: The column number in the generated source, or null.\n * The column number is 0-based.\n */\nIndexedSourceMapConsumer.prototype.generatedPositionFor =\n function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n\n // Only consider this section if the requested source is in the list of\n // sources of the consumer.\n if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {\n continue;\n }\n var generatedPosition = section.consumer.generatedPositionFor(aArgs);\n if (generatedPosition) {\n var ret = {\n line: generatedPosition.line +\n (section.generatedOffset.generatedLine - 1),\n column: generatedPosition.column +\n (section.generatedOffset.generatedLine === generatedPosition.line\n ? section.generatedOffset.generatedColumn - 1\n : 0)\n };\n return ret;\n }\n }\n\n return {\n line: null,\n column: null\n };\n };\n\n/**\n * Parse the mappings in a string in to a data structure which we can easily\n * query (the ordered arrays in the `this.__generatedMappings` and\n * `this.__originalMappings` properties).\n */\nIndexedSourceMapConsumer.prototype._parseMappings =\n function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {\n this.__generatedMappings = [];\n this.__originalMappings = [];\n for (var i = 0; i < this._sections.length; i++) {\n var section = this._sections[i];\n var sectionMappings = section.consumer._generatedMappings;\n for (var j = 0; j < sectionMappings.length; j++) {\n var mapping = sectionMappings[j];\n\n var source = section.consumer._sources.at(mapping.source);\n source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);\n this._sources.add(source);\n source = this._sources.indexOf(source);\n\n var name = null;\n if (mapping.name) {\n name = section.consumer._names.at(mapping.name);\n this._names.add(name);\n name = this._names.indexOf(name);\n }\n\n // The mappings coming from the consumer for the section have\n // generated positions relative to the start of the section, so we\n // need to offset them to be relative to the start of the concatenated\n // generated file.\n var adjustedMapping = {\n source: source,\n generatedLine: mapping.generatedLine +\n (section.generatedOffset.generatedLine - 1),\n generatedColumn: mapping.generatedColumn +\n (section.generatedOffset.generatedLine === mapping.generatedLine\n ? section.generatedOffset.generatedColumn - 1\n : 0),\n originalLine: mapping.originalLine,\n originalColumn: mapping.originalColumn,\n name: name\n };\n\n this.__generatedMappings.push(adjustedMapping);\n if (typeof adjustedMapping.originalLine === 'number') {\n this.__originalMappings.push(adjustedMapping);\n }\n }\n }\n\n quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);\n quickSort(this.__originalMappings, util.compareByOriginalPositions);\n };\n\nexports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;\n", "/* -*- Mode: js; js-indent-level: 2; -*- */\n/*\n * Copyright 2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\nvar SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;\nvar util = require('./util');\n\n// Matches a Windows-style `\\r\\n` newline or a `\\n` newline used by all other\n// operating systems these days (capturing the result).\nvar REGEX_NEWLINE = /(\\r?\\n)/;\n\n// Newline character code for charCodeAt() comparisons\nvar NEWLINE_CODE = 10;\n\n// Private symbol for identifying `SourceNode`s when multiple versions of\n// the source-map library are loaded. This MUST NOT CHANGE across\n// versions!\nvar isSourceNode = \"$$$isSourceNode$$$\";\n\n/**\n * SourceNodes provide a way to abstract over interpolating/concatenating\n * snippets of generated JavaScript source code while maintaining the line and\n * column information associated with the original source code.\n *\n * @param aLine The original line number.\n * @param aColumn The original column number.\n * @param aSource The original source's filename.\n * @param aChunks Optional. An array of strings which are snippets of\n * generated JS, or other SourceNodes.\n * @param aName The original identifier.\n */\nfunction SourceNode(aLine, aColumn, aSource, aChunks, aName) {\n this.children = [];\n this.sourceContents = {};\n this.line = aLine == null ? null : aLine;\n this.column = aColumn == null ? null : aColumn;\n this.source = aSource == null ? null : aSource;\n this.name = aName == null ? null : aName;\n this[isSourceNode] = true;\n if (aChunks != null) this.add(aChunks);\n}\n\n/**\n * Creates a SourceNode from generated code and a SourceMapConsumer.\n *\n * @param aGeneratedCode The generated code\n * @param aSourceMapConsumer The SourceMap for the generated code\n * @param aRelativePath Optional. The path that relative sources in the\n * SourceMapConsumer should be relative to.\n */\nSourceNode.fromStringWithSourceMap =\n function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {\n // The SourceNode we want to fill with the generated code\n // and the SourceMap\n var node = new SourceNode();\n\n // All even indices of this array are one line of the generated code,\n // while all odd indices are the newlines between two adjacent lines\n // (since `REGEX_NEWLINE` captures its match).\n // Processed fragments are accessed by calling `shiftNextLine`.\n var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);\n var remainingLinesIndex = 0;\n var shiftNextLine = function() {\n var lineContents = getNextLine();\n // The last line of a file might not have a newline.\n var newLine = getNextLine() || \"\";\n return lineContents + newLine;\n\n function getNextLine() {\n return remainingLinesIndex < remainingLines.length ?\n remainingLines[remainingLinesIndex++] : undefined;\n }\n };\n\n // We need to remember the position of \"remainingLines\"\n var lastGeneratedLine = 1, lastGeneratedColumn = 0;\n\n // The generate SourceNodes we need a code range.\n // To extract it current and last mapping is used.\n // Here we store the last mapping.\n var lastMapping = null;\n\n aSourceMapConsumer.eachMapping(function (mapping) {\n if (lastMapping !== null) {\n // We add the code from \"lastMapping\" to \"mapping\":\n // First check if there is a new line in between.\n if (lastGeneratedLine < mapping.generatedLine) {\n // Associate first line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n lastGeneratedLine++;\n lastGeneratedColumn = 0;\n // The remaining code is added without mapping\n } else {\n // There is no new line in between.\n // Associate the code between \"lastGeneratedColumn\" and\n // \"mapping.generatedColumn\" with \"lastMapping\"\n var nextLine = remainingLines[remainingLinesIndex] || '';\n var code = nextLine.substr(0, mapping.generatedColumn -\n lastGeneratedColumn);\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -\n lastGeneratedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n addMappingWithCode(lastMapping, code);\n // No more remaining code, continue\n lastMapping = mapping;\n return;\n }\n }\n // We add the generated code until the first mapping\n // to the SourceNode without any mapping.\n // Each line is added as separate string.\n while (lastGeneratedLine < mapping.generatedLine) {\n node.add(shiftNextLine());\n lastGeneratedLine++;\n }\n if (lastGeneratedColumn < mapping.generatedColumn) {\n var nextLine = remainingLines[remainingLinesIndex] || '';\n node.add(nextLine.substr(0, mapping.generatedColumn));\n remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);\n lastGeneratedColumn = mapping.generatedColumn;\n }\n lastMapping = mapping;\n }, this);\n // We have processed all mappings.\n if (remainingLinesIndex < remainingLines.length) {\n if (lastMapping) {\n // Associate the remaining code in the current line with \"lastMapping\"\n addMappingWithCode(lastMapping, shiftNextLine());\n }\n // and add the remaining lines without any mapping\n node.add(remainingLines.splice(remainingLinesIndex).join(\"\"));\n }\n\n // Copy sourcesContent into SourceNode\n aSourceMapConsumer.sources.forEach(function (sourceFile) {\n var content = aSourceMapConsumer.sourceContentFor(sourceFile);\n if (content != null) {\n if (aRelativePath != null) {\n sourceFile = util.join(aRelativePath, sourceFile);\n }\n node.setSourceContent(sourceFile, content);\n }\n });\n\n return node;\n\n function addMappingWithCode(mapping, code) {\n if (mapping === null || mapping.source === undefined) {\n node.add(code);\n } else {\n var source = aRelativePath\n ? util.join(aRelativePath, mapping.source)\n : mapping.source;\n node.add(new SourceNode(mapping.originalLine,\n mapping.originalColumn,\n source,\n code,\n mapping.name));\n }\n }\n };\n\n/**\n * Add a chunk of generated JS to this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.add = function SourceNode_add(aChunk) {\n if (Array.isArray(aChunk)) {\n aChunk.forEach(function (chunk) {\n this.add(chunk);\n }, this);\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n if (aChunk) {\n this.children.push(aChunk);\n }\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Add a chunk of generated JS to the beginning of this source node.\n *\n * @param aChunk A string snippet of generated JS code, another instance of\n * SourceNode, or an array where each member is one of those things.\n */\nSourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {\n if (Array.isArray(aChunk)) {\n for (var i = aChunk.length-1; i >= 0; i--) {\n this.prepend(aChunk[i]);\n }\n }\n else if (aChunk[isSourceNode] || typeof aChunk === \"string\") {\n this.children.unshift(aChunk);\n }\n else {\n throw new TypeError(\n \"Expected a SourceNode, string, or an array of SourceNodes and strings. Got \" + aChunk\n );\n }\n return this;\n};\n\n/**\n * Walk over the tree of JS snippets in this node and its children. The\n * walking function is called once for each snippet of JS and is passed that\n * snippet and the its original associated source's line/column location.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walk = function SourceNode_walk(aFn) {\n var chunk;\n for (var i = 0, len = this.children.length; i < len; i++) {\n chunk = this.children[i];\n if (chunk[isSourceNode]) {\n chunk.walk(aFn);\n }\n else {\n if (chunk !== '') {\n aFn(chunk, { source: this.source,\n line: this.line,\n column: this.column,\n name: this.name });\n }\n }\n }\n};\n\n/**\n * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between\n * each of `this.children`.\n *\n * @param aSep The separator.\n */\nSourceNode.prototype.join = function SourceNode_join(aSep) {\n var newChildren;\n var i;\n var len = this.children.length;\n if (len > 0) {\n newChildren = [];\n for (i = 0; i < len-1; i++) {\n newChildren.push(this.children[i]);\n newChildren.push(aSep);\n }\n newChildren.push(this.children[i]);\n this.children = newChildren;\n }\n return this;\n};\n\n/**\n * Call String.prototype.replace on the very right-most source snippet. Useful\n * for trimming whitespace from the end of a source node, etc.\n *\n * @param aPattern The pattern to replace.\n * @param aReplacement The thing to replace the pattern with.\n */\nSourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {\n var lastChild = this.children[this.children.length - 1];\n if (lastChild[isSourceNode]) {\n lastChild.replaceRight(aPattern, aReplacement);\n }\n else if (typeof lastChild === 'string') {\n this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);\n }\n else {\n this.children.push(''.replace(aPattern, aReplacement));\n }\n return this;\n};\n\n/**\n * Set the source content for a source file. This will be added to the SourceMapGenerator\n * in the sourcesContent field.\n *\n * @param aSourceFile The filename of the source file\n * @param aSourceContent The content of the source file\n */\nSourceNode.prototype.setSourceContent =\n function SourceNode_setSourceContent(aSourceFile, aSourceContent) {\n this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;\n };\n\n/**\n * Walk over the tree of SourceNodes. The walking function is called for each\n * source file content and is passed the filename and source content.\n *\n * @param aFn The traversal function.\n */\nSourceNode.prototype.walkSourceContents =\n function SourceNode_walkSourceContents(aFn) {\n for (var i = 0, len = this.children.length; i < len; i++) {\n if (this.children[i][isSourceNode]) {\n this.children[i].walkSourceContents(aFn);\n }\n }\n\n var sources = Object.keys(this.sourceContents);\n for (var i = 0, len = sources.length; i < len; i++) {\n aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);\n }\n };\n\n/**\n * Return the string representation of this source node. Walks over the tree\n * and concatenates all the various snippets together to one string.\n */\nSourceNode.prototype.toString = function SourceNode_toString() {\n var str = \"\";\n this.walk(function (chunk) {\n str += chunk;\n });\n return str;\n};\n\n/**\n * Returns the string representation of this source node along with a source\n * map.\n */\nSourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {\n var generated = {\n code: \"\",\n line: 1,\n column: 0\n };\n var map = new SourceMapGenerator(aArgs);\n var sourceMappingActive = false;\n var lastOriginalSource = null;\n var lastOriginalLine = null;\n var lastOriginalColumn = null;\n var lastOriginalName = null;\n this.walk(function (chunk, original) {\n generated.code += chunk;\n if (original.source !== null\n && original.line !== null\n && original.column !== null) {\n if(lastOriginalSource !== original.source\n || lastOriginalLine !== original.line\n || lastOriginalColumn !== original.column\n || lastOriginalName !== original.name) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n lastOriginalSource = original.source;\n lastOriginalLine = original.line;\n lastOriginalColumn = original.column;\n lastOriginalName = original.name;\n sourceMappingActive = true;\n } else if (sourceMappingActive) {\n map.addMapping({\n generated: {\n line: generated.line,\n column: generated.column\n }\n });\n lastOriginalSource = null;\n sourceMappingActive = false;\n }\n for (var idx = 0, length = chunk.length; idx < length; idx++) {\n if (chunk.charCodeAt(idx) === NEWLINE_CODE) {\n generated.line++;\n generated.column = 0;\n // Mappings end at eol\n if (idx + 1 === length) {\n lastOriginalSource = null;\n sourceMappingActive = false;\n } else if (sourceMappingActive) {\n map.addMapping({\n source: original.source,\n original: {\n line: original.line,\n column: original.column\n },\n generated: {\n line: generated.line,\n column: generated.column\n },\n name: original.name\n });\n }\n } else {\n generated.column++;\n }\n }\n });\n this.walkSourceContents(function (sourceFile, sourceContent) {\n map.setSourceContent(sourceFile, sourceContent);\n });\n\n return { code: generated.code, map: map };\n};\n\nexports.SourceNode = SourceNode;\n", "/*\n * Copyright 2009-2011 Mozilla Foundation and contributors\n * Licensed under the New BSD license. See LICENSE.txt or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\nexports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;\nexports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;\nexports.SourceNode = require('./lib/source-node').SourceNode;\n", "/* eslint-disable node/no-deprecated-api */\n\nvar toString = Object.prototype.toString\n\nvar isModern = (\n typeof Buffer !== 'undefined' &&\n typeof Buffer.alloc === 'function' &&\n typeof Buffer.allocUnsafe === 'function' &&\n typeof Buffer.from === 'function'\n)\n\nfunction isArrayBuffer (input) {\n return toString.call(input).slice(8, -1) === 'ArrayBuffer'\n}\n\nfunction fromArrayBuffer (obj, byteOffset, length) {\n byteOffset >>>= 0\n\n var maxLength = obj.byteLength - byteOffset\n\n if (maxLength < 0) {\n throw new RangeError(\"'offset' is out of bounds\")\n }\n\n if (length === undefined) {\n length = maxLength\n } else {\n length >>>= 0\n\n if (length > maxLength) {\n throw new RangeError(\"'length' is out of bounds\")\n }\n }\n\n return isModern\n ? Buffer.from(obj.slice(byteOffset, byteOffset + length))\n : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n return isModern\n ? Buffer.from(string, encoding)\n : new Buffer(string, encoding)\n}\n\nfunction bufferFrom (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (isArrayBuffer(value)) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n return isModern\n ? Buffer.from(value)\n : new Buffer(value)\n}\n\nmodule.exports = bufferFrom\n", "var SourceMapConsumer = require('source-map').SourceMapConsumer;\nvar path = require('path');\n\nvar fs;\ntry {\n fs = require('fs');\n if (!fs.existsSync || !fs.readFileSync) {\n // fs doesn't have all methods we need\n fs = null;\n }\n} catch (err) {\n /* nop */\n}\n\nvar bufferFrom = require('buffer-from');\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param {NodeModule} mod\n * @param {string} request\n */\nfunction dynamicRequire(mod, request) {\n return mod.require(request);\n}\n\n// Only install once if called multiple times\nvar errorFormatterInstalled = false;\nvar uncaughtShimInstalled = false;\n\n// If true, the caches are reset before a stack trace formatting operation\nvar emptyCacheBetweenOperations = false;\n\n// Supports {browser, node, auto}\nvar environment = \"auto\";\n\n// Maps a file path to a string containing the file contents\nvar fileContentsCache = {};\n\n// Maps a file path to a source map for that file\nvar sourceMapCache = {};\n\n// Regex for detecting source maps\nvar reSourceMap = /^data:application\\/json[^,]+base64,/;\n\n// Priority list of retrieve handlers\nvar retrieveFileHandlers = [];\nvar retrieveMapHandlers = [];\n\nfunction isInBrowser() {\n if (environment === \"browser\")\n return true;\n if (environment === \"node\")\n return false;\n return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === \"renderer\"));\n}\n\nfunction hasGlobalProcessEventEmitter() {\n return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));\n}\n\nfunction globalProcessVersion() {\n if ((typeof process === 'object') && (process !== null)) {\n return process.version;\n } else {\n return '';\n }\n}\n\nfunction globalProcessStderr() {\n if ((typeof process === 'object') && (process !== null)) {\n return process.stderr;\n }\n}\n\nfunction globalProcessExit(code) {\n if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) {\n return process.exit(code);\n }\n}\n\nfunction handlerExec(list) {\n return function(arg) {\n for (var i = 0; i < list.length; i++) {\n var ret = list[i](arg);\n if (ret) {\n return ret;\n }\n }\n return null;\n };\n}\n\nvar retrieveFile = handlerExec(retrieveFileHandlers);\n\nretrieveFileHandlers.push(function(path) {\n // Trim the path to make sure there is no extra whitespace.\n path = path.trim();\n if (/^file:/.test(path)) {\n // existsSync/readFileSync can't handle file protocol, but once stripped, it works\n path = path.replace(/file:\\/\\/\\/(\\w:)?/, function(protocol, drive) {\n return drive ?\n '' : // file:///C:/dir/file -> C:/dir/file\n '/'; // file:///root-dir/file -> /root-dir/file\n });\n }\n if (path in fileContentsCache) {\n return fileContentsCache[path];\n }\n\n var contents = '';\n try {\n if (!fs) {\n // Use SJAX if we are in the browser\n var xhr = new XMLHttpRequest();\n xhr.open('GET', path, /** async */ false);\n xhr.send(null);\n if (xhr.readyState === 4 && xhr.status === 200) {\n contents = xhr.responseText;\n }\n } else if (fs.existsSync(path)) {\n // Otherwise, use the filesystem\n contents = fs.readFileSync(path, 'utf8');\n }\n } catch (er) {\n /* ignore any errors */\n }\n\n return fileContentsCache[path] = contents;\n});\n\n// Support URLs relative to a directory, but be careful about a protocol prefix\n// in case we are in the browser (i.e. directories may start with \"http://\" or \"file:///\")\nfunction supportRelativeURL(file, url) {\n if (!file) return url;\n var dir = path.dirname(file);\n var match = /^\\w+:\\/\\/[^\\/]*/.exec(dir);\n var protocol = match ? match[0] : '';\n var startPath = dir.slice(protocol.length);\n if (protocol && /^\\/\\w\\:/.test(startPath)) {\n // handle file:///C:/ paths\n protocol += '/';\n return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\\\/g, '/');\n }\n return protocol + path.resolve(dir.slice(protocol.length), url);\n}\n\nfunction retrieveSourceMapURL(source) {\n var fileData;\n\n if (isInBrowser()) {\n try {\n var xhr = new XMLHttpRequest();\n xhr.open('GET', source, false);\n xhr.send(null);\n fileData = xhr.readyState === 4 ? xhr.responseText : null;\n\n // Support providing a sourceMappingURL via the SourceMap header\n var sourceMapHeader = xhr.getResponseHeader(\"SourceMap\") ||\n xhr.getResponseHeader(\"X-SourceMap\");\n if (sourceMapHeader) {\n return sourceMapHeader;\n }\n } catch (e) {\n }\n }\n\n // Get the URL of the source map\n fileData = retrieveFile(source);\n var re = /(?:\\/\\/[@#][\\s]*sourceMappingURL=([^\\s'\"]+)[\\s]*$)|(?:\\/\\*[@#][\\s]*sourceMappingURL=([^\\s*'\"]+)[\\s]*(?:\\*\\/)[\\s]*$)/mg;\n // Keep executing the search to find the *last* sourceMappingURL to avoid\n // picking up sourceMappingURLs from comments, strings, etc.\n var lastMatch, match;\n while (match = re.exec(fileData)) lastMatch = match;\n if (!lastMatch) return null;\n return lastMatch[1];\n};\n\n// Can be overridden by the retrieveSourceMap option to install. Takes a\n// generated source filename; returns a {map, optional url} object, or null if\n// there is no source map. The map field may be either a string or the parsed\n// JSON object (ie, it must be a valid argument to the SourceMapConsumer\n// constructor).\nvar retrieveSourceMap = handlerExec(retrieveMapHandlers);\nretrieveMapHandlers.push(function(source) {\n var sourceMappingURL = retrieveSourceMapURL(source);\n if (!sourceMappingURL) return null;\n\n // Read the contents of the source map\n var sourceMapData;\n if (reSourceMap.test(sourceMappingURL)) {\n // Support source map URL as a data url\n var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);\n sourceMapData = bufferFrom(rawData, \"base64\").toString();\n sourceMappingURL = source;\n } else {\n // Support source map URLs relative to the source URL\n sourceMappingURL = supportRelativeURL(source, sourceMappingURL);\n sourceMapData = retrieveFile(sourceMappingURL);\n }\n\n if (!sourceMapData) {\n return null;\n }\n\n return {\n url: sourceMappingURL,\n map: sourceMapData\n };\n});\n\nfunction mapSourcePosition(position) {\n var sourceMap = sourceMapCache[position.source];\n if (!sourceMap) {\n // Call the (overrideable) retrieveSourceMap function to get the source map.\n var urlAndMap = retrieveSourceMap(position.source);\n if (urlAndMap) {\n sourceMap = sourceMapCache[position.source] = {\n url: urlAndMap.url,\n map: new SourceMapConsumer(urlAndMap.map)\n };\n\n // Load all sources stored inline with the source map into the file cache\n // to pretend like they are already loaded. They may not exist on disk.\n if (sourceMap.map.sourcesContent) {\n sourceMap.map.sources.forEach(function(source, i) {\n var contents = sourceMap.map.sourcesContent[i];\n if (contents) {\n var url = supportRelativeURL(sourceMap.url, source);\n fileContentsCache[url] = contents;\n }\n });\n }\n } else {\n sourceMap = sourceMapCache[position.source] = {\n url: null,\n map: null\n };\n }\n }\n\n // Resolve the source URL relative to the URL of the source map\n if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {\n var originalPosition = sourceMap.map.originalPositionFor(position);\n\n // Only return the original position if a matching line was found. If no\n // matching line is found then we return position instead, which will cause\n // the stack trace to print the path and line for the compiled file. It is\n // better to give a precise location in the compiled file than a vague\n // location in the original file.\n if (originalPosition.source !== null) {\n originalPosition.source = supportRelativeURL(\n sourceMap.url, originalPosition.source);\n return originalPosition;\n }\n }\n\n return position;\n}\n\n// Parses code generated by FormatEvalOrigin(), a function inside V8:\n// https://code.google.com/p/v8/source/browse/trunk/src/messages.js\nfunction mapEvalOrigin(origin) {\n // Most eval() calls are in this format\n var match = /^eval at ([^(]+) \\((.+):(\\d+):(\\d+)\\)$/.exec(origin);\n if (match) {\n var position = mapSourcePosition({\n source: match[2],\n line: +match[3],\n column: match[4] - 1\n });\n return 'eval at ' + match[1] + ' (' + position.source + ':' +\n position.line + ':' + (position.column + 1) + ')';\n }\n\n // Parse nested eval() calls using recursion\n match = /^eval at ([^(]+) \\((.+)\\)$/.exec(origin);\n if (match) {\n return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';\n }\n\n // Make sure we still return useful information if we didn't find anything\n return origin;\n}\n\n// This is copied almost verbatim from the V8 source code at\n// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The\n// implementation of wrapCallSite() used to just forward to the actual source\n// code of CallSite.prototype.toString but unfortunately a new release of V8\n// did something to the prototype chain and broke the shim. The only fix I\n// could find was copy/paste.\nfunction CallSiteToString() {\n var fileName;\n var fileLocation = \"\";\n if (this.isNative()) {\n fileLocation = \"native\";\n } else {\n fileName = this.getScriptNameOrSourceURL();\n if (!fileName && this.isEval()) {\n fileLocation = this.getEvalOrigin();\n fileLocation += \", \"; // Expecting source position to follow.\n }\n\n if (fileName) {\n fileLocation += fileName;\n } else {\n // Source code does not originate from a file and is not native, but we\n // can still get the source position inside the source string, e.g. in\n // an eval string.\n fileLocation += \"<anonymous>\";\n }\n var lineNumber = this.getLineNumber();\n if (lineNumber != null) {\n fileLocation += \":\" + lineNumber;\n var columnNumber = this.getColumnNumber();\n if (columnNumber) {\n fileLocation += \":\" + columnNumber;\n }\n }\n }\n\n var line = \"\";\n var functionName = this.getFunctionName();\n var addSuffix = true;\n var isConstructor = this.isConstructor();\n var isMethodCall = !(this.isToplevel() || isConstructor);\n if (isMethodCall) {\n var typeName = this.getTypeName();\n // Fixes shim to be backward compatable with Node v0 to v4\n if (typeName === \"[object Object]\") {\n typeName = \"null\";\n }\n var methodName = this.getMethodName();\n if (functionName) {\n if (typeName && functionName.indexOf(typeName) != 0) {\n line += typeName + \".\";\n }\n line += functionName;\n if (methodName && functionName.indexOf(\".\" + methodName) != functionName.length - methodName.length - 1) {\n line += \" [as \" + methodName + \"]\";\n }\n } else {\n line += typeName + \".\" + (methodName || \"<anonymous>\");\n }\n } else if (isConstructor) {\n line += \"new \" + (functionName || \"<anonymous>\");\n } else if (functionName) {\n line += functionName;\n } else {\n line += fileLocation;\n addSuffix = false;\n }\n if (addSuffix) {\n line += \" (\" + fileLocation + \")\";\n }\n return line;\n}\n\nfunction cloneCallSite(frame) {\n var object = {};\n Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {\n object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];\n });\n object.toString = CallSiteToString;\n return object;\n}\n\nfunction wrapCallSite(frame, state) {\n // provides interface backward compatibility\n if (state === undefined) {\n state = { nextPosition: null, curPosition: null }\n }\n if(frame.isNative()) {\n state.curPosition = null;\n return frame;\n }\n\n // Most call sites will return the source file from getFileName(), but code\n // passed to eval() ending in \"//# sourceURL=...\" will return the source file\n // from getScriptNameOrSourceURL() instead\n var source = frame.getFileName() || frame.getScriptNameOrSourceURL();\n if (source) {\n var line = frame.getLineNumber();\n var column = frame.getColumnNumber() - 1;\n\n // Fix position in Node where some (internal) code is prepended.\n // See https://github.com/evanw/node-source-map-support/issues/36\n // Header removed in node at ^10.16 || >=11.11.0\n // v11 is not an LTS candidate, we can just test the one version with it.\n // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11\n var noHeader = /^v(10\\.1[6-9]|10\\.[2-9][0-9]|10\\.[0-9]{3,}|1[2-9]\\d*|[2-9]\\d|\\d{3,}|11\\.11)/;\n var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;\n if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {\n column -= headerLength;\n }\n\n var position = mapSourcePosition({\n source: source,\n line: line,\n column: column\n });\n state.curPosition = position;\n frame = cloneCallSite(frame);\n var originalFunctionName = frame.getFunctionName;\n frame.getFunctionName = function() {\n if (state.nextPosition == null) {\n return originalFunctionName();\n }\n return state.nextPosition.name || originalFunctionName();\n };\n frame.getFileName = function() { return position.source; };\n frame.getLineNumber = function() { return position.line; };\n frame.getColumnNumber = function() { return position.column + 1; };\n frame.getScriptNameOrSourceURL = function() { return position.source; };\n return frame;\n }\n\n // Code called using eval() needs special handling\n var origin = frame.isEval() && frame.getEvalOrigin();\n if (origin) {\n origin = mapEvalOrigin(origin);\n frame = cloneCallSite(frame);\n frame.getEvalOrigin = function() { return origin; };\n return frame;\n }\n\n // If we get here then we were unable to change the source position\n return frame;\n}\n\n// This function is part of the V8 stack trace API, for more info see:\n// https://v8.dev/docs/stack-trace-api\nfunction prepareStackTrace(error, stack) {\n if (emptyCacheBetweenOperations) {\n fileContentsCache = {};\n sourceMapCache = {};\n }\n\n var name = error.name || 'Error';\n var message = error.message || '';\n var errorString = name + \": \" + message;\n\n var state = { nextPosition: null, curPosition: null };\n var processedStack = [];\n for (var i = stack.length - 1; i >= 0; i--) {\n processedStack.push('\\n at ' + wrapCallSite(stack[i], state));\n state.nextPosition = state.curPosition;\n }\n state.curPosition = state.nextPosition = null;\n return errorString + processedStack.reverse().join('');\n}\n\n// Generate position and snippet of original source with pointer\nfunction getErrorSource(error) {\n var match = /\\n at [^(]+ \\((.*):(\\d+):(\\d+)\\)/.exec(error.stack);\n if (match) {\n var source = match[1];\n var line = +match[2];\n var column = +match[3];\n\n // Support the inline sourceContents inside the source map\n var contents = fileContentsCache[source];\n\n // Support files on disk\n if (!contents && fs && fs.existsSync(source)) {\n try {\n contents = fs.readFileSync(source, 'utf8');\n } catch (er) {\n contents = '';\n }\n }\n\n // Format the line from the original source code like node does\n if (contents) {\n var code = contents.split(/(?:\\r\\n|\\r|\\n)/)[line - 1];\n if (code) {\n return source + ':' + line + '\\n' + code + '\\n' +\n new Array(column).join(' ') + '^';\n }\n }\n }\n return null;\n}\n\nfunction printErrorAndExit (error) {\n var source = getErrorSource(error);\n\n // Ensure error is printed synchronously and not truncated\n var stderr = globalProcessStderr();\n if (stderr && stderr._handle && stderr._handle.setBlocking) {\n stderr._handle.setBlocking(true);\n }\n\n if (source) {\n console.error();\n console.error(source);\n }\n\n console.error(error.stack);\n globalProcessExit(1);\n}\n\nfunction shimEmitUncaughtException () {\n var origEmit = process.emit;\n\n process.emit = function (type) {\n if (type === 'uncaughtException') {\n var hasStack = (arguments[1] && arguments[1].stack);\n var hasListeners = (this.listeners(type).length > 0);\n\n if (hasStack && !hasListeners) {\n return printErrorAndExit(arguments[1]);\n }\n }\n\n return origEmit.apply(this, arguments);\n };\n}\n\nvar originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);\nvar originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);\n\nexports.wrapCallSite = wrapCallSite;\nexports.getErrorSource = getErrorSource;\nexports.mapSourcePosition = mapSourcePosition;\nexports.retrieveSourceMap = retrieveSourceMap;\n\nexports.install = function(options) {\n options = options || {};\n\n if (options.environment) {\n environment = options.environment;\n if ([\"node\", \"browser\", \"auto\"].indexOf(environment) === -1) {\n throw new Error(\"environment \" + environment + \" was unknown. Available options are {auto, browser, node}\")\n }\n }\n\n // Allow sources to be found by methods other than reading the files\n // directly from disk.\n if (options.retrieveFile) {\n if (options.overrideRetrieveFile) {\n retrieveFileHandlers.length = 0;\n }\n\n retrieveFileHandlers.unshift(options.retrieveFile);\n }\n\n // Allow source maps to be found by methods other than reading the files\n // directly from disk.\n if (options.retrieveSourceMap) {\n if (options.overrideRetrieveSourceMap) {\n retrieveMapHandlers.length = 0;\n }\n\n retrieveMapHandlers.unshift(options.retrieveSourceMap);\n }\n\n // Support runtime transpilers that include inline source maps\n if (options.hookRequire && !isInBrowser()) {\n // Use dynamicRequire to avoid including in browser bundles\n var Module = dynamicRequire(module, 'module');\n var $compile = Module.prototype._compile;\n\n if (!$compile.__sourceMapSupport) {\n Module.prototype._compile = function(content, filename) {\n fileContentsCache[filename] = content;\n sourceMapCache[filename] = undefined;\n return $compile.call(this, content, filename);\n };\n\n Module.prototype._compile.__sourceMapSupport = true;\n }\n }\n\n // Configure options\n if (!emptyCacheBetweenOperations) {\n emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?\n options.emptyCacheBetweenOperations : false;\n }\n\n // Install the error reformatter\n if (!errorFormatterInstalled) {\n errorFormatterInstalled = true;\n Error.prepareStackTrace = prepareStackTrace;\n }\n\n if (!uncaughtShimInstalled) {\n var installHandler = 'handleUncaughtExceptions' in options ?\n options.handleUncaughtExceptions : true;\n\n // Do not override 'uncaughtException' with our own handler in Node.js\n // Worker threads. Workers pass the error to the main thread as an event,\n // rather than printing something to stderr and exiting.\n try {\n // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.\n var worker_threads = dynamicRequire(module, 'worker_threads');\n if (worker_threads.isMainThread === false) {\n installHandler = false;\n }\n } catch(e) {}\n\n // Provide the option to not install the uncaught exception handler. This is\n // to support other uncaught exception handlers (in test frameworks, for\n // example). If this handler is not installed and there are no other uncaught\n // exception handlers, uncaught exceptions will be caught by node's built-in\n // exception handler and the process will still be terminated. However, the\n // generated JavaScript code will be shown above the stack trace instead of\n // the original source code.\n if (installHandler && hasGlobalProcessEventEmitter()) {\n uncaughtShimInstalled = true;\n shimEmitUncaughtException();\n }\n }\n};\n\nexports.resetRetrieveHandlers = function() {\n retrieveFileHandlers.length = 0;\n retrieveMapHandlers.length = 0;\n\n retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);\n retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);\n\n retrieveSourceMap = handlerExec(retrieveMapHandlers);\n retrieveFile = handlerExec(retrieveFileHandlers);\n}\n", "#!/usr/bin/env node\n\nimport program from 'commander'\n\nimport { getCountryFlag } from './index'\nimport * as Sentry from \"@sentry/node\";\n\n// Importing @sentry/tracing patches the global hub for tracing to work.\nimport * as Tracing from \"@sentry/tracing\";\nimport { RewriteFrames } from '@sentry/integrations';\nimport 'source-map-support/register';\n\nSentry.init({\n dsn: \"https://aec0873e750c49b082fe3594def15af1@o1116132.ingest.sentry.io/6149280\",\n\n // We recommend adjusting this value in production, or using tracesSampler\n // for finer control\n tracesSampleRate: 1.0,\n integrations: [new RewriteFrames({root: global.__rootdir__})]\n});\n\nprogram\n .version('0.1.0')\n .name('country-flag-cli')\n .command('get <flag>')\n .action((flag) => {\n const transaction = Sentry.startTransaction({\n op: \"get flag from 2 alpha code\",\n name: \"GET flag from 2 alpha code\"\n })\n try {\n const result = getCountryFlag(flag);\n if (result === undefined) throw new Error(`Flag: ${flag} \\nResult: ${result}\\n`)\n console.log(result);\n } catch (e) {\n console.error(e);\n Sentry.captureException(e);\n } finally {\n transaction.finish()\n }\n })\n\nprogram.parse(process.argv)\n", "export function getCountryFlag (countryCode: string): string | undefined {\n if (countryCode.length != 2) { return undefined}\n return countryCode.toUpperCase().replace(/./g, char => \n String.fromCodePoint(127397 + char.charCodeAt(0)));\n}\n ", "require('./').install();\n"],
5
+ "mappings": ";qmBAAA,mBAIA,GAAI,IAAe,QAAQ,UAAU,aACjC,GAAQ,QAAQ,iBAAiB,MACjC,GAAO,QAAQ,QACf,GAAU,GAAK,QACf,GAAW,GAAK,SAChB,GAAK,QAAQ,MAMjB,QAAQ,QAAQ,SAAS,EAAS,IAMlC,GAAU,GAAO,QAAU,GAAI,GAM/B,GAAQ,QAAU,EAMlB,GAAQ,OAAS,GAUjB,YAAgB,EAAO,EAAa,CAClC,KAAK,MAAQ,EACb,KAAK,SAAW,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