From cb449f563ee3fe35a3d592949ade3b5c5a9e5857 Mon Sep 17 00:00:00 2001 From: build-token <build-token> Date: Thu, 24 Aug 2023 09:02:30 +0000 Subject: [PATCH] publish: Merge branch '25-follow-up-from-detailed-sentry-logs' into 'main' generated from commit 772de020d15d7b0e201addc1a8195fdcf51822e2 --- index.js | 29080 +++++++++++++++++++++--------------------- onDeleteAccount.js | 29141 ++++++++++++++++++++++--------------------- 2 files changed, 29220 insertions(+), 29001 deletions(-) diff --git a/index.js b/index.js index eeb34b9..d22c8f8 100644 --- a/index.js +++ b/index.js @@ -27,13 +27,13 @@ const { const { consultationMesuresDetailleesMaxPower, consultationMesuresDetaillees, -} = __webpack_require__(1600) +} = __webpack_require__(1680) const { updateBoConsent, createBoConsent, getBoConsent, deleteBoConsent, -} = __webpack_require__(1601) +} = __webpack_require__(1681) const { verifyUserIdentity, activateContract, @@ -43,7 +43,7 @@ const { } = __webpack_require__(1719) const { getAccount, saveAccountData } = __webpack_require__(1730) const { isLocal, isDev } = __webpack_require__(1731) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) // eslint-disable-next-line const Tracing = __webpack_require__(1732) // Needed for tracking performance in Sentry const { version } = __webpack_require__(1769) @@ -95,6 +95,11 @@ Sentry.init({ * @param {{secret: fields}} cozyParameters */ async function start(fields, cozyParameters) { + const transaction = Sentry.startTransaction({ + op: 'konnector', + name: 'SGE Konnector', + }) + transaction.startChild({ op: 'Konnector starting' }) try { log('info', 'Konnector configuration ...') log('info', `isManual execution: ${manualExecution}`) @@ -105,10 +110,6 @@ async function start(fields, cozyParameters) { 'NO_DATA is enabled, konnector will stop after verifyUserIdentity()' ) } - const transaction = Sentry.startTransaction({ - op: 'konnector', - name: 'SGE Konnector', - }) const pointId = parsePointId(parseInt(fields.pointId)) let baseUrl = fields.wso2BaseUrl @@ -138,8 +139,10 @@ async function start(fields, cozyParameters) { ) { const errorMessage = 'Missing configuration secrets' log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { section: 'start' }, + }) + throw new Error(errors.VENDOR_DOWN) } /** @@ -250,8 +253,10 @@ async function start(fields, cozyParameters) { if (!userConsent) { const errorMessage = 'No user consent found' log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { section: 'start' }, + }) + throw new Error(errors.VENDOR_DOWN) } const consentEndDate = Date.parse(userConsent.endDate) @@ -281,7 +286,16 @@ async function start(fields, cozyParameters) { transaction.finish() log('info', 'Konnector success') } catch (error) { - log('debug', 'error catched in start()', error) + const errorMessage = `SGE konnector encountered an error. Response data: ${JSON.stringify( + error.message + )}` + Sentry.captureMessage(errorMessage, { + tags: { + section: 'start', + }, + }) + transaction.setStatus(Tracing.spanStatusfromHttpCode(409)) + transaction.finish() await Sentry.flush() throw error } @@ -325,14 +339,18 @@ async function deleteConsent( } else { const errorMessage = `No service id retrieved from BO` log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { section: 'start' }, + }) + throw new Error(errors.VENDOR_DOWN) } if (isConsentExpired) { - Sentry.captureException('Consent expired') - throw errors.USER_ACTION_NEEDED_OAUTH_OUTDATED + Sentry.captureException('Consent expired', { + tags: { section: 'start' }, + }) + throw new Error(errors.USER_ACTION_NEEDED_OAUTH_OUTDATED) } - throw errors.TERMS_VERSION_MISMATCH + throw new Error(errors.TERMS_VERSION_MISMATCH) } /** @@ -405,7 +423,9 @@ async function getData(url, apiAuthKey, userLogin, pointId) { }).catch(err => { log('error', 'consultationMesuresDetaillees') log('error', err) - Sentry.captureException('consultationMesuresDetaillees:', err) + Sentry.captureException(`consultationMesuresDetaillees: ${err}`, { + tags: { section: 'getData' }, + }) return err }) @@ -448,7 +468,9 @@ async function getMaxPowerData(url, apiAuthKey, userLogin, pointId) { }).catch(err => { log('error', 'getMaxPowerData') log('error', err) - Sentry.captureException('getMaxPowerDate') + Sentry.captureException(`getMaxPowerData: ${err}`, { + tags: { section: 'getMaxPowerData' }, + }) return err }) @@ -501,7 +523,7 @@ async function getDataHalfHour(url, apiAuthKey, userLogin, pointId) { // If manual execution, retrieve only 1 week otherwise retrieve 4 weeks const MAX_HISTO = manualExecution ? 1 : 4 - for (var i = 0; i < MAX_HISTO; i++) { + for (let i = 0; i < MAX_HISTO; i++) { log('info', 'launch process with history') const incrementedStartDateString = moment(startLoadDate) .subtract(7 * i, 'day') @@ -524,7 +546,12 @@ async function getDataHalfHour(url, apiAuthKey, userLogin, pointId) { }).catch(err => { log('error', 'consultationMesuresDetaillees half-hour') log('error', err) - Sentry.captureException('consultationMesuresDetaillees half-hour') + Sentry.captureException( + `consultationMesuresDetaillees half-hour: ${err}`, + { + tags: { section: 'getDataHalfHour' }, + } + ) return err }) @@ -570,7 +597,9 @@ function processData(doctype = 'com.grandlyon.enedis.day') { } catch (e) { if (doctype === 'com.grandlyon.enedis.minute') { const errorMessage = `No half-hour activated. Issue: ${result.Envelope.Body.Fault.faultstring}` - Sentry.captureMessage(errorMessage) + Sentry.captureMessage(errorMessage, { + tags: { section: 'processData' }, + }) log('warn', errorMessage) } else { log('warn', `Unknown error ${e}`) @@ -229084,6 +229113,7 @@ module.exports = { // @ts-check const { log } = __webpack_require__(1) const moment = __webpack_require__(1417) +const Sentry = __webpack_require__(1600) /** * Return User PDL @@ -229293,7 +229323,16 @@ function parsePointId(pointId) { } else if (strPointId.length === 13) { return `0${strPointId}` } else { - throw new Error(`PointId ${pointId} is malformed`) + const errorMessage = 'PointId is malformed' + Sentry.captureException(errorMessage, { + tags: { + section: 'parsePointId', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errorMessage) } } @@ -229318,4664 +229357,4914 @@ module.exports = { /***/ }), /* 1600 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -// @ts-check -const { log } = __webpack_require__(1) +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), +/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), +/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), +/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), +/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), +/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), +/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), +/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), +/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), +/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), +/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), +/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), +/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), +/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), +/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), +/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), +/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), +/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), +/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), +/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), +/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), +/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), +/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), +/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), +/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), +/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), +/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), +/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), +/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), +/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), +/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), +/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), +/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), +/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), +/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), +/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1679); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1616); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1617); +/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1626); +/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1634); +/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1650); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1666); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1675); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); +/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1676); +/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1651); +/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1635); -/** - * Get daily data up to 36 months & P max - * @param {string} pointId - * @param {string} appLogin - * @param {string} startDate - * @param {string} endDate - * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType - * @param {'EA' | 'PA' | 'PMA'} unit - * @returns {string} - */ -function consultationMesuresDetaillees( - pointId, - appLogin, - startDate, - endDate, - mesureType = 'ENERGIE', - unit = 'EA' -) { - log( - 'info', - `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterMesuresDetaillees> - <demande> - <initiateurLogin>${appLogin}</initiateurLogin> - <pointId>${pointId}</pointId> - <mesuresTypeCode>${mesureType}</mesuresTypeCode> - <grandeurPhysique>${unit}</grandeurPhysique> - <soutirage>true</soutirage> - <injection>false</injection> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <mesuresCorrigees>false</mesuresCorrigees> - <accordClient>true</accordClient> - </demande> - </v2:consulterMesuresDetaillees> - </soapenv:Body> - </soapenv:Envelope> - ` -} -/** - * Get user max power - * @param {string} pointId - * @param {string} appLogin - * @param {string} startDate - * @param {string} endDate - * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType - * @param {'EA' | 'PA' | 'PMA'} unit - * @returns {string} - */ -function consultationMesuresDetailleesMaxPower( - pointId, - appLogin, - startDate, - endDate, - mesureType = 'PMAX', - unit = 'PMA' -) { - log( - 'info', - `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterMesuresDetaillees> - <demande> - <initiateurLogin>${appLogin}</initiateurLogin> - <pointId>${pointId}</pointId> - <mesuresTypeCode>${mesureType}</mesuresTypeCode> - <grandeurPhysique>${unit}</grandeurPhysique> - <soutirage>true</soutirage> - <injection>false</injection> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <mesuresPas>P1D</mesuresPas> - <mesuresCorrigees>false</mesuresCorrigees> - <accordClient>true</accordClient> - </demande> - </v2:consulterMesuresDetaillees> - </soapenv:Body> - </soapenv:Envelope> - ` -} -/** - * Get user technical data (contract start date) - * @param {string} pointId - * @param {string} appLogin - * @returns {string} - */ -function consulterDonneesTechniquesContractuelles( - pointId, - appLogin, - consent = true -) { - log('info', `Query consulterDonneesTechniquesContractuelles`) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consulterdonneestechniquescontractuelles/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterDonneesTechniquesContractuelles> - <pointId>${pointId}</pointId> - <loginUtilisateur>${appLogin}</loginUtilisateur> - <autorisationClient>${consent}</autorisationClient> - </v2:consulterDonneesTechniquesContractuelles> - </soapenv:Body> - </soapenv:Envelope> - ` + + + + + + + + + + +; +; + +; +; + +const INTEGRATIONS = { + ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, + ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, +}; + +// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like +// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. +const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); +if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; } + +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 1601 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), +/* harmony export */ "Hub": () => (/* binding */ Hub), +/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), +/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), +/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), +/* harmony export */ "makeMain": () => (/* binding */ makeMain), +/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1605); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1606); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1603); + + + + +const NIL_EVENT_ID = '00000000000000000000000000000000'; + /** - * Use rechercherPoint to find user PDL if exist - * @param {string} lastname - * @param {string} postalCode - * @param {string} inseeCode - * @param {string} address - * @param {string} [escalierEtEtageEtAppartement] - * @returns {string} PDL + * API compatibility version of this hub. + * + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * + * @hidden */ -function rechercherPoint( - appLogin, - lastname, - postalCode, - inseeCode, - address, - escalierEtEtageEtAppartement -) { - log( - 'info', - `Query rechercherPoint - postal code : ${postalCode} / insee code: ${inseeCode}` - ) - if (escalierEtEtageEtAppartement) { - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherPoint> - <criteres> - <adresseInstallation> - <escalierEtEtageEtAppartement>${escalierEtEtageEtAppartement}</escalierEtEtageEtAppartement> - <numeroEtNomVoie>${address}</numeroEtNomVoie> - <codePostal>${postalCode}</codePostal> - <codeInseeCommune>${inseeCode}</codeInseeCommune> - </adresseInstallation> - <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> - <rechercheHorsPerimetre>true</rechercheHorsPerimetre> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherPoint> - </soapenv:Body> - </soapenv:Envelope>` - } - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherPoint> - <criteres> - <adresseInstallation> - <numeroEtNomVoie>${address}</numeroEtNomVoie> - <codePostal>${postalCode}</codePostal> - <codeInseeCommune>${inseeCode}</codeInseeCommune> - </adresseInstallation> - <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> - <rechercheHorsPerimetre>true</rechercheHorsPerimetre> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherPoint> - </soapenv:Body> - </soapenv:Envelope>` -} +const API_VERSION = 4; /** - * Search if user as a service - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @returns {*} + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. */ -function rechercherServicesSouscritsMesures(appLogin, contractId, pointId) { - log('info', `Query rechercherServicesSouscritsMesures`) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/rechercherservicessouscritsmesures/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherServicesSouscritsMesures> - <criteres> - <pointId>${pointId}</pointId> - <contratId>${contractId}</contratId> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherServicesSouscritsMesures> - </soapenv:Body> - </soapenv:Envelope>` -} +const DEFAULT_BREADCRUMBS = 100; /** - * Activate half hour data collect for user - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @param {string} lastname - * @param {string} startDate - * @param {string} endDate - * @returns {*} + * A layer in the process stack. + * @hidden */ -function commanderCollectePublicationMesures( - appLogin, - contractId, - pointId, - lastname, - startDate, - endDate -) { - log( - 'info', - `Query commanderCollectePublicationMesures - between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/commandercollectepublicationmesures/v3.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:commanderCollectePublicationMesures> - <demande> - <donneesGenerales> - <objetCode>AME</objetCode> - <pointId>${pointId}</pointId> - <initiateurLogin>${appLogin}</initiateurLogin> - <contratId>${contractId}</contratId> - </donneesGenerales> - <accesMesures> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <declarationAccordClient> - <accord>true</accord> - <personnePhysique> - <nom>${lastname}</nom> - </personnePhysique> - </declarationAccordClient> - <mesuresTypeCode>CDC</mesuresTypeCode> - <soutirage>true</soutirage> - <injection>false</injection> - <mesuresPas>PT30M</mesuresPas> - <mesuresCorrigees>false</mesuresCorrigees> - <transmissionRecurrente>false</transmissionRecurrente> - <periodiciteTransmission>P1D</periodiciteTransmission> - </accesMesures> - </demande> - </v2:commanderCollectePublicationMesures> - </soapenv:Body> - </soapenv:Envelope>` -} /** - * Stop the user consent - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @param {number} serviceSouscritId - * @returns {*} + * @inheritDoc */ -function commanderArretServiceSouscritMesures( - appLogin, - contractId, - pointId, - serviceSouscritId -) { - log( - 'info', - `Query commanderArretServiceSouscritMesures - serviceSouscritId: ${serviceSouscritId}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/commanderarretservicesouscritmesures/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:commanderArretServiceSouscritMesures> - <demande> - <donneesGenerales> - <objetCode>ASS</objetCode> - <pointId>${pointId}</pointId> - <initiateurLogin>${appLogin}</initiateurLogin> - <contratId>${contractId}</contratId> - </donneesGenerales> - <arretServiceSouscrit> - <serviceSouscritId>${serviceSouscritId}</serviceSouscritId> - </arretServiceSouscrit> - </demande> - </v2:commanderArretServiceSouscritMesures> - </soapenv:Body> - </soapenv:Envelope>` -} - -module.exports = { - consulterDonneesTechniquesContractuelles, - consultationMesuresDetailleesMaxPower, - consultationMesuresDetaillees, - rechercherPoint, - rechercherServicesSouscritsMesures, - commanderCollectePublicationMesures, - commanderArretServiceSouscritMesures, -} +class Hub { + /** Is a {@link Layer}[] containing the client and scope */ + __init() {this._stack = [{}];} + /** Contains the last event id of a captured event. */ -/***/ }), -/* 1601 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. + */ + constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); + this.getStackTop().scope = scope; + if (client) { + this.bindClient(client); + } + } -// @ts-check -const { log, errors } = __webpack_require__(1) -const { default: axios } = __webpack_require__(1602) -const Sentry = __webpack_require__(1639) + /** + * @inheritDoc + */ + isOlderThan(version) { + return this._version < version; + } -/** - * @param {string} pointID - * @param {string} lastname - * @param {string} firstname - * @param {string} address - * @param {string} postalCode - * @param {string} inseeCode - * @param {string} city - * @param {boolean} safetyOnBoarding - * @returns {Promise<Consent>} - */ -async function createBoConsent( - url, - token, - pointID, - lastname, - firstname, - address, - postalCode, - inseeCode, - city, - safetyOnBoarding -) { - log('info', `Query createBoConsent`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, + /** + * @inheritDoc + */ + bindClient(client) { + const top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); + } } - try { - const { data } = await axios.post( - `${url}/consent`, - { - pointID, - lastname, - firstname, - address, - postalCode, - inseeCode, - city, - safetyOnBoarding, - }, - headers - ) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE + /** + * @inheritDoc + */ + pushScope() { + // We want to clone the content of prev scope + const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); + this.getStack().push({ + client: this.getClient(), + scope, + }); + return scope; } -} -/** - * @param {string} url - * @param {string} token - * @param {Consent} consent - * @param {string} serviceId - * @returns {Promise<Consent>} - */ -async function updateBoConsent(url, token, consent, serviceId) { - log('info', `Query updateBoConsent`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, + /** + * @inheritDoc + */ + popScope() { + if (this.getStack().length <= 1) return false; + return !!this.getStack().pop(); } - try { - let consentId = '' - if (consent.ID) { - consentId = consent.ID.toString() + /** + * @inheritDoc + */ + withScope(callback) { + const scope = this.pushScope(); + try { + callback(scope); + } finally { + this.popScope(); } - const { data } = await axios.put( - `${url}/consent/${consentId}`, - { - ...consent, - serviceId: parseInt(serviceId), - }, - headers - ) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE } -} -/** - * @param {number} boId - * @returns {Promise<Consent>} - */ -async function getBoConsent(url, token, boId) { - log('info', `Query getBoConsent ${boId}`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, + /** + * @inheritDoc + */ + getClient() { + return this.getStackTop().client ; } - try { - const { data } = await axios.get(`${url}/consent/${boId}`, headers) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE + + /** Returns the scope of the top stack. */ + getScope() { + return this.getStackTop().scope; } -} -/** - * Delete BO consent - * @param {string} url - * @param {string} token - * @param {number} boId - * @returns - */ -async function deleteBoConsent(url, token, boId) { - log('info', `Query deleteBoConsent ${boId}`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, + /** Returns the scope stack for domains or the process. */ + getStack() { + return this._stack; } - try { - const { data } = await axios.delete(`${url}/consent/${boId}`, headers) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE + + /** Returns the topmost scope layer in the order domain > local > process. */ + getStackTop() { + return this._stack[this._stack.length - 1]; } -} -module.exports = { - createBoConsent, - updateBoConsent, - getBoConsent, - deleteBoConsent, -} + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint) { + const syntheticException = new Error('Sentry syntheticException'); + this._lastEventId = + this._withClient((client, scope) => { + return client.captureException( + exception, + { + originalException: exception, + syntheticException, + ...hint, + }, + scope, + ); + }) || NIL_EVENT_ID; + return this._lastEventId; + } + /** + * @inheritDoc + */ + captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level, + hint, + ) { + const syntheticException = new Error(message); + this._lastEventId = + this._withClient((client, scope) => { + return client.captureMessage( + message, + level, + { + originalException: message, + syntheticException, + ...hint, + }, + scope, + ); + }) || NIL_EVENT_ID; + return this._lastEventId; + } -/***/ }), -/* 1602 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + captureEvent(event, hint) { + const clientId = + this._withClient((client, scope) => { + return client.captureEvent(event, { ...hint }, scope); + }) || NIL_EVENT_ID; -module.exports = __webpack_require__(1603); + if (event.type !== 'transaction') { + this._lastEventId = clientId; + } -/***/ }), -/* 1603 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return clientId; + } -"use strict"; + /** + * @inheritDoc + */ + lastEventId() { + return this._lastEventId; + } + /** + * @inheritDoc + */ + addBreadcrumb(breadcrumb, hint) { + const { scope, client } = this.getStackTop(); -var utils = __webpack_require__(1604); -var bind = __webpack_require__(1605); -var Axios = __webpack_require__(1606); -var mergeConfig = __webpack_require__(1634); -var defaults = __webpack_require__(1611); + if (!scope || !client) return; -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); + // eslint-disable-next-line @typescript-eslint/unbound-method + const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = + (client.getOptions && client.getOptions()) || {}; - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); + if (maxBreadcrumbs <= 0) return; - // Copy context to instance - utils.extend(instance, context); + const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); + const mergedBreadcrumb = { timestamp, ...breadcrumb }; + const finalBreadcrumb = beforeBreadcrumb + ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) + : mergedBreadcrumb; - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; + if (finalBreadcrumb === null) return; - return instance; -} + scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); + } -// Create the default instance to be exported -var axios = createInstance(defaults); + /** + * @inheritDoc + */ + setUser(user) { + const scope = this.getScope(); + if (scope) scope.setUser(user); + } -// Expose Axios class to allow class inheritance -axios.Axios = Axios; + /** + * @inheritDoc + */ + setTags(tags) { + const scope = this.getScope(); + if (scope) scope.setTags(tags); + } -// Expose Cancel & CancelToken -axios.CanceledError = __webpack_require__(1624); -axios.CancelToken = __webpack_require__(1636); -axios.isCancel = __webpack_require__(1633); -axios.VERSION = (__webpack_require__(1629).version); -axios.toFormData = __webpack_require__(1615); + /** + * @inheritDoc + */ + setExtras(extras) { + const scope = this.getScope(); + if (scope) scope.setExtras(extras); + } -// Expose AxiosError class -axios.AxiosError = __webpack_require__(1613); + /** + * @inheritDoc + */ + setTag(key, value) { + const scope = this.getScope(); + if (scope) scope.setTag(key, value); + } -// alias for CanceledError for backward compatibility -axios.Cancel = axios.CanceledError; + /** + * @inheritDoc + */ + setExtra(key, extra) { + const scope = this.getScope(); + if (scope) scope.setExtra(key, extra); + } -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = __webpack_require__(1637); + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setContext(name, context) { + const scope = this.getScope(); + if (scope) scope.setContext(name, context); + } -// Expose isAxiosError -axios.isAxiosError = __webpack_require__(1638); + /** + * @inheritDoc + */ + configureScope(callback) { + const { scope, client } = this.getStackTop(); + if (scope && client) { + callback(scope); + } + } -module.exports = axios; + /** + * @inheritDoc + */ + run(callback) { + const oldHub = makeMain(this); + try { + callback(this); + } finally { + makeMain(oldHub); + } + } -// Allow use of default import syntax in TypeScript -module.exports["default"] = axios; + /** + * @inheritDoc + */ + getIntegration(integration) { + const client = this.getClient(); + if (!client) return null; + try { + return client.getIntegration(integration); + } catch (_oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); + return null; + } + } + /** + * @inheritDoc + */ + startTransaction(context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); + } -/***/ }), -/* 1604 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + traceHeaders() { + return this._callExtensionMethod('traceHeaders'); + } -"use strict"; + /** + * @inheritDoc + */ + captureSession(endSession = false) { + // both send the update and pull the session from the scope + if (endSession) { + return this.endSession(); + } + // only send the update + this._sendSessionUpdate(); + } -var bind = __webpack_require__(1605); + /** + * @inheritDoc + */ + endSession() { + const layer = this.getStackTop(); + const scope = layer && layer.scope; + const session = scope && scope.getSession(); + if (session) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); + } + this._sendSessionUpdate(); -// utils is a library of generic helper functions non-specific to axios + // the session is over; take it off of the scope + if (scope) { + scope.setSession(); + } + } -var toString = Object.prototype.toString; + /** + * @inheritDoc + */ + startSession(context) { + const { scope, client } = this.getStackTop(); + const { release, environment } = (client && client.getOptions()) || {}; -// eslint-disable-next-line func-names -var kindOf = (function(cache) { - // eslint-disable-next-line func-names - return function(thing) { - var str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - }; -})(Object.create(null)); + // Will fetch userAgent if called from browser sdk + const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; -function kindOfTest(type) { - type = type.toLowerCase(); - return function isKindOf(thing) { - return kindOf(thing) === type; - }; -} + const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ + release, + environment, + ...(scope && { user: scope.getUser() }), + ...(userAgent && { userAgent }), + ...context, + }); -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return Array.isArray(val); + if (scope) { + // End existing session if there's one + const currentSession = scope.getSession && scope.getSession(); + if (currentSession && currentSession.status === 'ok') { + (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); + } + this.endSession(); + + // Afterwards we set the new session on the scope + scope.setSession(session); + } + + return session; + } + + /** + * Returns if default PII should be sent to Sentry and propagated in ourgoing requests + * when Tracing is used. + */ + shouldSendDefaultPii() { + const client = this.getClient(); + const options = client && client.getOptions(); + return Boolean(options && options.sendDefaultPii); + } + + /** + * Sends the current Session on the scope + */ + _sendSessionUpdate() { + const { scope, client } = this.getStackTop(); + if (!scope) return; + + const session = scope.getSession(); + if (session) { + if (client && client.captureSession) { + client.captureSession(session); + } + } + } + + /** + * Internal helper function to call a method on the top client if it exists. + * + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. + */ + _withClient(callback) { + const { scope, client } = this.getStackTop(); + return client && callback(client, scope); + } + + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _callExtensionMethod(method, ...args) { + const carrier = getMainCarrier(); + const sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); + } + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); + } } /** - * Determine if a value is undefined + * Returns the global shim registry. * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; + * FIXME: This function is problematic, because despite always returning a valid Carrier, + * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check + * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. + **/ +function getMainCarrier() { + _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; } /** - * Determine if a value is a Buffer + * Replaces the current main hub with the passed one on the global object * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false + * @returns The old replaced hub */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +function makeMain(hub) { + const registry = getMainCarrier(); + const oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; } /** - * Determine if a value is an ArrayBuffer + * Returns the default hub instance. * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. */ -var isArrayBuffer = kindOfTest('ArrayBuffer'); +function getCurrentHub() { + // Get main carrier (global for every environment) + const registry = getMainCarrier(); + // If there's no hub, or its an old API, assign a new one + if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { + setHubOnCarrier(registry, new Hub()); + } -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + // Prefer domains over global if they are there (applicable only to Node environment) + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { + return getHubFromActiveDomain(registry); } - return result; + // Return hub that lives on a global object + return getHubFromCarrier(registry); } /** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false + * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist + * @returns discovered hub */ -function isString(val) { - return typeof val === 'string'; -} +function getHubFromActiveDomain(registry) { + try { + const sentry = getMainCarrier().__SENTRY__; + const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; -} + // If there's no active domain, just return global hub + if (!activeDomain) { + return getHubFromCarrier(registry); + } -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} + // If there's no hub on current domain, or it's an old API, assign a new one + if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { + const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); + setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(registryHubTopStack.scope))); + } -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (kindOf(val) !== 'object') { - return false; + // Return hub that lives on a domain + return getHubFromCarrier(activeDomain); + } catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; } /** - * Determine if a value is a Date - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -var isDate = kindOfTest('Date'); - -/** - * Determine if a value is a File - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -var isFile = kindOfTest('File'); - -/** - * Determine if a value is a Blob - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -var isBlob = kindOfTest('Blob'); - -/** - * Determine if a value is a FileList - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -var isFileList = kindOfTest('FileList'); - -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false + * This will tell whether a carrier has a hub on it or not + * @param carrier object */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; +function hasHubOnCarrier(carrier) { + return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); } /** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); +function getHubFromCarrier(carrier) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); } /** - * Determine if a value is a FormData - * - * @param {Object} thing The value to test - * @returns {boolean} True if value is an FormData, otherwise false + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + * @returns A boolean indicating success or failure */ -function isFormData(thing) { - var pattern = '[object FormData]'; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || - toString.call(thing) === pattern || - (isFunction(thing.toString) && thing.toString() === pattern) - ); +function setHubOnCarrier(carrier, hub) { + if (!carrier) return false; + const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); + __SENTRY__.hub = hub; + return true; } -/** - * Determine if a value is a URLSearchParams object - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -var isURLSearchParams = kindOfTest('URLSearchParams'); - -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); -} -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} +//# sourceMappingURL=hub.js.map -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } +/***/ }), +/* 1602 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Scope": () => (/* binding */ Scope), +/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1605); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1603); -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} /** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a + * Default value for maximum number of breadcrumbs added to an event. */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; -} +const DEFAULT_MAX_BREADCRUMBS = 100; /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} +class Scope { + /** Flag if notifying is happening. */ -/** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - */ + /** Callback for client to receive scope changes. */ -function inherits(constructor, superConstructor, props, descriptors) { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - props && Object.assign(constructor.prototype, props); -} + /** Callback list that will be called after {@link applyToEvent}. */ -/** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function} [filter] - * @returns {Object} - */ + /** Array of breadcrumbs. */ -function toFlatObject(sourceObj, destObj, filter) { - var props; - var i; - var prop; - var merged = {}; + /** User */ - destObj = destObj || {}; + /** Tags */ - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if (!merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = Object.getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + /** Extra */ - return destObj; -} + /** Contexts */ -/* - * determines whether a string ends with the characters of a specified string - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * @returns {boolean} - */ -function endsWith(str, searchString, position) { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - var lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -} + /** Attachments */ + /** + * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get + * sent to Sentry + */ -/** - * Returns new array from array like object - * @param {*} [thing] - * @returns {Array} - */ -function toArray(thing) { - if (!thing) return null; - var i = thing.length; - if (isUndefined(i)) return null; - var arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; -} + /** Fingerprint */ -// eslint-disable-next-line func-names -var isTypedArray = (function(TypedArray) { - // eslint-disable-next-line func-names - return function(thing) { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); + /** Severity */ + // eslint-disable-next-line deprecation/deprecation -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM, - inherits: inherits, - toFlatObject: toFlatObject, - kindOf: kindOf, - kindOfTest: kindOfTest, - endsWith: endsWith, - toArray: toArray, - isTypedArray: isTypedArray, - isFileList: isFileList -}; + /** Transaction Name */ + /** Span */ -/***/ }), -/* 1605 */ -/***/ ((module) => { + /** Session */ -"use strict"; + /** Request Mode Session Status */ + // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + constructor() { + this._notifyingListeners = false; + this._scopeListeners = []; + this._eventProcessors = []; + this._breadcrumbs = []; + this._attachments = []; + this._user = {}; + this._tags = {}; + this._extra = {}; + this._contexts = {}; + this._sdkProcessingMetadata = {}; + } + + /** + * Inherit values from the parent scope. + * @param scope to clone. + */ + static clone(scope) { + const newScope = new Scope(); + if (scope) { + newScope._breadcrumbs = [...scope._breadcrumbs]; + newScope._tags = { ...scope._tags }; + newScope._extra = { ...scope._extra }; + newScope._contexts = { ...scope._contexts }; + newScope._user = scope._user; + newScope._level = scope._level; + newScope._span = scope._span; + newScope._session = scope._session; + newScope._transactionName = scope._transactionName; + newScope._fingerprint = scope._fingerprint; + newScope._eventProcessors = [...scope._eventProcessors]; + newScope._requestSession = scope._requestSession; + newScope._attachments = [...scope._attachments]; + newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; } - return fn.apply(thisArg, args); - }; -}; + return newScope; + } + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + addScopeListener(callback) { + this._scopeListeners.push(callback); + } -/***/ }), -/* 1606 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + addEventProcessor(callback) { + this._eventProcessors.push(callback); + return this; + } -"use strict"; + /** + * @inheritDoc + */ + setUser(user) { + this._user = user || {}; + if (this._session) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); + } + this._notifyScopeListeners(); + return this; + } + /** + * @inheritDoc + */ + getUser() { + return this._user; + } -var utils = __webpack_require__(1604); -var buildURL = __webpack_require__(1607); -var InterceptorManager = __webpack_require__(1608); -var dispatchRequest = __webpack_require__(1609); -var mergeConfig = __webpack_require__(1634); -var buildFullPath = __webpack_require__(1619); -var validator = __webpack_require__(1635); + /** + * @inheritDoc + */ + getRequestSession() { + return this._requestSession; + } -var validators = validator.validators; -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; -} + /** + * @inheritDoc + */ + setRequestSession(requestSession) { + this._requestSession = requestSession; + return this; + } -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; + /** + * @inheritDoc + */ + setTags(tags) { + this._tags = { + ...this._tags, + ...tags, + }; + this._notifyScopeListeners(); + return this; } - config = mergeConfig(this.defaults, config); + /** + * @inheritDoc + */ + setTag(key, value) { + this._tags = { ...this._tags, [key]: value }; + this._notifyScopeListeners(); + return this; + } - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; + /** + * @inheritDoc + */ + setExtras(extras) { + this._extra = { + ...this._extra, + ...extras, + }; + this._notifyScopeListeners(); + return this; } - var transitional = config.transitional; + /** + * @inheritDoc + */ + setExtra(key, extra) { + this._extra = { ...this._extra, [key]: extra }; + this._notifyScopeListeners(); + return this; + } - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); + /** + * @inheritDoc + */ + setFingerprint(fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; } - // filter out skipped interceptors - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } + /** + * @inheritDoc + */ + setLevel( + // eslint-disable-next-line deprecation/deprecation + level, + ) { + this._level = level; + this._notifyScopeListeners(); + return this; + } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + /** + * @inheritDoc + */ + setTransactionName(name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + } - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); + /** + * @inheritDoc + */ + setContext(key, context) { + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; + } else { + this._contexts[key] = context; + } - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); + this._notifyScopeListeners(); + return this; + } - var promise; + /** + * @inheritDoc + */ + setSpan(span) { + this._span = span; + this._notifyScopeListeners(); + return this; + } - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest, undefined]; + /** + * @inheritDoc + */ + getSpan() { + return this._span; + } - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); + /** + * @inheritDoc + */ + getTransaction() { + // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will + // have a pointer to the currently-active transaction. + const span = this.getSpan(); + return span && span.transaction; + } - promise = Promise.resolve(config); - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); + /** + * @inheritDoc + */ + setSession(session) { + if (!session) { + delete this._session; + } else { + this._session = session; } + this._notifyScopeListeners(); + return this; + } - return promise; + /** + * @inheritDoc + */ + getSession() { + return this._session; } + /** + * @inheritDoc + */ + update(captureContext) { + if (!captureContext) { + return this; + } - var newConfig = config; - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; + if (typeof captureContext === 'function') { + const updatedScope = (captureContext )(this); + return updatedScope instanceof Scope ? updatedScope : this; } - } - try { - promise = dispatchRequest(newConfig); - } catch (error) { - return Promise.reject(error); - } + if (captureContext instanceof Scope) { + this._tags = { ...this._tags, ...captureContext._tags }; + this._extra = { ...this._extra, ...captureContext._extra }; + this._contexts = { ...this._contexts, ...captureContext._contexts }; + if (captureContext._user && Object.keys(captureContext._user).length) { + this._user = captureContext._user; + } + if (captureContext._level) { + this._level = captureContext._level; + } + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; + } + if (captureContext._requestSession) { + this._requestSession = captureContext._requestSession; + } + } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { + // eslint-disable-next-line no-param-reassign + captureContext = captureContext ; + this._tags = { ...this._tags, ...captureContext.tags }; + this._extra = { ...this._extra, ...captureContext.extra }; + this._contexts = { ...this._contexts, ...captureContext.contexts }; + if (captureContext.user) { + this._user = captureContext.user; + } + if (captureContext.level) { + this._level = captureContext.level; + } + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; + } + if (captureContext.requestSession) { + this._requestSession = captureContext.requestSession; + } + } - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + return this; } - return promise; -}; - -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - var fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); -}; + /** + * @inheritDoc + */ + clear() { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._requestSession = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + this._attachments = []; + return this; + } -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; -}); + /** + * @inheritDoc + */ + addBreadcrumb(breadcrumb, maxBreadcrumbs) { + const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ + // No data has been changed, so don't notify scope listeners + if (maxCrumbs <= 0) { + return this; + } - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url: url, - data: data - })); + const mergedBreadcrumb = { + timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), + ...breadcrumb, }; + this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); + this._notifyScopeListeners(); + + return this; } - Axios.prototype[method] = generateHTTPMethod(); + /** + * @inheritDoc + */ + clearBreadcrumbs() { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + } - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); -}); + /** + * @inheritDoc + */ + addAttachment(attachment) { + this._attachments.push(attachment); + return this; + } -module.exports = Axios; + /** + * @inheritDoc + */ + getAttachments() { + return this._attachments; + } + /** + * @inheritDoc + */ + clearAttachments() { + this._attachments = []; + return this; + } -/***/ }), -/* 1607 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * Applies data from the scope to the event and runs all event processors on it. + * + * @param event Event + * @param hint Object containing additional information about the original exception, for use by the event processors. + * @hidden + */ + applyToEvent(event, hint = {}) { + if (this._extra && Object.keys(this._extra).length) { + event.extra = { ...this._extra, ...event.extra }; + } + if (this._tags && Object.keys(this._tags).length) { + event.tags = { ...this._tags, ...event.tags }; + } + if (this._user && Object.keys(this._user).length) { + event.user = { ...this._user, ...event.user }; + } + if (this._contexts && Object.keys(this._contexts).length) { + event.contexts = { ...this._contexts, ...event.contexts }; + } + if (this._level) { + event.level = this._level; + } + if (this._transactionName) { + event.transaction = this._transactionName; + } -"use strict"; + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relies on that. + if (this._span) { + event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; + const transactionName = this._span.transaction && this._span.transaction.name; + if (transactionName) { + event.tags = { transaction: transactionName, ...event.tags }; + } + } + this._applyFingerprint(event); -var utils = __webpack_require__(1604); + event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; + event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} + event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; + return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); } - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; + /** + * Add data which will be accessible during event processing but won't get sent to Sentry + */ + setSDKProcessingMetadata(newData) { + this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } + return this; + } - if (utils.isArray(val)) { - key = key + '[]'; + /** + * This will be called after {@link applyToEvent} is finished. + */ + _notifyEventProcessors( + processors, + event, + hint, + index = 0, + ) { + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { + const processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); } else { - val = [val]; - } + const result = processor({ ...event }, hint) ; - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + processor.id && + result === null && + _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); + + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { + void result + .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) + .then(null, reject); + } else { + void this._notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); } - parts.push(encode(key) + '=' + encode(v)); - }); + } }); - - serializedParams = parts.join('&'); } - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); + /** + * This will be called on every set call. + */ + _notifyScopeListeners() { + // We need this check for this._notifyingListeners to be able to work on scope during updates + // If this check is not here we'll produce endless recursion when something is done with the scope + // during the callback. + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach(callback => { + callback(this); + }); + this._notifyingListeners = false; } - - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } - return url; -}; + /** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ + _applyFingerprint(event) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(event.fingerprint) : []; + // If we have something on the scope, then merge it with event + if (this._fingerprint) { + event.fingerprint = event.fingerprint.concat(this._fingerprint); + } -/***/ }), -/* 1608 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(1604); - -function InterceptorManager() { - this.handlers = []; + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; + } + } } /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later + * Returns the global event processors. */ -InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; -}; +function getGlobalEventProcessors() { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); +} /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); +} -/** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; -module.exports = InterceptorManager; +//# sourceMappingURL=scope.js.map /***/ }), -/* 1609 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1603 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "closeSession": () => (/* binding */ closeSession), +/* harmony export */ "makeSession": () => (/* binding */ makeSession), +/* harmony export */ "updateSession": () => (/* binding */ updateSession) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); -var utils = __webpack_require__(1604); -var transformData = __webpack_require__(1610); -var isCancel = __webpack_require__(1633); -var defaults = __webpack_require__(1611); -var CanceledError = __webpack_require__(1624); - /** - * Throws a `CanceledError` if cancellation has been requested. + * Creates a new `Session` object by setting certain default parameters. If optional @param context + * is passed, the passed properties are applied to the session object. + * + * @param context (optional) additional properties to be applied to the returned session object + * + * @returns a new `Session` object */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } +function makeSession(context) { + // Both timestamp and started are in seconds since the UNIX epoch. + const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - if (config.signal && config.signal.aborted) { - throw new CanceledError(); + const session = { + sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), + init: true, + timestamp: startingTime, + started: startingTime, + duration: 0, + status: 'ok', + errors: 0, + ignoreDuration: false, + toJSON: () => sessionToJSON(session), + }; + + if (context) { + updateSession(session, context); } + + return session; } /** - * Dispatch a request to the server using the configured adapter. + * Updates a session object with the properties passed in the context. * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled + * Note that this function mutates the passed object and returns void. + * (Had to do this instead of returning a new and updated session because closing and sending a session + * makes an update to the session after it was passed to the sending logic. + * @see BaseClient.captureSession ) + * + * @param session the `Session` to update + * @param context the `SessionContext` holding the properties that should be updated in @param session */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); - - // Ensure headers exist - config.headers = config.headers || {}; - - // Transform request data - config.data = transformData.call( - config, - config.data, - config.headers, - config.transformRequest - ); - - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); - - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; +// eslint-disable-next-line complexity +function updateSession(session, context = {}) { + if (context.user) { + if (!session.ipAddress && context.user.ip_address) { + session.ipAddress = context.user.ip_address; } - ); - - var adapter = config.adapter || defaults.adapter; - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - response.data, - response.headers, - config.transformResponse - ); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } + if (!session.did && !context.did) { + session.did = context.user.id || context.user.email || context.user.username; } + } - return Promise.reject(reason); - }); -}; - - -/***/ }), -/* 1610 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); -"use strict"; + if (context.ignoreDuration) { + session.ignoreDuration = context.ignoreDuration; + } + if (context.sid) { + // Good enough uuid validation. — Kamil + session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); + } + if (context.init !== undefined) { + session.init = context.init; + } + if (!session.did && context.did) { + session.did = `${context.did}`; + } + if (typeof context.started === 'number') { + session.started = context.started; + } + if (session.ignoreDuration) { + session.duration = undefined; + } else if (typeof context.duration === 'number') { + session.duration = context.duration; + } else { + const duration = session.timestamp - session.started; + session.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + session.release = context.release; + } + if (context.environment) { + session.environment = context.environment; + } + if (!session.ipAddress && context.ipAddress) { + session.ipAddress = context.ipAddress; + } + if (!session.userAgent && context.userAgent) { + session.userAgent = context.userAgent; + } + if (typeof context.errors === 'number') { + session.errors = context.errors; + } + if (context.status) { + session.status = context.status; + } +} +/** + * Closes a session by setting its status and updating the session object with it. + * Internally calls `updateSession` to update the passed session object. + * + * Note that this function mutates the passed session (@see updateSession for explanation). + * + * @param session the `Session` object to be closed + * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, + * this function will keep the previously set status, unless it was `'ok'` in which case + * it is changed to `'exited'`. + */ +function closeSession(session, status) { + let context = {}; + if (status) { + context = { status }; + } else if (session.status === 'ok') { + context = { status: 'exited' }; + } -var utils = __webpack_require__(1604); -var defaults = __webpack_require__(1611); + updateSession(session, context); +} /** - * Transform the data for a request or a response + * Serializes a passed session object to a JSON object with a slightly different structure. + * This is necessary because the Sentry backend requires a slightly different schema of a session + * than the one the JS SDKs use internally. * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data + * @param session the session to be converted + * + * @returns a JSON object of the passed session */ -module.exports = function transformData(data, headers, fns) { - var context = this || defaults; - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); +function sessionToJSON(session) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ + sid: `${session.sid}`, + init: session.init, + // Make sure that sec is converted to ms for date constructor + started: new Date(session.started * 1000).toISOString(), + timestamp: new Date(session.timestamp * 1000).toISOString(), + status: session.status, + errors: session.errors, + did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, + duration: session.duration, + attrs: { + release: session.release, + environment: session.environment, + ip_address: session.ipAddress, + user_agent: session.userAgent, + }, }); +} - return data; -}; + +//# sourceMappingURL=session.js.map /***/ }), -/* 1611 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1604 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), +/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), +/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), +/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), +/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), +/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) +/* harmony export */ }); +/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1606); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); +/* module decorator */ module = __webpack_require__.hmd(module); -var utils = __webpack_require__(1604); -var normalizeHeaderName = __webpack_require__(1612); -var AxiosError = __webpack_require__(1613); -var transitionalDefaults = __webpack_require__(1614); -var toFormData = __webpack_require__(1615); -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' +// eslint-disable-next-line deprecation/deprecation +const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); + +/** + * An object that can return the current timestamp in seconds since the UNIX epoch. + */ + +/** + * A TimestampSource implementation for environments that do not support the Performance Web API natively. + * + * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier + * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It + * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + */ +const dateTimestampSource = { + nowSeconds: () => Date.now() / 1000, }; -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} +/** + * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} + * for accessing a high-resolution monotonic clock. + */ -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __webpack_require__(1616); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __webpack_require__(1626); +/** + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. + * + * Wrapping the native API works around differences in behavior from different browsers. + */ +function getBrowserPerformance() { + const { performance } = WINDOW; + if (!performance || !performance.now) { + return undefined; } - return adapter; -} -function stringifySafely(rawValue, parser, encoder) { - if (utils.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } + // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). + // + // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + + // performance.now() gives a date arbitrarily in the past. + // + // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is + // undefined. + // + // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to + // interact with data coming out of performance entries. + // + // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that + // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes + // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have + // observed skews that can be as long as days, weeks or months. + // + // See https://github.com/getsentry/sentry-javascript/issues/2590. + // + // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload + // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation + // transactions of long-lived web pages. + const timeOrigin = Date.now() - performance.now(); - return (encoder || JSON.stringify)(rawValue); + return { + now: () => performance.now(), + timeOrigin, + }; } -var defaults = { - - transitional: transitionalDefaults, - - adapter: getDefaultAdapter(), - - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } +/** + * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't + * implement the API. + */ +function getNodePerformance() { + try { + const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; + return perfHooks.performance; + } catch (_) { + return undefined; + } +} - var isObjectPayload = utils.isObject(data); - var contentType = headers && headers['Content-Type']; +/** + * The Performance API implementation for the current platform, if available. + */ +const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); - var isFileList; +const timestampSource = + platformPerformance === undefined + ? dateTimestampSource + : { + nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, + }; - if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { - var _FormData = this.env && this.env.FormData; - return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); - } else if (isObjectPayload || contentType === 'application/json') { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } +/** + * Returns a timestamp in seconds since the UNIX epoch using the Date API. + */ +const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); - return data; - }], +/** + * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the + * availability of the Performance API. + * + * See `usingPerformanceAPI` to test whether the Performance API is used. + * + * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is + * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The + * skew can grow to arbitrary amounts like days, weeks or months. + * See https://github.com/getsentry/sentry-javascript/issues/2590. + */ +const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; +// Re-exported with an old name for backwards-compatibility. +const timestampWithMs = timestampInSeconds; - if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } - } +/** + * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. + */ +const usingPerformanceAPI = platformPerformance !== undefined; - return data; - }], +/** + * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. + */ +let _browserPerformanceTimeOriginMode; - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, +/** + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. + */ +const browserPerformanceTimeOrigin = (() => { + // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or + // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin + // data as reliable if they are within a reasonable threshold of the current time. - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', + const { performance } = WINDOW; + if (!performance || !performance.now) { + _browserPerformanceTimeOriginMode = 'none'; + return undefined; + } - maxContentLength: -1, - maxBodyLength: -1, + const threshold = 3600 * 1000; + const performanceNow = performance.now(); + const dateNow = Date.now(); - env: { - FormData: __webpack_require__(1630) - }, + // if timeOrigin isn't available set delta to threshold so it isn't used + const timeOriginDelta = performance.timeOrigin + ? Math.abs(performance.timeOrigin + performanceNow - dateNow) + : threshold; + const timeOriginIsReliable = timeOriginDelta < threshold; - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, + // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin + // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. + // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always + // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the + // Date API. + // eslint-disable-next-line deprecation/deprecation + const navigationStart = performance.timing && performance.timing.navigationStart; + const hasNavigationStart = typeof navigationStart === 'number'; + // if navigationStart isn't available set delta to threshold so it isn't used + const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + const navigationStartIsReliable = navigationStartDelta < threshold; - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' + if (timeOriginIsReliable || navigationStartIsReliable) { + // Use the more reliable time origin + if (timeOriginDelta <= navigationStartDelta) { + _browserPerformanceTimeOriginMode = 'timeOrigin'; + return performance.timeOrigin; + } else { + _browserPerformanceTimeOriginMode = 'navigationStart'; + return navigationStart; } } -}; -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); + // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. + _browserPerformanceTimeOriginMode = 'dateNow'; + return dateNow; +})(); -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); -module.exports = defaults; +//# sourceMappingURL=time.js.map /***/ }), -/* 1612 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1605 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), +/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), +/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) +/* harmony export */ }); +/** Internal global with common properties and Sentry extensions */ +// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification +// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js +// core-js has the following licence: +// +// Copyright (c) 2014-2022 Denis Pushkarev +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. -var utils = __webpack_require__(1604); +/** Returns 'obj' if it's the global object, otherwise returns undefined */ +function isGlobalObj(obj) { + return obj && obj.Math == Math ? obj : undefined; +} -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; +/** Get's the global object for the current JavaScript runtime */ +const GLOBAL_OBJ = + (typeof globalThis == 'object' && isGlobalObj(globalThis)) || + // eslint-disable-next-line no-restricted-globals + (typeof window == 'object' && isGlobalObj(window)) || + (typeof self == 'object' && isGlobalObj(self)) || + (typeof global == 'object' && isGlobalObj(global)) || + (function () { + return this; + })() || + {}; + +/** + * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 + */ +function getGlobalObject() { + return GLOBAL_OBJ ; +} + +/** + * Returns a global singleton contained in the global `__SENTRY__` object. + * + * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory + * function and added to the `__SENTRY__` object. + * + * @param name name of the global singleton on __SENTRY__ + * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` + * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value + * @returns the singleton + */ +function getGlobalSingleton(name, creator, obj) { + const gbl = (obj || GLOBAL_OBJ) ; + const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); + const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); + return singleton; +} + + +//# sourceMappingURL=worldwide.js.map /***/ }), -/* 1613 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1606 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), +/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), +/* harmony export */ "loadModule": () => (/* binding */ loadModule) +/* harmony export */ }); +/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); +/* module decorator */ module = __webpack_require__.hmd(module); -var utils = __webpack_require__(1604); +/** + * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, + * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + */ /** - * Create an Error with the specified message, config, error code, request and response. + * Checks whether we're in the Node.js or Browser environment * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. + * @returns Answer to given question */ -function AxiosError(message, code, config, request, response) { - Error.call(this); - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); +function isNodeEnv() { + // explicitly check for browser bundles as those can be optimized statically + // by terser/rollup. + return ( + !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && + Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' + ); } -utils.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - } -}); - -var prototype = AxiosError.prototype; -var descriptors = {}; - -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED' -// eslint-disable-next-line func-names -].forEach(function(code) { - descriptors[code] = {value: code}; -}); - -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype, 'isAxiosError', {value: true}); - -// eslint-disable-next-line func-names -AxiosError.from = function(error, code, config, request, response, customProps) { - var axiosError = Object.create(prototype); +/** + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} - utils.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }); +/** + * Helper for dynamically loading module that should work with linked dependencies. + * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` + * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during + * build time. `require.resolve` is also not available in any other way, so we cannot create, + * a fake helper like we do with `dynamicRequire`. + * + * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. + * That is to mimic the behavior of `require.resolve` exactly. + * + * @param moduleName module name to require + * @returns possibly required module + */ +function loadModule(moduleName) { + let mod; - AxiosError.call(axiosError, error.message, code, config, request, response); + try { + mod = dynamicRequire(module, moduleName); + } catch (e) { + // no-empty + } - axiosError.name = error.name; + try { + const { cwd } = dynamicRequire(module, 'process'); + mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; + } catch (e) { + // no-empty + } - customProps && Object.assign(axiosError, customProps); + return mod; +} - return axiosError; -}; -module.exports = AxiosError; +//# sourceMappingURL=node.js.map /***/ }), -/* 1614 */ -/***/ ((module) => { +/* 1607 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) +/* harmony export */ }); +/* + * This module exists for optimizations in the build process through rollup and terser. We define some global + * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these + * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will + * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to + * `logger` and preventing node-related code from appearing in browser bundles. + * + * Attention: + * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by + * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) + * having issues tree-shaking these constants across package boundaries. + * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want + * users to be able to shake away expressions that it guards. + */ +/** + * Figures out if we're building a browser bundle. + * + * @returns true if this is a browser bundle build. + */ +function isBrowserBundle() { + return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; +} -module.exports = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}; + +//# sourceMappingURL=env.js.map /***/ }), -/* 1615 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1608 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), +/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), +/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), +/* harmony export */ "arrayify": () => (/* binding */ arrayify), +/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), +/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), +/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), +/* harmony export */ "uuid4": () => (/* binding */ uuid4) +/* harmony export */ }); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); +/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -var utils = __webpack_require__(1604); -/** - * Convert a data object to FormData - * @param {Object} obj - * @param {?Object} [formData] - * @returns {Object} - **/ -function toFormData(obj, formData) { - // eslint-disable-next-line no-param-reassign - formData = formData || new FormData(); +/** + * UUID4 generator + * + * @returns string Generated UUID4. + */ +function uuid4() { + const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; + const crypto = gbl.crypto || gbl.msCrypto; - var stack = []; + if (crypto && crypto.randomUUID) { + return crypto.randomUUID().replace(/-/g, ''); + } - function convertValue(value) { - if (value === null) return ''; + const getRandomByte = + crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; - if (utils.isDate(value)) { - return value.toISOString(); - } + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 + // Concatenating the following numbers as strings results in '10000000100040008000100000000000' + return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => + // eslint-disable-next-line no-bitwise + ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), + ); +} - if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { - return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); - } +function getFirstException(event) { + return event.exception && event.exception.values ? event.exception.values[0] : undefined; +} - return value; +/** + * Extracts either message or type+value from an event that can be used for user-facing logs + * @returns event's description + */ +function getEventDescription(event) { + const { message, event_id: eventId } = event; + if (message) { + return message; } - function build(data, parentKey) { - if (utils.isPlainObject(data) || utils.isArray(data)) { - if (stack.indexOf(data) !== -1) { - throw Error('Circular reference detected in ' + parentKey); - } - - stack.push(data); - - utils.forEach(data, function each(value, key) { - if (utils.isUndefined(value)) return; - var fullKey = parentKey ? parentKey + '.' + key : key; - var arr; - - if (value && !parentKey && typeof value === 'object') { - if (utils.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { - // eslint-disable-next-line func-names - arr.forEach(function(el) { - !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); - }); - return; - } - } + const firstException = getFirstException(event); + if (firstException) { + if (firstException.type && firstException.value) { + return `${firstException.type}: ${firstException.value}`; + } + return firstException.type || firstException.value || eventId || '<unknown>'; + } + return eventId || '<unknown>'; +} - build(value, fullKey); - }); +/** + * Adds exception values, type and value to an synthetic Exception. + * @param event The event to modify. + * @param value Value of the exception. + * @param type Type of the exception. + * @hidden + */ +function addExceptionTypeValue(event, value, type) { + const exception = (event.exception = event.exception || {}); + const values = (exception.values = exception.values || []); + const firstException = (values[0] = values[0] || {}); + if (!firstException.value) { + firstException.value = value || ''; + } + if (!firstException.type) { + firstException.type = type || 'Error'; + } +} - stack.pop(); - } else { - formData.append(parentKey, convertValue(data)); - } +/** + * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. + * + * @param event The event to modify. + * @param newMechanism Mechanism data to add to the event. + * @hidden + */ +function addExceptionMechanism(event, newMechanism) { + const firstException = getFirstException(event); + if (!firstException) { + return; } - build(obj); + const defaultMechanism = { type: 'generic', handled: true }; + const currentMechanism = firstException.mechanism; + firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; - return formData; + if (newMechanism && 'data' in newMechanism) { + const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; + firstException.mechanism.data = mergedData; + } } -module.exports = toFormData; +// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +const SEMVER_REGEXP = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +/** + * Represents Semantic Versioning object + */ -/***/ }), -/* 1616 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Parses input into a SemVer interface + * @param input string representation of a semver version + */ +function parseSemver(input) { + const match = input.match(SEMVER_REGEXP) || []; + const major = parseInt(match[1], 10); + const minor = parseInt(match[2], 10); + const patch = parseInt(match[3], 10); + return { + buildmetadata: match[5], + major: isNaN(major) ? undefined : major, + minor: isNaN(minor) ? undefined : minor, + patch: isNaN(patch) ? undefined : patch, + prerelease: match[4], + }; +} -"use strict"; +/** + * This function adds context (pre/post/line) lines to the provided frame + * + * @param lines string[] containing all lines + * @param frame StackFrame that will be mutated + * @param linesOfContext number of context lines we want to add pre/post + */ +function addContextToFrame(lines, frame, linesOfContext = 5) { + const lineno = frame.lineno || 0; + const maxLines = lines.length; + const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); + frame.pre_context = lines + .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) + .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); -var utils = __webpack_require__(1604); -var settle = __webpack_require__(1617); -var cookies = __webpack_require__(1618); -var buildURL = __webpack_require__(1607); -var buildFullPath = __webpack_require__(1619); -var parseHeaders = __webpack_require__(1622); -var isURLSameOrigin = __webpack_require__(1623); -var transitionalDefaults = __webpack_require__(1614); -var AxiosError = __webpack_require__(1613); -var CanceledError = __webpack_require__(1624); -var parseProtocol = __webpack_require__(1625); + frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } + frame.post_context = lines + .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) + .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); +} - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - - if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - - var request = new XMLHttpRequest(); - - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - - var fullPath = buildFullPath(config.baseURL, config.url); - - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; +/** + * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object + * in question), and marks it captured if not. + * + * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and + * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so + * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because + * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not + * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This + * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we + * see it. + * + * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on + * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent + * object wrapper forms so that this check will always work. However, because we need to flag the exact object which + * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification + * must be done before the exception captured. + * + * @param A thrown exception to check or flag as having been seen + * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) + */ +function checkOrSetAlreadyCaught(exception) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (exception && (exception ).__sentry_captured__) { + return true; + } - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); + try { + // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the + // `ExtraErrorData` integration + (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); + } catch (err) { + // `exception` is a primitive, so we can't mark it seen + } - // Clean up request - request = null; - } + return false; +} - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } +/** + * Checks whether the given input is already an array, and if it isn't, wraps it in one. + * + * @param maybeArray Input to turn into an array, if necessary + * @returns The input, if already an array, or an array with the input as the only element, if not + */ +function arrayify(maybeArray) { + return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; +} - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } +//# sourceMappingURL=misc.js.map - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); - // Clean up request - request = null; - }; +/***/ }), +/* 1609 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), +/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), +/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), +/* harmony export */ "snipLine": () => (/* binding */ snipLine), +/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), +/* harmony export */ "truncate": () => (/* binding */ truncate) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); - // Clean up request - request = null; - }; - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request)); +/** + * Truncates given string to the maximum characters count + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string (0 = unlimited) + * @returns string Encoded + */ +function truncate(str, max = 0) { + if (typeof str !== 'string' || max === 0) { + return str; + } + return str.length <= max ? str : `${str.substr(0, max)}...`; +} - // Clean up request - request = null; - }; +/** + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded + */ +function snipLine(line, colno) { + let newLine = line; + const lineLength = newLine.length; + if (lineLength <= 150) { + return newLine; + } + if (colno > lineLength) { + // eslint-disable-next-line no-param-reassign + colno = lineLength; + } - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + let start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } + let end = Math.min(start + 140, lineLength); + if (end > lineLength - 5) { + end = lineLength; + } + if (end === lineLength) { + start = Math.max(end - 140, 0); + } - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = `'{snip} ${newLine}`; + } + if (end < lineLength) { + newLine += ' {snip}'; + } - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } + return newLine; +} - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } +/** + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; + } - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); + const output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < input.length; i++) { + const value = input[i]; + try { + output.push(String(value)); + } catch (e) { + output.push('[value cannot be serialized]'); } + } - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } + return output.join(delimiter); +} - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (!request) { - return; - } - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); - request.abort(); - request = null; - }; +/** + * Checks if the given value matches a regex or string + * + * @param value The string to test + * @param pattern Either a regex or a string against which `value` will be matched + * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match + * `pattern` if it contains `pattern`. Only applies to string-type patterns. + */ +function isMatchingPattern( + value, + pattern, + requireExactStringMatch = false, +) { + if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { + return false; + } - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { + return pattern.test(value); + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { + return requireExactStringMatch ? value === pattern : value.includes(pattern); + } - if (!requestData) { - requestData = null; - } + return false; +} - var protocol = parseProtocol(fullPath); +/** + * Test the given string against an array of strings and regexes. By default, string matching is done on a + * substring-inclusion basis rather than a strict equality basis + * + * @param testString The string to test + * @param patterns The patterns against which to test the string + * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to + * count. If false, `testString` will match a string pattern if it contains that pattern. + * @returns + */ +function stringMatchesSomePattern( + testString, + patterns = [], + requireExactStringMatch = false, +) { + return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); +} - if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; - } +/** + * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to + * `new RegExp()`. + * + * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime + * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node + * 12+). + * + * @param regexString The string to escape + * @returns An version of the string with all special regex characters escaped + */ +function escapeStringForRegex(regexString) { + // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems + // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. + return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +} - // Send the request - request.send(requestData); - }); -}; +//# sourceMappingURL=string.js.map /***/ }), -/* 1617 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1610 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - - -var AxiosError = __webpack_require__(1613); +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), +/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), +/* harmony export */ "isElement": () => (/* binding */ isElement), +/* harmony export */ "isError": () => (/* binding */ isError), +/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), +/* harmony export */ "isEvent": () => (/* binding */ isEvent), +/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), +/* harmony export */ "isNaN": () => (/* binding */ isNaN), +/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), +/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), +/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), +/* harmony export */ "isString": () => (/* binding */ isString), +/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), +/* harmony export */ "isThenable": () => (/* binding */ isThenable) +/* harmony export */ }); +// eslint-disable-next-line @typescript-eslint/unbound-method +const objectToString = Object.prototype.toString; /** - * Resolve or reject a Promise based on response status. + * Checks whether given value's type is one of a few Error or Error-like + * {@link isError}. * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. + * @param wat A value to be checked. + * @returns A boolean representing the result. */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); +function isError(wat) { + switch (objectToString.call(wat)) { + case '[object Error]': + case '[object Exception]': + case '[object DOMException]': + return true; + default: + return isInstanceOf(wat, Error); } -}; +} +/** + * Checks whether given value is an instance of the given built-in class. + * + * @param wat The value to be checked + * @param className + * @returns A boolean representing the result. + */ +function isBuiltin(wat, className) { + return objectToString.call(wat) === `[object ${className}]`; +} +/** + * Checks whether given value's type is ErrorEvent + * {@link isErrorEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isErrorEvent(wat) { + return isBuiltin(wat, 'ErrorEvent'); +} -/***/ }), -/* 1618 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Checks whether given value's type is DOMError + * {@link isDOMError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMError(wat) { + return isBuiltin(wat, 'DOMError'); +} -"use strict"; +/** + * Checks whether given value's type is DOMException + * {@link isDOMException}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMException(wat) { + return isBuiltin(wat, 'DOMException'); +} +/** + * Checks whether given value's type is a string + * {@link isString}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isString(wat) { + return isBuiltin(wat, 'String'); +} -var utils = __webpack_require__(1604); +/** + * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) + * {@link isPrimitive}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isPrimitive(wat) { + return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +} -module.exports = ( - utils.isStandardBrowserEnv() ? +/** + * Checks whether given value's type is an object literal + * {@link isPlainObject}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isPlainObject(wat) { + return isBuiltin(wat, 'Object'); +} - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); +/** + * Checks whether given value's type is an Event instance + * {@link isEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isEvent(wat) { + return typeof Event !== 'undefined' && isInstanceOf(wat, Event); +} - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } +/** + * Checks whether given value's type is an Element instance + * {@link isElement}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isElement(wat) { + return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +} - if (utils.isString(path)) { - cookie.push('path=' + path); - } +/** + * Checks whether given value's type is an regexp + * {@link isRegExp}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isRegExp(wat) { + return isBuiltin(wat, 'RegExp'); +} - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } +/** + * Checks whether given value has a then function. + * @param wat A value to be checked. + */ +function isThenable(wat) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return Boolean(wat && wat.then && typeof wat.then === 'function'); +} - if (secure === true) { - cookie.push('secure'); - } +/** + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +} - document.cookie = cookie.join('; '); - }, +/** + * Checks whether given value is NaN + * {@link isNaN}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isNaN(wat) { + return typeof wat === 'number' && wat !== wat; +} - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, +/** + * Checks whether given value's type is an instance of provided constructor. + * {@link isInstanceOf}. + * + * @param wat A value to be checked. + * @param base A constructor to be used in a check. + * @returns A boolean representing the result. + */ +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } catch (_e) { + return false; + } +} - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); +//# sourceMappingURL=is.js.map /***/ }), -/* 1619 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1611 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), +/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), +/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), +/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), +/* harmony export */ "fill": () => (/* binding */ fill), +/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), +/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), +/* harmony export */ "objectify": () => (/* binding */ objectify), +/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) +/* harmony export */ }); +/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1609); + -var isAbsoluteURL = __webpack_require__(1620); -var combineURLs = __webpack_require__(1621); /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. + * Replace a method in an object with a wrapped version of itself. * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path + * @param source An object that contains a method to be wrapped. + * @param name The name of the method to be wrapped. + * @param replacementFactory A higher-order function that takes the original version of the given method and returns a + * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to + * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other + * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. + * @returns void */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); +function fill(source, name, replacementFactory) { + if (!(name in source)) { + return; } - return requestedURL; -}; + const original = source[name] ; + const wrapped = replacementFactory(original) ; -/***/ }), -/* 1620 */ -/***/ ((module) => { - -"use strict"; + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + try { + markFunctionWrapped(wrapped, original); + } catch (_Oo) { + // This can throw if multiple fill happens on a global object like XMLHttpRequest + // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 + } + } + source[name] = wrapped; +} /** - * Determines whether the specified URL is absolute + * Defines a non-enumerable property on the given object. * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false + * @param obj The object on which to set the property + * @param name The name of the property to be set + * @param value The value to which to set the property */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -}; - - -/***/ }), -/* 1621 */ -/***/ ((module) => { - -"use strict"; - +function addNonEnumerableProperty(obj, name, value) { + Object.defineProperty(obj, name, { + // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it + value: value, + writable: true, + configurable: true, + }); +} /** - * Creates a new URL by combining the specified URLs + * Remembers the original function on the wrapped function and + * patches up the prototype. * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL + * @param wrapped the wrapper function + * @param original the original function that gets wrapped */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; - - -/***/ }), -/* 1622 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(1604); +function markFunctionWrapped(wrapped, original) { + const proto = original.prototype || {}; + wrapped.prototype = original.prototype = proto; + addNonEnumerableProperty(wrapped, '__sentry_original__', original); +} -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; +/** + * This extracts the original function if available. See + * `markFunctionWrapped` for more information. + * + * @param func the function to unwrap + * @returns the unwrapped version of the function if available. + */ +function getOriginalFunction(func) { + return func.__sentry_original__; +} /** - * Parse headers into an object + * Encodes given object into url-friendly format * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` + * @param object An object that contains serializable values + * @returns string Encoded + */ +function urlEncode(object) { + return Object.keys(object) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) + .join('&'); +} + +/** + * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their + * non-enumerable properties attached. * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object + * @param value Initial source that we have to transform in order for it to be usable by the serializer + * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor + * an Error. */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; +function convertToPlainObject( + value, +) - if (!headers) { return parsed; } + { + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { + return { + message: value.message, + name: value.name, + stack: value.stack, + ...getOwnProperties(value), + }; + } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { + const newObj - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); + = { + type: value.type, + target: serializeEventTarget(value.target), + currentTarget: serializeEventTarget(value.currentTarget), + ...getOwnProperties(value), + }; - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } + if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { + newObj.detail = value.detail; } - }); - - return parsed; -}; + return newObj; + } else { + return value; + } +} -/***/ }), -/* 1623 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** Creates a string representation of the target of an `Event` object */ +function serializeEventTarget(target) { + try { + return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); + } catch (_oO) { + return '<unknown>'; + } +} -"use strict"; +/** Filters out all but an object's own properties */ +function getOwnProperties(obj) { + if (typeof obj === 'object' && obj !== null) { + const extractedProps = {}; + for (const property in obj) { + if (Object.prototype.hasOwnProperty.call(obj, property)) { + extractedProps[property] = (obj )[property]; + } + } + return extractedProps; + } else { + return {}; + } +} +/** + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` + */ +function extractExceptionKeysForMessage(exception, maxLength = 40) { + const keys = Object.keys(convertToPlainObject(exception)); + keys.sort(); -var utils = __webpack_require__(1604); + if (!keys.length) { + return '[object has no keys]'; + } -module.exports = ( - utils.isStandardBrowserEnv() ? + if (keys[0].length >= maxLength) { + return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); + } - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; + for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { + const serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; + } + if (includedKeys === keys.length) { + return serialized; + } + return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); + } - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; + return ''; +} - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } +/** + * Given any object, return a new object having removed all fields whose value was `undefined`. + * Works recursively on objects and arrays. + * + * Attention: This function keeps circular references in the returned object. + */ +function dropUndefinedKeys(inputValue) { + // This map keeps track of what already visited nodes map to. + // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular + // references as the input object. + const memoizationMap = new Map(); - urlParsingNode.setAttribute('href', href); + // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API + return _dropUndefinedKeys(inputValue, memoizationMap); +} - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } +function _dropUndefinedKeys(inputValue, memoizationMap) { + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { + // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; + } - originURL = resolveURL(window.location.href); + const returnValue = {}; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : + for (const key of Object.keys(inputValue)) { + if (typeof inputValue[key] !== 'undefined') { + returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); + } + } - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); + return returnValue ; + } + if (Array.isArray(inputValue)) { + // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; + } -/***/ }), -/* 1624 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + const returnValue = []; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); -"use strict"; + inputValue.forEach((item) => { + returnValue.push(_dropUndefinedKeys(item, memoizationMap)); + }); + return returnValue ; + } -var AxiosError = __webpack_require__(1613); -var utils = __webpack_require__(1604); + return inputValue; +} /** - * A `CanceledError` is an object that is thrown when an operation is canceled. + * Ensure that something is an object. * - * @class - * @param {string=} message The message. + * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper + * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. + * + * @param wat The subject of the objectification + * @returns A version of `wat` which can safely be used with `Object` class methods */ -function CanceledError(message) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); - this.name = 'CanceledError'; +function objectify(wat) { + let objectified; + switch (true) { + case wat === undefined || wat === null: + objectified = new String(wat); + break; + + // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason + // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as + // an object in order to wrap it. + case typeof wat === 'symbol' || typeof wat === 'bigint': + objectified = Object(wat); + break; + + // this will catch the remaining primitives: `String`, `Number`, and `Boolean` + case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + objectified = new (wat ).constructor(wat); + break; + + // by process of elimination, at this point we know that `wat` must already be an object + default: + objectified = wat; + break; + } + return objectified; } -utils.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); -module.exports = CanceledError; +//# sourceMappingURL=object.js.map /***/ }), -/* 1625 */ -/***/ ((module) => { +/* 1612 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), +/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), +/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -module.exports = function parseProtocol(url) { - var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; -}; +// eslint-disable-next-line deprecation/deprecation +const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); -/***/ }), -/* 1626 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Given a child DOM element, returns a query-selector statement describing that + * and its ancestors + * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] + * @returns generated DOM path + */ +function htmlTreeAsString(elem, keyAttrs) { -"use strict"; + // try/catch both: + // - accessing event.target (see getsentry/raven-js#838, #768) + // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly + // - can throw an exception in some circumstances. + try { + let currentElem = elem ; + const MAX_TRAVERSE_HEIGHT = 5; + const MAX_OUTPUT_LEN = 80; + const out = []; + let height = 0; + let len = 0; + const separator = ' > '; + const sepLength = separator.length; + let nextStr; + while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem, keyAttrs); + // bail out if + // - nextStr is the 'html' element + // - the length of the string that would be created exceeds MAX_OUTPUT_LEN + // (ignore this limit if we are on the first iteration) + if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { + break; + } -var utils = __webpack_require__(1604); -var settle = __webpack_require__(1617); -var buildFullPath = __webpack_require__(1619); -var buildURL = __webpack_require__(1607); -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var httpFollow = (__webpack_require__(1627).http); -var httpsFollow = (__webpack_require__(1627).https); -var url = __webpack_require__(63); -var zlib = __webpack_require__(83); -var VERSION = (__webpack_require__(1629).version); -var transitionalDefaults = __webpack_require__(1614); -var AxiosError = __webpack_require__(1613); -var CanceledError = __webpack_require__(1624); + out.push(nextStr); -var isHttps = /https:?/; + len += nextStr.length; + currentElem = currentElem.parentNode; + } -var supportedProtocols = [ 'http:', 'https:', 'file:' ]; + return out.reverse().join(separator); + } catch (_oO) { + return '<unknown>'; + } +} /** - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location + * Returns a simple, query-selector representation of a DOM element + * e.g. [HTMLElement] => input#foo.btn[name=baz] + * @returns generated DOM path */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; +function _htmlElementAsString(el, keyAttrs) { + const elem = el - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } +; - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); - }; -} + const out = []; + let className; + let classes; + let key; + let attr; + let i; -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } + if (!elem || !elem.tagName) { + return ''; + } - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - var resolve = function resolve(value) { - done(); - resolvePromise(value); - }; - var rejected = false; - var reject = function reject(value) { - done(); - rejected = true; - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; - var headerNames = {}; + out.push(elem.tagName.toLowerCase()); - Object.keys(headers).forEach(function storeLowerName(name) { - headerNames[name.toLowerCase()] = name; + // Pairs of attribute keys defined in `serializeAttribute` and their values on element. + const keyAttrPairs = + keyAttrs && keyAttrs.length + ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) + : null; + + if (keyAttrPairs && keyAttrPairs.length) { + keyAttrPairs.forEach(keyAttrPair => { + out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); }); + } else { + if (elem.id) { + out.push(`#${elem.id}`); + } - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - if ('user-agent' in headerNames) { - // User-Agent is specified; handle case where no UA header is desired - if (!headers[headerNames['user-agent']]) { - delete headers[headerNames['user-agent']]; + // eslint-disable-next-line prefer-const + className = elem.className; + if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { + classes = className.split(/\s+/); + for (i = 0; i < classes.length; i++) { + out.push(`.${classes[i]}`); } - // Otherwise, use specified value - } else { - // Only set header if it hasn't been set in config - headers['User-Agent'] = 'axios/' + VERSION; } + } + const allowedAttrs = ['type', 'name', 'title', 'alt']; + for (i = 0; i < allowedAttrs.length; i++) { + key = allowedAttrs[i]; + attr = elem.getAttribute(key); + if (attr) { + out.push(`[${key}="${attr}"]`); + } + } + return out.join(''); +} - // support for https://www.npmjs.com/package/form-data api - if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { - Object.assign(headers, data.getHeaders()); - } else if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new AxiosError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - AxiosError.ERR_BAD_REQUEST, - config - )); - } +/** + * A safe form of location.href + */ +function getLocationHref() { + try { + return WINDOW.document.location.href; + } catch (oO) { + return ''; + } +} - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new AxiosError( - 'Request body larger than maxBodyLength limit', - AxiosError.ERR_BAD_REQUEST, - config - )); - } +/** + * Gets a DOM element by using document.querySelector. + * + * This wrapper will first check for the existance of the function before + * actually calling it so that we don't have to take care of this check, + * every time we want to access the DOM. + * + * Reason: DOM/querySelector is not available in all environments. + * + * We have to cast to any because utils can be consumed by a variety of environments, + * and we don't want to break TS users. If you know what element will be selected by + * `document.querySelector`, specify it as part of the generic call. For example, + * `const element = getDomElement<Element>('selector');` + * + * @param selector the selector string passed on to document.querySelector + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getDomElement(selector) { + if (WINDOW.document && WINDOW.document.querySelector) { + return WINDOW.document.querySelector(selector) ; + } + return null; +} - // Add Content-Length header if data exists - if (!headerNames['content-length']) { - headers['Content-Length'] = data.length; - } - } - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } +//# sourceMappingURL=browser.js.map - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || supportedProtocols[0]; - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError( - 'Unsupported protocol ' + protocol, - AxiosError.ERR_BAD_REQUEST, - config - )); - } +/***/ }), +/* 1613 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), +/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), +/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); - if (auth && headerNames.authorization) { - delete headers[headerNames.authorization]; - } - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; +/* eslint-disable @typescript-eslint/explicit-function-return-type */ - try { - buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''); - } catch (err) { - var customErr = new Error(err.message); - customErr.config = config; - customErr.url = config.url; - customErr.exists = true; - reject(customErr); - } +/** SyncPromise internal states */ +var States; (function (States) { + /** Pending */ + const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; + /** Resolved / OK */ + const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; + /** Rejected / Error */ + const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; +})(States || (States = {})); - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; +// Overloads so we can call resolvedSyncPromise without arguments and generic argument - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; - } +/** + * Creates a resolved sync promise. + * + * @param value the value to resolve the promise with + * @returns the resolved sync promise + */ +function resolvedSyncPromise(value) { + return new SyncPromise(resolve => { + resolve(value); + }); +} - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; +/** + * Creates a rejected sync promise. + * + * @param value the value to reject the promise with + * @returns the rejected sync promise + */ +function rejectedSyncPromise(reason) { + return new SyncPromise((_, reject) => { + reject(reason); + }); +} - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); +/** + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally + */ +class SyncPromise { + __init() {this._state = States.PENDING;} + __init2() {this._handlers = [];} - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; + constructor( + executor, + ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); + try { + executor(this._resolve, this._reject); + } catch (e) { + this._reject(e); + } + } + + /** JSDoc */ + then( + onfulfilled, + onrejected, + ) { + return new SyncPromise((resolve, reject) => { + this._handlers.push([ + false, + result => { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result ); + } else { + try { + resolve(onfulfilled(result)); + } catch (e) { + reject(e); } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; + } + }, + reason => { + if (!onrejected) { + reject(reason); + } else { + try { + resolve(onrejected(reason)); + } catch (e) { + reject(e); } + } + }, + ]); + this._executeHandlers(); + }); + } - return parsed.hostname === proxyElement; - }); - } + /** JSDoc */ + catch( + onrejected, + ) { + return this.then(val => val, onrejected); + } - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; + /** JSDoc */ + finally(onfinally) { + return new SyncPromise((resolve, reject) => { + let val; + let isRejected; - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; + return this.then( + value => { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); } + }, + reason => { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }, + ).then(() => { + if (isRejected) { + reject(val); + return; } - } - } - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } + resolve(val ); + }); + }); + } - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirect = config.beforeRedirect; - } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } + /** JSDoc */ + __init3() {this._resolve = (value) => { + this._setResult(States.RESOLVED, value); + };} - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } + /** JSDoc */ + __init4() {this._reject = (reason) => { + this._setResult(States.REJECTED, reason); + };} - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; + /** JSDoc */ + __init5() {this._setResult = (state, value) => { + if (this._state !== States.PENDING) { + return; } - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { + void (value ).then(this._resolve, this._reject); + return; + } - // uncompress the response body transparently if required - var stream = res; + this._state = state; + this._value = value; - // return the last request in case of redirects - var lastRequest = res.req || req; + this._executeHandlers(); + };} + /** JSDoc */ + __init6() {this._executeHandlers = () => { + if (this._state === States.PENDING) { + return; + } - // if no content, is HEAD request or decompress disabled we should not decompress - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = stream.pipe(zlib.createUnzip()); + const cachedHandlers = this._handlers.slice(); + this._handlers = []; - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - } + cachedHandlers.forEach(handler => { + if (handler[0]) { + return; } - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; - - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - var totalResponseBytes = 0; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - // stream.destoy() emit aborted event before calling reject() on Node.js v16 - rejected = true; - stream.destroy(); - reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); - } - }); - - stream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } - stream.destroy(); - reject(new AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, - config, - lastRequest - )); - }); - - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(AxiosError.from(err, null, config, lastRequest)); - }); + if (this._state === States.RESOLVED) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler[1](this._value ); + } - stream.on('end', function handleStreamEnd() { - try { - var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - if (!config.responseEncoding || config.responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - reject(AxiosError.from(err, null, config, response.request, response)); - } - settle(resolve, reject, response); - }); + if (this._state === States.REJECTED) { + handler[2](this._value); } - }); - // Handle errors - req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(AxiosError.from(err, null, config, req)); + handler[0] = true; }); + };} +} - // set tcp keep alive to prevent drop connection by peer - req.on('socket', function handleRequestSocket(socket) { - // default interval of sending ack packet is 1 minute - socket.setKeepAlive(true, 1000 * 60); - }); - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - var timeout = parseInt(config.timeout, 10); +//# sourceMappingURL=syncpromise.js.map - if (isNaN(timeout)) { - reject(new AxiosError( - 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); - return; - } +/***/ }), +/* 1614 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - req.abort(); - var transitional = config.transitional || transitionalDefaults; - reject(new AxiosError( - 'timeout of ' + timeout + 'ms exceeded', - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - req - )); - }); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), +/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), +/* harmony export */ "logger": () => (/* binding */ logger) +/* harmony export */ }); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (req.aborted) return; - req.abort(); - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); - }; +/** Prefix for logging strings */ +const PREFIX = 'Sentry Logger '; - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } +const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; +/** + * Temporarily disable sentry console instrumentations. + * + * @param callback The function to run against the original `console` messages + * @returns The results of the callback + */ +function consoleSandbox(callback) { + if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { + return callback(); + } - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(AxiosError.from(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); + const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; + const wrappedLevels = {}; + + // Restore all wrapped console methods + CONSOLE_LEVELS.forEach(level => { + // TODO(v7): Remove this check as it's only needed for Node 6 + const originalWrappedFunc = + originalConsole[level] && (originalConsole[level] ).__sentry_original__; + if (level in originalConsole && originalWrappedFunc) { + wrappedLevels[level] = originalConsole[level] ; + originalConsole[level] = originalWrappedFunc ; } }); -}; - - -/***/ }), -/* 1627 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var url = __webpack_require__(63); -var URL = url.URL; -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var Writable = (__webpack_require__(82).Writable); -var assert = __webpack_require__(91); -var debug = __webpack_require__(1628); + try { + return callback(); + } finally { + // Revert restoration to wrapped state + Object.keys(wrappedLevels).forEach(level => { + originalConsole[level] = wrappedLevels[level ]; + }); + } +} -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); +function makeLogger() { + let enabled = false; + const logger = { + enable: () => { + enabled = true; + }, + disable: () => { + enabled = false; + }, }; -}); - -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + CONSOLE_LEVELS.forEach(name => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + logger[name] = (...args) => { + if (enabled) { + consoleSandbox(() => { + _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); + }); + } + }; + }); + } else { + CONSOLE_LEVELS.forEach(name => { + logger[name] = () => undefined; + }); } - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; - - // Perform the first request - this._performRequest(); + return logger ; } -RedirectableRequest.prototype = Object.create(Writable.prototype); -RedirectableRequest.prototype.abort = function () { - abortRequest(this._currentRequest); - this.emit("abort"); -}; +// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used +let logger; +if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); +} else { + logger = makeLogger(); +} -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } +//# sourceMappingURL=logger.js.map - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } +/***/ }), +/* 1615 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) +/* harmony export */ }); +const SDK_VERSION = '7.23.0'; -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; +//# sourceMappingURL=version.js.map -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } +/***/ }), +/* 1616 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), +/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), +/* harmony export */ "captureException": () => (/* binding */ captureException), +/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), +/* harmony export */ "configureScope": () => (/* binding */ configureScope), +/* harmony export */ "setContext": () => (/* binding */ setContext), +/* harmony export */ "setExtra": () => (/* binding */ setExtra), +/* harmony export */ "setExtras": () => (/* binding */ setExtras), +/* harmony export */ "setTag": () => (/* binding */ setTag), +/* harmony export */ "setTags": () => (/* binding */ setTags), +/* harmony export */ "setUser": () => (/* binding */ setUser), +/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), +/* harmony export */ "withScope": () => (/* binding */ withScope) +/* harmony export */ }); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } +// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, +// where HUB_FUNCTION is some method on the Hub class. +// +// This is done to make sure the top level SDK methods stay in sync with the hub methods. +// Although every method here has an explicit return type, some of them (that map to void returns) do not +// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } +/** + * Captures an exception event and sends it to Sentry. + * + * @param exception An exception-like object. + * @param captureContext Additional scope data to apply to exception event. + * @returns The generated eventId. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types +function captureException(exception, captureContext) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); +} - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } +/** + * Captures a message event and sends it to Sentry. + * + * @param message The message to send to Sentry. + * @param Severity Define the level of the message. + * @returns The generated eventId. + */ +function captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + captureContext, +) { + // This is necessary to provide explicit scopes upgrade, without changing the original + // arity of the `captureMessage(message, level)` method. + const level = typeof captureContext === 'string' ? captureContext : undefined; + const context = typeof captureContext !== 'string' ? { captureContext } : undefined; + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); +} - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); +/** + * Captures a manually created event and sends it to Sentry. + * + * @param event The event to send to Sentry. + * @returns The generated eventId. + */ +function captureEvent(event, hint) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); +} - return this; -}; +/** + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. + */ +function configureScope(callback) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); +} -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); +/** + * Records a new breadcrumb which will be attached to future events. + * + * Breadcrumbs will be added to subsequent events to provide more context on + * user's actions prior to an error or crash. + * + * @param breadcrumb The breadcrumb to record. + */ +function addBreadcrumb(breadcrumb) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); +} -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); +/** + * Sets context data with the given name. + * @param name of the context + * @param context Any kind of data. This data will be normalized. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContext(name, context) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); +} -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } +/** + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. + */ +function setExtras(extras) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); +} - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } +/** + * Set key:value that will be sent as extra data with the event. + * @param key String of extra + * @param extra Any kind of data. This data will be normalized. + */ +function setExtra(key, extra) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); +} - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; +/** + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. + */ +function setTags(tags) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); +} +/** + * Set key:value that will be sent as tags data with the event. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key String key of tag + * @param value Value of tag + */ +function setTag(key, value) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); +} -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } +/** + * Updates user context information for future events. + * + * @param user User context object to be set in the current context. Pass `null` to unset the user. + */ +function setUser(user) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); +} - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } +/** + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. + * + * This is essentially a convenience function for: + * + * pushScope(); + * callback(); + * popScope(); + * + * @param callback that will be enclosed into push/popScope. + */ +function withScope(callback) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); +} - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } +/** + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call + * `startTransaction` directly on the hub. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started + */ +function startTransaction( + context, + customSamplingContext, +) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); +} - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._currentUrl = this._options.path; - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; +//# sourceMappingURL=exports.js.map -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. +/***/ }), +/* 1617 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), +/* harmony export */ "createTransport": () => (/* binding */ createTransport) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1618); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1619); - // Clean up - this._requestBodyBuffers = []; - return; - } - // The response is a redirect, so abort the current request - abortRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); +const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } +/** + * Creates an instance of a Sentry `Transport` + * + * @param options + * @param makeRequest + */ +function createTransport( + options, + makeRequest, + buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), +) { + let rateLimits = {}; - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } + const flush = (timeout) => buffer.drain(timeout); - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } + function send(envelope) { + const filteredEnvelopeItems = []; - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + // Drop rate limited items from envelope + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { + const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); + } else { + filteredEnvelopeItems.push(item); + } + }); - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = url.parse(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); + // Skip sending if envelope is empty after filtering out rate limited events + if (filteredEnvelopeItems.length === 0) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); + } - // Determine the URL of the redirection - var redirectUrl; - try { - redirectUrl = url.resolve(currentUrl, location); - } - catch (cause) { - this.emit("error", new RedirectionError(cause)); - return; - } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); - // Create the redirected request - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); + // Creates client report for each item in an envelope + const recordEnvelopeLoss = (reason) => { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); + }); + }; - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrlParts.protocol !== currentUrlParts.protocol && - redirectUrlParts.protocol !== "https:" || - redirectUrlParts.host !== currentHost && - !isSubdomain(redirectUrlParts.host, currentHost)) { - removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); - } + const requestTask = () => + makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( + response => { + // We don't want to throw on NOK responses, but we want to at least log them + if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); + } - // Evaluate the beforeRedirect callback - if (typeof beforeRedirect === "function") { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - try { - beforeRedirect(this._options, responseDetails, requestDetails); - } - catch (err) { - this.emit("error", err); - return; - } - this._sanitizeOptions(this._options); - } + rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); + }, + error => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); + recordEnvelopeLoss('network_error'); + }, + ); - // Perform the redirected request - try { - this._performRequest(); - } - catch (cause) { - this.emit("error", new RedirectionError(cause)); + return buffer.add(requestTask).then( + result => result, + error => { + if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); + recordEnvelopeLoss('queue_overflow'); + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); + } else { + throw error; + } + }, + ); } -}; -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, + return { + send, + flush, }; +} - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); +function getEventForEnvelopeItem(item, type) { + if (type !== 'event' && type !== 'transaction') { + return undefined; + } - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url.parse(urlStr); - } - } - else if (URL && (input instanceof URL)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } + return Array.isArray(item) ? (item )[1] : undefined; +} - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } +//# sourceMappingURL=base.js.map - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} +/***/ }), +/* 1618 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/* istanbul ignore next */ -function noop() { /* empty */ } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) +/* harmony export */ }); +/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1619); +/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1613); -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); + + +/** + * Creates an new PromiseBuffer object with the specified limit + * @param limit max number of promises that can be stored in the buffer + */ +function makePromiseBuffer(limit) { + const buffer = []; + + function isReady() { + return limit === undefined || buffer.length < limit; } - return options; -} -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } + /** + * Remove a promise from the queue. + * + * @param task Can be any PromiseLike<T> + * @returns Removed promise. + */ + function remove(task) { + return buffer.splice(buffer.indexOf(task), 1)[0]; } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} -function createErrorType(code, defaultMessage) { - function CustomError(cause) { - Error.captureStackTrace(this, this.constructor); - if (!cause) { - this.message = defaultMessage; + /** + * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. + * + * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: + * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor + * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By + * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer + * limit check. + * @returns The original promise. + */ + function add(taskProducer) { + if (!isReady()) { + return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); } - else { - this.message = defaultMessage + ": " + cause.message; - this.cause = cause; + + // start the task and add its promise to the queue + const task = taskProducer(); + if (buffer.indexOf(task) === -1) { + buffer.push(task); } + void task + .then(() => remove(task)) + // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` + // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't + // have promises, so TS has to polyfill when down-compiling.) + .then(null, () => + remove(task).then(null, () => { + // We have to add another catch here because `remove()` starts a new promise chain. + }), + ); + return task; } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} -function abortRequest(request) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.abort(); -} + /** + * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or + * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to + * `true`. + * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and + * `false` otherwise + */ + function drain(timeout) { + return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { + let counter = buffer.length; -function isSubdomain(subdomain, domain) { - const dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} + if (!counter) { + return resolve(true); + } -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; + // wait for `timeout` ms and then resolve to `false` (if not cancelled first) + const capturedSetTimeout = setTimeout(() => { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); + // if all promises resolve in time, cancel the timer and resolve to `true` + buffer.forEach(item => { + void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { + if (!--counter) { + clearTimeout(capturedSetTimeout); + resolve(true); + } + }, reject); + }); + }); + } -/***/ }), -/* 1628 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return { + $: buffer, + add, + drain, + }; +} -var debug; -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __webpack_require__(1402)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; - } - } - debug.apply(null, arguments); -}; +//# sourceMappingURL=promisebuffer.js.map /***/ }), -/* 1629 */ -/***/ ((module) => { +/* 1619 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -module.exports = { - "version": "0.27.2" -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SentryError": () => (/* binding */ SentryError) +/* harmony export */ }); +/** An error emitted by Sentry SDKs and related utilities. */ +class SentryError extends Error { + /** Display name of this error instance. */ -/***/ }), -/* 1630 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + constructor( message, logLevel = 'warn') { + super(message);this.message = message;; -// eslint-disable-next-line strict -module.exports = __webpack_require__(1631); + this.name = new.target.prototype.constructor.name; + // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line + // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes + // instances of `SentryError` fail `obj instanceof SentryError` checks. + Object.setPrototypeOf(this, new.target.prototype); + this.logLevel = logLevel; + } +} + + +//# sourceMappingURL=error.js.map /***/ }), -/* 1631 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1620 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -var CombinedStream = __webpack_require__(147); -var util = __webpack_require__(64); -var path = __webpack_require__(142); -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var parseUrl = (__webpack_require__(63).parse); -var fs = __webpack_require__(149); -var Stream = (__webpack_require__(82).Stream); -var mime = __webpack_require__(139); -var asynckit = __webpack_require__(150); -var populate = __webpack_require__(1632); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), +/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), +/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), +/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), +/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), +/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) +/* harmony export */ }); +/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1621); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); -// Public API -module.exports = FormData; -// make it a Stream -util.inherits(FormData, CombinedStream); /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * Creates an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; +function createEnvelope(headers, items = []) { + return [headers, items] ; +} - CombinedStream.call(this); +/** + * Add an item to an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. + */ +function addItemToEnvelope(envelope, newItem) { + const [headers, items] = envelope; + return [headers, [...items, newItem]] ; +} - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } +/** + * Convenience function to loop through the items and item types of an envelope. + * (This function was mostly created because working with envelope types is painful at the moment) + */ +function forEachEnvelopeItem( + envelope, + callback, +) { + const envelopeItems = envelope[1]; + envelopeItems.forEach((envelopeItem) => { + const envelopeItemType = envelopeItem[0].type; + callback(envelopeItem, envelopeItemType); + }); } -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; +function encodeUTF8(input, textEncoder) { + const utf8 = textEncoder || new TextEncoder(); + return utf8.encode(input); +} -FormData.prototype.append = function(field, value, options) { +/** + * Serializes an envelope. + */ +function serializeEnvelope(envelope, textEncoder) { + const [envHeaders, items] = envelope; - options = options || {}; + // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data + let parts = JSON.stringify(envHeaders); - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; + function append(next) { + if (typeof parts === 'string') { + parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; + } else { + parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); + } } - var append = CombinedStream.prototype.append.bind(this); + for (const item of items) { + const [itemHeaders, payload] = item; - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } + append(`\n${JSON.stringify(itemHeaders)}\n`); - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; + if (typeof payload === 'string' || payload instanceof Uint8Array) { + append(payload); + } else { + let stringifiedPayload; + try { + stringifiedPayload = JSON.stringify(payload); + } catch (e) { + // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still + // fails, we try again after normalizing it again with infinite normalization depth. This of course has a + // performance impact but in this case a performance hit is better than throwing. + stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); + } + append(stringifiedPayload); + } } - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; + return typeof parts === 'string' ? parts : concatBuffers(parts); +} -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; +function concatBuffers(buffers) { + const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const buffer of buffers) { + merged.set(buffer, offset); + offset += buffer.length; } - this._valueLength += valueLength; + return merged; +} - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; +/** + * Creates attachment envelope items + */ +function createAttachmentEnvelopeItem( + attachment, + textEncoder, +) { + const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } + return [ + (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ + type: 'attachment', + length: buffer.length, + filename: attachment.filename, + content_type: attachment.contentType, + attachment_type: attachment.attachmentType, + }), + buffer, + ]; +} - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } +const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { + session: 'session', + sessions: 'session', + attachment: 'attachment', + transaction: 'transaction', + event: 'error', + client_report: 'internal', + user_report: 'default', }; -FormData.prototype._lengthRetriever = function(value, callback) { +/** + * Maps the type of an envelope item to a data category. + */ +function envelopeItemTypeToDataCategory(type) { + return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; +} - if (value.hasOwnProperty('fd')) { - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { +//# sourceMappingURL=envelope.js.map - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +/***/ }), +/* 1621 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - var fileSize; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "normalize": () => (/* binding */ normalize), +/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), +/* harmony export */ "walk": () => (/* binding */ visit) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1622); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); +/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1623); - if (err) { - callback(err); - return; - } - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - // something else - } else { - callback('Unknown stream'); +/** + * Recursively normalizes the given object. + * + * - Creates a copy to prevent original input mutation + * - Skips non-enumerable properties + * - When stringifying, calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format + * - Translates known global objects/classes to a string representations + * - Takes care of `Error` object serialization + * - Optionally limits depth of final output + * - Optionally limits number of properties/elements included in any single object/array + * + * @param input The object to be normalized. + * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) + * @param maxProperties The max number of elements or properties to be included in any single array or + * object in the normallized output. + * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function normalize(input, depth = +Infinity, maxProperties = +Infinity) { + try { + // since we're at the outermost level, we don't provide a key + return visit('', input, depth, maxProperties); + } catch (err) { + return { ERROR: `**non-serializable** (${err})` }; } -}; +} -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; +/** JSDoc */ +function normalizeToSize( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object, + // Default Node.js REPL depth + depth = 3, + // 100kB, as 200kB is max payload size, so half sounds reasonable + maxSize = 100 * 1024, +) { + const normalized = normalize(object, depth); + + if (jsonSize(normalized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); } - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); + return normalized ; +} - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +/** + * Visits a node to perform normalization on it + * + * @param key The key corresponding to the given node + * @param value The node to be visited + * @param depth Optional number indicating the maximum recursion depth + * @param maxProperties Optional maximum number of properties/elements included in any single object/array + * @param memo Optional Memo class handling decycling + */ +function visit( + key, + value, + depth = +Infinity, + maxProperties = +Infinity, + memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), +) { + const [memoize, unmemoize] = memo; - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); + // Get the simple cases out of the way first + if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { + return value ; } - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; + const stringified = stringifyValue(key, value); - // skip nullish headers. - if (header == null) { - continue; - } + // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. + // Everything else will have already been serialized, so if we don't see that pattern, we're done. + if (!stringified.startsWith('[object ')) { + return stringified; + } - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } + // From here on, we can assert that `value` is either an object or an array. - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } + // Do not normalize objects that we know have already been normalized. As a general rule, the + // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that + // have already been normalized. + if ((value )['__sentry_skip_normalization__']) { + return value ; } - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { + // We're also done if we've reached the max depth + if (depth === 0) { + // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. + return stringified.replace('object ', ''); + } - var filename - , contentDisposition - ; + // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. + if (memoize(value)) { + return '[Circular ~]'; + } - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); + // If the value has a `toJSON` method, we call it to extract more information + const valueWithToJSON = value ; + if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { + try { + const jsonValue = valueWithToJSON.toJSON(); + // We need to normalize the return value of `.toJSON()` in case it has circular references + return visit('', jsonValue, depth - 1, maxProperties, memo); + } catch (err) { + // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) + } } - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } + // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse + // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each + // property/entry, and keep track of the number of items we add to it. + const normalized = (Array.isArray(value) ? [] : {}) ; + let numAdded = 0; - return contentDisposition; -}; + // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant + // properties are non-enumerable and otherwise would get missed. + const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); -FormData.prototype._getContentType = function(value, options) { + for (const visitKey in visitable) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { + continue; + } - // use custom content-type above all - var contentType = options.contentType; + if (numAdded >= maxProperties) { + normalized[visitKey] = '[MaxProperties ~]'; + break; + } - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } + // Recursively visit all the child nodes + const visitValue = visitable[visitKey]; + normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); + numAdded++; } - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } + // Once we've visited all the branches, remove the parent from memo storage + unmemoize(value); - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } + // Return accumulated values + return normalized; +} - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } +/** + * Stringify the given value. Handles various known special values and types. + * + * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn + * the number 1231 into "[Object Number]", nor on `null`, as it will throw. + * + * @param value The value to stringify + * @returns A stringified representation of the given value + */ +function stringifyValue( + key, + // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for + // our internal use, it'll do + value, +) { + try { + if (key === 'domain' && value && typeof value === 'object' && (value )._events) { + return '[Domain]'; + } - return contentType; -}; + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; + // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first + // which won't throw if they are not present. - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; } - next(footer); - }.bind(this); -}; + // eslint-disable-next-line no-restricted-globals + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; + // eslint-disable-next-line no-restricted-globals + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; + // React's SyntheticEvent thingy + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { + return '[SyntheticEvent]'; + } - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; + if (typeof value === 'number' && value !== value) { + return '[NaN]'; } - } - return formHeaders; -}; + // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) + if (value === void 0) { + return '[undefined]'; + } -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; + if (typeof value === 'function') { + return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; + } -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + if (typeof value === 'symbol') { + return `[${String(value)}]`; + } + + // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion + if (typeof value === 'bigint') { + return `[BigInt: ${String(value)}]`; + } + + // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting + // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as + // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), + // we can make sure that only plain objects come out that way. + return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; + } catch (err) { + return `**non-serializable** (${err})`; } +} - return this._boundary; -}; +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); +/** Calculates bytes size of input object */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); +} - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } +//# sourceMappingURL=normalize.js.map - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + +/***/ }), +/* 1622 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) +/* harmony export */ }); +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +/** + * Helper to decycle json objects + */ +function memoBuilder() { + const hasWeakSet = typeof WeakSet === 'function'; + const inner = hasWeakSet ? new WeakSet() : []; + function memoize(obj) { + if (hasWeakSet) { + if (inner.has(obj)) { + return true; + } + inner.add(obj); + return false; + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < inner.length; i++) { + const value = inner[i]; + if (value === obj) { + return true; } } + inner.push(obj); + return false; } - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); + function unmemoize(obj) { + if (hasWeakSet) { + inner.delete(obj); + } else { + for (let i = 0; i < inner.length; i++) { + if (inner[i] === obj) { + inner.splice(i, 1); + break; + } + } + } } + return [memoize, unmemoize]; +} - this._boundary = boundary; -}; -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; +//# sourceMappingURL=memo.js.map - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } +/***/ }), +/* 1623 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - return knownLength; -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), +/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), +/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), +/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), +/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) +/* harmony export */ }); +/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1624); -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } +const STACKTRACE_LIMIT = 50; - return hasKnownLength; -}; +/** + * Creates a stack parser with the supplied line parsers + * + * StackFrames are returned in the correct order for Sentry Exception + * frames and with Sentry SDK internal frames removed from the top and bottom + * + */ +function createStackParser(...parsers) { + const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; + return (stack, skipFirst = 0) => { + const frames = []; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } + for (const line of stack.split('\n').slice(skipFirst)) { + // https://github.com/getsentry/sentry-javascript/issues/5459 + // Remove webpack (error: *) wrappers + const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } + for (const parser of sortedParsers) { + const frame = parser(cleanedLine); - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; + if (frame) { + frames.push(frame); + break; + } + } } - values.forEach(function(length) { - knownLength += length; - }); - - cb(null, knownLength); - }); -}; + return stripSentryFramesAndReverse(frames); + }; +} -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; +/** + * Gets a stack parser implementation from Options.stackParser + * @see Options + * + * If options contains an array of line parsers, it is converted into a parser + */ +function stackParserFromStackParserOptions(stackParser) { + if (Array.isArray(stackParser)) { + return createStackParser(...stackParser); + } + return stackParser; +} - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { +/** + * @hidden + */ +function stripSentryFramesAndReverse(stack) { + if (!stack.length) { + return []; + } - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); + let localStack = stack; - // use custom params - } else { + const firstFrameFunction = localStack[0].function || ''; + const lastFrameFunction = localStack[localStack.length - 1].function || ''; - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } + // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); + // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) + if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { + localStack = localStack.slice(0, -1); } - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } + // The frame where the crash happened, should be the last entry in the array + return localStack + .slice(0, STACKTRACE_LIMIT) + .map(frame => ({ + ...frame, + filename: frame.filename || localStack[0].filename, + function: frame.function || '?', + })) + .reverse(); +} - // add content length - if (length) { - request.setHeader('Content-Length', length); - } +const defaultFunctionName = '<anonymous>'; - this.pipe(request); - if (cb) { - var onResponse; +/** + * Safely extract function name from itself + */ +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } +} - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); +// eslint-disable-next-line complexity +function node(getModule) { + const FILENAME_MATCH = /^\s*[-]{4,}$/; + const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; - return cb.call(this, error, responce); + // eslint-disable-next-line complexity + return (line) => { + if (line.match(FILENAME_MATCH)) { + return { + filename: line, }; + } - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); + const lineMatch = line.match(FULL_MATCH); + if (!lineMatch) { + return undefined; } - }.bind(this)); - return request; -}; + let object; + let method; + let functionName; + let typeName; + let methodName; -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; + if (lineMatch[1]) { + functionName = lineMatch[1]; -FormData.prototype.toString = function () { - return '[object FormData]'; -}; + let methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') { + methodStart--; + } + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + const objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = undefined; + } -/***/ }), -/* 1632 */ -/***/ ((module) => { + if (method) { + typeName = object; + methodName = method; + } -// populates missing values -module.exports = function(dst, src) { + if (method === '<anonymous>') { + methodName = undefined; + functionName = undefined; + } - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); + if (functionName === undefined) { + methodName = methodName || '<anonymous>'; + functionName = typeName ? `${typeName}.${methodName}` : methodName; + } - return dst; -}; + const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; + const isNative = lineMatch[5] === 'native'; + const isInternal = + isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 + const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); -/***/ }), -/* 1633 */ -/***/ ((module) => { + return { + filename, + module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), + function: functionName, + lineno: parseInt(lineMatch[3], 10) || undefined, + colno: parseInt(lineMatch[4], 10) || undefined, + in_app, + }; + }; +} -"use strict"; +/** + * Node.js stack line parser + * + * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. + * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain + */ +function nodeStackLineParser(getModule) { + return [90, node(getModule)]; +} -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; +//# sourceMappingURL=stacktrace.js.map /***/ }), -/* 1634 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1624 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - - -var utils = __webpack_require__(1604); - +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) +/* harmony export */ }); /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions. * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * + * @param ops Array result of expression conversion + * @returns The value of the expression */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); +function _optionalChain(ops) { + let lastAccessLHS = undefined; + let value = ops[0]; + let i = 1; + while (i < ops.length) { + const op = ops[i] ; + const fn = ops[i + 1] ; + i += 2; + // by checking for loose equality to `null`, we catch both `null` and `undefined` + if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { + // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it + return; } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); + if (op === 'access' || op === 'optionalAccess') { + lastAccessLHS = value; + value = fn(value); + } else if (op === 'call' || op === 'optionalCall') { + value = fn((...args) => (value ).call(lastAccessLHS, ...args)); + lastAccessLHS = undefined; } } + return value; +} - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'beforeRedirect': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; +// Sucrase version +// function _optionalChain(ops) { +// let lastAccessLHS = undefined; +// let value = ops[0]; +// let i = 1; +// while (i < ops.length) { +// const op = ops[i]; +// const fn = ops[i + 1]; +// i += 2; +// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { +// return undefined; +// } +// if (op === 'access' || op === 'optionalAccess') { +// lastAccessLHS = value; +// value = fn(value); +// } else if (op === 'call' || op === 'optionalCall') { +// value = fn((...args) => value.call(lastAccessLHS, ...args)); +// lastAccessLHS = undefined; +// } +// } +// return value; +// } - utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - return config; -}; +//# sourceMappingURL=_optionalChain.js.map /***/ }), -/* 1635 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1625 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), +/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), +/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), +/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), +/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) +/* harmony export */ }); +// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend - -var VERSION = (__webpack_require__(1629).version); -var AxiosError = __webpack_require__(1613); - -var validators = {}; - -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { - validators[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); - -var deprecatedWarnings = {}; +const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds /** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} + * Extracts Retry-After value from the request header or returns default value + * @param header string representation of 'Retry-After' header + * @param now current unix timestamp + * */ -validators.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); +function parseRetryAfterHeader(header, now = Date.now()) { + const headerDelay = parseInt(`${header}`, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; } - // eslint-disable-next-line func-names - return function(value, opt, opts) { - if (validator === false) { - throw new AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED - ); - } + const headerDate = Date.parse(`${header}`); + if (!isNaN(headerDate)) { + return headerDate - now; + } - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); - } + return DEFAULT_RETRY_AFTER; +} - return validator ? validator(value, opt, opts) : true; - }; -}; +/** + * Gets the time that given category is disabled until for rate limiting + */ +function disabledUntil(limits, category) { + return limits[category] || limits.all || 0; +} /** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown + * Checks if a category is rate limited */ +function isRateLimited(limits, category, now = Date.now()) { + return disabledUntil(limits, category) > now; +} -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); - } - var keys = Object.keys(options); - var i = keys.length; - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); +/** + * Update ratelimits from incoming headers. + * Returns true if headers contains a non-empty rate limiting header. + */ +function updateRateLimits( + limits, + { statusCode, headers }, + now = Date.now(), +) { + const updatedRateLimits = { + ...limits, + }; + + // "The name is case-insensitive." + // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get + const rateLimitHeader = headers && headers['x-sentry-rate-limits']; + const retryAfterHeader = headers && headers['retry-after']; + + if (rateLimitHeader) { + /** + * rate limit headers are of the form + * <header>,<header>,.. + * where each <header> is of the form + * <retry_after>: <categories>: <scope>: <reason_code> + * where + * <retry_after> is a delay in seconds + * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form + * <category>;<category>;... + * <scope> is what's being limited (org, project, or key) - ignored by SDK + * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK + */ + for (const limit of rateLimitHeader.trim().split(',')) { + const [retryAfter, categories] = limit.split(':', 2); + const headerDelay = parseInt(retryAfter, 10); + const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default + if (!categories) { + updatedRateLimits.all = now + delay; + } else { + for (const category of categories.split(';')) { + updatedRateLimits[category] = now + delay; + } } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); } + } else if (retryAfterHeader) { + updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); + } else if (statusCode === 429) { + updatedRateLimits.all = now + 60 * 1000; } + + return updatedRateLimits; } -module.exports = { - assertOptions: assertOptions, - validators: validators -}; + +//# sourceMappingURL=ratelimit.js.map /***/ }), -/* 1636 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1626 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1628); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1633); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1613); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1627); + + + + -var CanceledError = __webpack_require__(1624); /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. + * The Sentry Node SDK Client. * - * @class - * @param {Function} executor The executor function. + * @see NodeClientOptions for documentation on configuration options. + * @see SentryClient for usage documentation. */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } - - var resolvePromise; +class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); + /** + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. + */ + constructor(options) { + options._metadata = options._metadata || {}; + options._metadata.sdk = options._metadata.sdk || { + name: 'sentry.javascript.node', + packages: [ + { + name: 'npm:@sentry/node', + version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, + }, + ], + version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, + }; - var token = this; + // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util + options.transportOptions = { + textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), + ...options.transportOptions, + }; - // eslint-disable-next-line func-names - this.promise.then(function(cancel) { - if (!token._listeners) return; + super(options); + } - var i; - var l = token._listeners.length; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const requestSession = scope.getRequestSession(); - for (i = 0; i < l; i++) { - token._listeners[i](cancel); + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } } - token._listeners = null; - }); - // eslint-disable-next-line func-names - this.promise.then = function(onfulfilled) { - var _resolve; - // eslint-disable-next-line func-names - var promise = new Promise(function(resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); + return super.captureException(exception, hint, scope); + } - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; + /** + * @inheritDoc + */ + captureEvent(event, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const eventType = event.type || 'exception'; + const isException = + eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - return promise; - }; + // If the event is of type Exception, then a request session should be captured + if (isException) { + const requestSession = scope.getRequestSession(); - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } + } } - token.reason = new CanceledError(message); - resolvePromise(token.reason); - }); -} - -/** - * Throws a `CanceledError` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; + return super.captureEvent(event, hint, scope); } -}; -/** - * Subscribe to the cancel signal - */ + /** + * + * @inheritdoc + */ + close(timeout) { + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); + return super.close(timeout); + } -CancelToken.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; + /** Method that initialises an instance of SessionFlusher on Client */ + initSessionFlusher() { + const { release, environment } = this._options; + if (!release) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } else { + this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { + release, + environment, + }); + } } - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + eventFromException(exception, hint) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); } -}; -/** - * Unsubscribe from the cancel signal - */ - -CancelToken.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; - } - var index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); + /** + * @inheritDoc + */ + eventFromMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + ) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( + (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), + ); } -}; - -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; - -module.exports = CancelToken; - - -/***/ }), -/* 1637 */ -/***/ ((module) => { - -"use strict"; - - -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * @returns {Function} - */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -}; - - -/***/ }), -/* 1638 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; + /** + * @inheritDoc + */ + _prepareEvent(event, hint, scope) { + event.platform = event.platform || 'node'; + event.contexts = { + ...event.contexts, + runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { + name: 'node', + version: global.process.version, + }, + }; + event.server_name = + event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); + return super._prepareEvent(event, hint, scope); + } + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + _captureRequestSession() { + if (!this._sessionFlusher) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } else { + this._sessionFlusher.incrementSessionStatusCount(); + } + } +} -var utils = __webpack_require__(1604); -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -module.exports = function isAxiosError(payload) { - return utils.isObject(payload) && (payload.isAxiosError === true); -}; +//# sourceMappingURL=client.js.map /***/ }), -/* 1639 */ +/* 1627 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), -/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), -/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), -/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), -/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), -/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), -/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), -/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), -/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), -/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), -/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), -/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), -/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), -/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), -/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), -/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), -/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), -/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), -/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), -/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), -/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), -/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), -/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), -/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), -/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), -/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), -/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), -/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), -/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), -/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) +/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), +/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), +/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), +/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1718); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1654); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1641); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1655); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1656); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1665); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1673); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1689); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1705); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1714); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1715); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1690); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1674); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1621); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1608); +/** + * Extracts stack frames from the error.stack string + */ +function parseStackFrames(stackParser, error) { + return stackParser(error.stack || '', 1); +} +/** + * Extracts stack frames from the error and builds a Sentry Exception + */ +function exceptionFromError(stackParser, error) { + const exception = { + type: error.name || error.constructor.name, + value: error.message, + }; + const frames = parseStackFrames(stackParser, error); + if (frames.length) { + exception.stacktrace = { frames }; + } + return exception; +} +/** + * Builds and Event from a Exception + * @hidden + */ +function eventFromUnknownInput(stackParser, exception, hint) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let ex = exception; + const providedMechanism = + hint && hint.data && (hint.data ).mechanism; + const mechanism = providedMechanism || { + handled: true, + type: 'generic', + }; + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(exception)) { + // This will allow us to group events based on top-level keys + // which is much better than creating new group when any key/value change + const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); + const client = hub.getClient(); + const normalizeDepth = client && client.getOptions().normalizeDepth; + hub.configureScope(scope => { + scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); + }); + ex = (hint && hint.syntheticException) || new Error(message); + (ex ).message = message; + } else { + // This handles when someone does: `throw "something awesome";` + // We use synthesized Error here so we can extract a (rough) stack trace. + ex = (hint && hint.syntheticException) || new Error(exception ); + (ex ).message = exception ; + } + mechanism.synthetic = true; + } + const event = { + exception: { + values: [exceptionFromError(stackParser, ex )], + }, + }; + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); -; -; + return { + ...event, + event_id: hint && hint.event_id, + }; +} -; -; +/** + * Builds and Event from a Message + * @hidden + */ +function eventFromMessage( + stackParser, + message, + // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + attachStacktrace, +) { + const event = { + event_id: hint && hint.event_id, + level, + message, + }; -const INTEGRATIONS = { - ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, - ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, -}; + if (attachStacktrace && hint && hint.syntheticException) { + const frames = parseStackFrames(stackParser, hint.syntheticException); + if (frames.length) { + event.exception = { + values: [ + { + value: message, + stacktrace: { frames }, + }, + ], + }; + } + } -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; + return event; } -//# sourceMappingURL=index.js.map +//# sourceMappingURL=eventbuilder.js.map /***/ }), -/* 1640 */ +/* 1628 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), -/* harmony export */ "Hub": () => (/* binding */ Hub), -/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), -/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), -/* harmony export */ "makeMain": () => (/* binding */ makeMain), -/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) +/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1644); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1645); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1641); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1642); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1629); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1621); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1609); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1619); +/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1630); +/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1632); +/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1631); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1602); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1603); -const NIL_EVENT_ID = '00000000000000000000000000000000'; -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -const API_VERSION = 4; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -const DEFAULT_BREADCRUMBS = 100; -/** - * A layer in the process stack. - * @hidden - */ +const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; /** - * @inheritDoc + * Base implementation for all JavaScript SDK clients. + * + * Call the constructor with the corresponding options + * specific to the client subclass. To access these options later, use + * {@link Client.getOptions}. + * + * If a Dsn is specified in the options, it will be parsed and stored. Use + * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is + * invalid, the constructor will throw a {@link SentryException}. Note that + * without a valid Dsn, the SDK will not send any events to Sentry. + * + * Before sending an event, it is passed through + * {@link BaseClient._prepareEvent} to add SDK information and scope data + * (breadcrumbs and context). To add more custom information, override this + * method and extend the resulting prepared event. + * + * To issue automatically created events (e.g. via instrumentation), use + * {@link Client.captureEvent}. It will prepare the event and pass it through + * the callback lifecycle. To issue auto-breadcrumbs, use + * {@link Client.addBreadcrumb}. + * + * @example + * class NodeClient extends BaseClient<NodeOptions> { + * public constructor(options: NodeOptions) { + * super(options); + * } + * + * // ... + * } */ -class Hub { - /** Is a {@link Layer}[] containing the client and scope */ - __init() {this._stack = [{}];} - - /** Contains the last event id of a captured event. */ +class BaseClient { + /** Options passed to the SDK. */ - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); - this.getStackTop().scope = scope; - if (client) { - this.bindClient(client); - } - } + /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ - /** - * @inheritDoc - */ - isOlderThan(version) { - return this._version < version; - } + /** Array of set up integrations. */ + __init() {this._integrations = {};} - /** - * @inheritDoc - */ - bindClient(client) { - const top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - } + /** Indicates whether this client's integrations have been set up. */ + __init2() {this._integrationsInitialized = false;} - /** - * @inheritDoc - */ - pushScope() { - // We want to clone the content of prev scope - const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope, - }); - return scope; - } + /** Number of calls being processed */ + __init3() {this._numProcessing = 0;} - /** - * @inheritDoc - */ - popScope() { - if (this.getStack().length <= 1) return false; - return !!this.getStack().pop(); - } + /** Holds flushable */ + __init4() {this._outcomes = {};} /** - * @inheritDoc + * Initializes this client instance. + * + * @param options Options for the client. */ - withScope(callback) { - const scope = this.pushScope(); - try { - callback(scope); - } finally { - this.popScope(); + constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); + this._options = options; + if (options.dsn) { + this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); + const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); + this._transport = options.transport({ + recordDroppedEvent: this.recordDroppedEvent.bind(this), + ...options.transportOptions, + url, + }); + } else { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); } } /** * @inheritDoc */ - getClient() { - return this.getStackTop().client ; - } - - /** Returns the scope of the top stack. */ - getScope() { - return this.getStackTop().scope; - } - - /** Returns the scope stack for domains or the process. */ - getStack() { - return this._stack; - } + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // ensure we haven't captured this very object before + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); + return; + } - /** Returns the topmost scope layer in the order domain > local > process. */ - getStackTop() { - return this._stack[this._stack.length - 1]; - } + let eventId; + this._process( + this.eventFromException(exception, hint) + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint) { - const syntheticException = new Error('Sentry syntheticException'); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureException( - exception, - { - originalException: exception, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; + return eventId; } /** @@ -233986,153 +234275,136 @@ class Hub { // eslint-disable-next-line deprecation/deprecation level, hint, + scope, ) { - const syntheticException = new Error(message); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureMessage( - message, - level, - { - originalException: message, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - - /** - * @inheritDoc - */ - captureEvent(event, hint) { - const clientId = - this._withClient((client, scope) => { - return client.captureEvent(event, { ...hint }, scope); - }) || NIL_EVENT_ID; + let eventId; - if (event.type !== 'transaction') { - this._lastEventId = clientId; - } + const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) + ? this.eventFromMessage(String(message), level, hint) + : this.eventFromException(message, hint); - return clientId; - } + this._process( + promisedEvent + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); - /** - * @inheritDoc - */ - lastEventId() { - return this._lastEventId; + return eventId; } /** * @inheritDoc */ - addBreadcrumb(breadcrumb, hint) { - const { scope, client } = this.getStackTop(); - - if (!scope || !client) return; - - // eslint-disable-next-line @typescript-eslint/unbound-method - const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = - (client.getOptions && client.getOptions()) || {}; - - if (maxBreadcrumbs <= 0) return; + captureEvent(event, hint, scope) { + // ensure we haven't captured this very object before + if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); + return; + } - const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); - const mergedBreadcrumb = { timestamp, ...breadcrumb }; - const finalBreadcrumb = beforeBreadcrumb - ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) - : mergedBreadcrumb; + let eventId; - if (finalBreadcrumb === null) return; + this._process( + this._captureEvent(event, hint, scope).then(result => { + eventId = result; + }), + ); - scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); + return eventId; } /** * @inheritDoc */ - setUser(user) { - const scope = this.getScope(); - if (scope) scope.setUser(user); + captureSession(session) { + if (!this._isEnabled()) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); + return; + } + + if (!(typeof session.release === 'string')) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); + } else { + this.sendSession(session); + // After sending, we set init false to indicate it's not the first occurrence + (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); + } } /** * @inheritDoc */ - setTags(tags) { - const scope = this.getScope(); - if (scope) scope.setTags(tags); + getDsn() { + return this._dsn; } /** * @inheritDoc */ - setExtras(extras) { - const scope = this.getScope(); - if (scope) scope.setExtras(extras); + getOptions() { + return this._options; } /** * @inheritDoc */ - setTag(key, value) { - const scope = this.getScope(); - if (scope) scope.setTag(key, value); + getTransport() { + return this._transport; } /** * @inheritDoc */ - setExtra(key, extra) { - const scope = this.getScope(); - if (scope) scope.setExtra(key, extra); + flush(timeout) { + const transport = this._transport; + if (transport) { + return this._isClientDoneProcessing(timeout).then(clientFinished => { + return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); + }); + } else { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); + } } /** * @inheritDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setContext(name, context) { - const scope = this.getScope(); - if (scope) scope.setContext(name, context); + close(timeout) { + return this.flush(timeout).then(result => { + this.getOptions().enabled = false; + return result; + }); } /** - * @inheritDoc + * Sets up the integrations */ - configureScope(callback) { - const { scope, client } = this.getStackTop(); - if (scope && client) { - callback(scope); + setupIntegrations() { + if (this._isEnabled() && !this._integrationsInitialized) { + this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); + this._integrationsInitialized = true; } } /** - * @inheritDoc + * Gets an installed integration by its `id`. + * + * @returns The installed integration or `undefined` if no integration with that `id` was installed. */ - run(callback) { - const oldHub = makeMain(this); - try { - callback(this); - } finally { - makeMain(oldHub); - } + getIntegrationById(integrationId) { + return this._integrations[integrationId]; } /** * @inheritDoc */ getIntegration(integration) { - const client = this.getClient(); - if (!client) return null; try { - return client.getIntegration(integration); + return (this._integrations[integration.id] ) || null; } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); return null; } } @@ -234140,12809 +234412,12605 @@ class Hub { /** * @inheritDoc */ - startTransaction(context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - } + sendEvent(event, hint = {}) { + if (this._dsn) { + let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); - /** - * @inheritDoc - */ - traceHeaders() { - return this._callExtensionMethod('traceHeaders'); + for (const attachment of hint.attachments || []) { + env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( + env, + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( + attachment, + this._options.transportOptions && this._options.transportOptions.textEncoder, + ), + ); + } + + this._sendEnvelope(env); + } } /** * @inheritDoc */ - captureSession(endSession = false) { - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); + sendSession(session) { + if (this._dsn) { + const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); + this._sendEnvelope(env); } - - // only send the update - this._sendSessionUpdate(); } /** * @inheritDoc */ - endSession() { - const layer = this.getStackTop(); - const scope = layer && layer.scope; - const session = scope && scope.getSession(); - if (session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); - } - this._sendSessionUpdate(); + recordDroppedEvent(reason, category, _event) { + // Note: we use `event` in replay, where we overwrite this hook. - // the session is over; take it off of the scope - if (scope) { - scope.setSession(); + if (this._options.sendClientReports) { + // We want to track each category (error, transaction, session) separately + // but still keep the distinction between different type of outcomes. + // We could use nested maps, but it's much easier to read and type this way. + // A correct type for map-based implementation if we want to go that route + // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` + // With typescript 4.1 we could even use template literal types + const key = `${reason}:${category}`; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); + + // The following works because undefined + 1 === NaN and NaN is falsy + this._outcomes[key] = this._outcomes[key] + 1 || 1; } } - /** - * @inheritDoc - */ - startSession(context) { - const { scope, client } = this.getStackTop(); - const { release, environment } = (client && client.getOptions()) || {}; - - // Will fetch userAgent if called from browser sdk - const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; + /** Updates existing session based on the provided event */ + _updateSessionFromEvent(session, event) { + let crashed = false; + let errored = false; + const exceptions = event.exception && event.exception.values; - const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ - release, - environment, - ...(scope && { user: scope.getUser() }), - ...(userAgent && { userAgent }), - ...context, - }); + if (exceptions) { + errored = true; - if (scope) { - // End existing session if there's one - const currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === 'ok') { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); + for (const ex of exceptions) { + const mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } } - this.endSession(); - - // Afterwards we set the new session on the scope - scope.setSession(session); } - return session; + // A session is updated and that session update is sent in only one of the two following scenarios: + // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update + // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update + const sessionNonTerminal = session.status === 'ok'; + const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); + + if (shouldUpdateAndSend) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { + ...(crashed && { status: 'crashed' }), + errors: session.errors || Number(errored || crashed), + }); + this.captureSession(session); + } } /** - * Returns if default PII should be sent to Sentry and propagated in ourgoing requests - * when Tracing is used. + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise */ - shouldSendDefaultPii() { - const client = this.getClient(); - const options = client && client.getOptions(); - return Boolean(options && options.sendDefaultPii); + _isClientDoneProcessing(timeout) { + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { + let ticked = 0; + const tick = 1; + + const interval = setInterval(() => { + if (this._numProcessing == 0) { + clearInterval(interval); + resolve(true); + } else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } + } + }, tick); + }); + } + + /** Determines whether this SDK is enabled and a valid Dsn is present. */ + _isEnabled() { + return this.getOptions().enabled !== false && this._dsn !== undefined; } /** - * Sends the current Session on the scope + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. */ - _sendSessionUpdate() { - const { scope, client } = this.getStackTop(); - if (!scope) return; + _prepareEvent(event, hint, scope) { + const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); + const prepared = { + ...event, + event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), + timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.dateTimestampInSeconds)(), + }; - const session = scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); + this._applyClientOptions(prepared); + this._applyIntegrationsMetadata(prepared); + + // If we have scope given to us, use it as the base for further modifications. + // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. + let finalScope = scope; + if (hint.captureContext) { + finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); + } + + // We prepare the result here with a resolved Event. + let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); + + // This should be the last thing called, since we want that + // {@link Hub.addEventProcessor} gets the finished prepared event. + // + // We need to check for the existence of `finalScope.getAttachments` + // because `getAttachments` can be undefined if users are using an older version + // of `@sentry/core` that does not have the `getAttachments` method. + // See: https://github.com/getsentry/sentry-javascript/issues/5229 + if (finalScope && finalScope.getAttachments) { + // Collect attachments from the hint and scope + const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; + + if (attachments.length) { + hint.attachments = attachments; } + + // In case we have a hub we reassign it. + result = finalScope.applyToEvent(prepared, hint); } - } - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - _withClient(callback) { - const { scope, client } = this.getStackTop(); - return client && callback(client, scope); + return result.then(evt => { + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); + } + return evt; + }); } /** - * Calls global extension method and binding current instance to the function call + * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. + * Normalized keys: + * - `breadcrumbs.data` + * - `user` + * - `contexts` + * - `extra` + * @param event Event + * @returns Normalized event */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _callExtensionMethod(method, ...args) { - const carrier = getMainCarrier(); - const sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); + _normalizeEvent(event, depth, maxBreadth) { + if (!event) { + return null; } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); - } -} -/** - * Returns the global shim registry. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -function getMainCarrier() { - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; -} + const normalized = { + ...event, + ...(event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map(b => ({ + ...b, + ...(b.data && { + data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), + }), + })), + }), + ...(event.user && { + user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), + }), + ...(event.contexts && { + contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), + }), + ...(event.extra && { + extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), + }), + }; -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - const registry = getMainCarrier(); - const oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} + // event.contexts.trace stores information about a Transaction. Similarly, + // event.spans[] stores information about child Spans. Given that a + // Transaction is conceptually a Span, normalization should apply to both + // Transactions and Spans consistently. + // For now the decision is to skip normalization of Transactions and Spans, + // so this block overwrites the normalized event to add back the original + // Transaction information prior to normalization. + if (event.contexts && event.contexts.trace && normalized.contexts) { + normalized.contexts.trace = event.contexts.trace; -/** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. - */ -function getCurrentHub() { - // Get main carrier (global for every environment) - const registry = getMainCarrier(); + // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it + if (event.contexts.trace.data) { + normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); + } + } - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { - setHubOnCarrier(registry, new Hub()); - } + // event.spans[].data may contain circular/dangerous data so we need to normalize it + if (event.spans) { + normalized.spans = event.spans.map(span => { + // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable + if (span.data) { + span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); + } + return span; + }); + } - // Prefer domains over global if they are there (applicable only to Node environment) - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { - return getHubFromActiveDomain(registry); + return normalized; } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - const sentry = getMainCarrier().__SENTRY__; - const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; + /** + * Enhances event using the client configuration. + * It takes care of all "static" values like environment, release and `dist`, + * as well as truncating overly long values. + * @param event event instance to be enhanced + */ + _applyClientOptions(event) { + const options = this.getOptions(); + const { environment, release, dist, maxValueLength = 250 } = options; - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); + if (!('environment' in event)) { + event.environment = 'environment' in options ? environment : 'production'; } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { - const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(registryHubTopStack.scope))); + if (event.release === undefined && release !== undefined) { + event.release = release; } - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); - } -} - -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); -} + if (event.dist === undefined && dist !== undefined) { + event.dist = dist; + } -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); -} + if (event.message) { + event.message = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); + } -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - * @returns A boolean indicating success or failure - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) return false; - const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); - __SENTRY__.hub = hub; - return true; -} - - -//# sourceMappingURL=hub.js.map - - -/***/ }), -/* 1641 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Scope": () => (/* binding */ Scope), -/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1644); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1642); - - - -/** - * Default value for maximum number of breadcrumbs added to an event. - */ -const DEFAULT_MAX_BREADCRUMBS = 100; - -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -class Scope { - /** Flag if notifying is happening. */ - - /** Callback for client to receive scope changes. */ - - /** Callback list that will be called after {@link applyToEvent}. */ - - /** Array of breadcrumbs. */ - - /** User */ - - /** Tags */ - - /** Extra */ - - /** Contexts */ - - /** Attachments */ - - /** - * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get - * sent to Sentry - */ - - /** Fingerprint */ - - /** Severity */ - // eslint-disable-next-line deprecation/deprecation - - /** Transaction Name */ - - /** Span */ - - /** Session */ - - /** Request Mode Session Status */ - - // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. + const exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); + } - constructor() { - this._notifyingListeners = false; - this._scopeListeners = []; - this._eventProcessors = []; - this._breadcrumbs = []; - this._attachments = []; - this._user = {}; - this._tags = {}; - this._extra = {}; - this._contexts = {}; - this._sdkProcessingMetadata = {}; + const request = event.request; + if (request && request.url) { + request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); + } } /** - * Inherit values from the parent scope. - * @param scope to clone. + * This function adds all used integrations to the SDK info in the event. + * @param event The event that will be filled with all integrations. */ - static clone(scope) { - const newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = [...scope._breadcrumbs]; - newScope._tags = { ...scope._tags }; - newScope._extra = { ...scope._extra }; - newScope._contexts = { ...scope._contexts }; - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = [...scope._eventProcessors]; - newScope._requestSession = scope._requestSession; - newScope._attachments = [...scope._attachments]; - newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; + _applyIntegrationsMetadata(event) { + const integrationsArray = Object.keys(this._integrations); + if (integrationsArray.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; } - return newScope; } /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope */ - addScopeListener(callback) { - this._scopeListeners.push(callback); + _captureEvent(event, hint = {}, scope) { + return this._processEvent(event, hint, scope).then( + finalEvent => { + return finalEvent.event_id; + }, + reason => { + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for + // control flow, log just the message (no stack) as a log-level log. + const sentryError = reason ; + if (sentryError.logLevel === 'log') { + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); + } else { + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); + } + } + return undefined; + }, + ); } /** - * @inheritDoc + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. */ - addEventProcessor(callback) { - this._eventProcessors.push(callback); - return this; - } + _processEvent(event, hint, scope) { + const options = this.getOptions(); + const { sampleRate } = options; - /** - * @inheritDoc - */ - setUser(user) { - this._user = user || {}; - if (this._session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); + if (!this._isEnabled()) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); } - this._notifyScopeListeners(); - return this; - } - /** - * @inheritDoc - */ - getUser() { - return this._user; - } + const isTransaction = event.type === 'transaction'; + const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; + const beforeSendProcessor = options[beforeSendProcessorName]; - /** - * @inheritDoc - */ - getRequestSession() { - return this._requestSession; - } + // 1.0 === 100% events are sent + // 0.0 === 0% events are sent + // Sampling for transaction happens somewhere else + if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { + this.recordDroppedEvent('sample_rate', 'error', event); + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( + new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( + `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, + 'log', + ), + ); + } - /** - * @inheritDoc - */ - setRequestSession(requestSession) { - this._requestSession = requestSession; - return this; - } + return this._prepareEvent(event, hint, scope) + .then(prepared => { + if (prepared === null) { + this.recordDroppedEvent('event_processor', event.type || 'error', event); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); + } - /** - * @inheritDoc - */ - setTags(tags) { - this._tags = { - ...this._tags, - ...tags, - }; - this._notifyScopeListeners(); - return this; - } + const isInternalException = hint.data && (hint.data ).__sentry__ === true; + if (isInternalException || !beforeSendProcessor) { + return prepared; + } - /** - * @inheritDoc - */ - setTag(key, value) { - this._tags = { ...this._tags, [key]: value }; - this._notifyScopeListeners(); - return this; - } + const beforeSendResult = beforeSendProcessor(prepared, hint); + return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); + }) + .then(processedEvent => { + if (processedEvent === null) { + this.recordDroppedEvent('before_send', event.type || 'error', event); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); + } - /** - * @inheritDoc - */ - setExtras(extras) { - this._extra = { - ...this._extra, - ...extras, - }; - this._notifyScopeListeners(); - return this; - } + const session = scope && scope.getSession(); + if (!isTransaction && session) { + this._updateSessionFromEvent(session, processedEvent); + } - /** - * @inheritDoc - */ - setExtra(key, extra) { - this._extra = { ...this._extra, [key]: extra }; - this._notifyScopeListeners(); - return this; - } + // None of the Sentry built event processor will update transaction name, + // so if the transaction name has been changed by an event processor, we know + // it has to come from custom event processor added by a user + const transactionInfo = processedEvent.transaction_info; + if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { + const source = 'custom'; + processedEvent.transaction_info = { + ...transactionInfo, + source, + changes: [ + ...transactionInfo.changes, + { + source, + // use the same timestamp as the processed event. + timestamp: processedEvent.timestamp , + propagations: transactionInfo.propagations, + }, + ], + }; + } - /** - * @inheritDoc - */ - setFingerprint(fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - } + this.sendEvent(processedEvent, hint); + return processedEvent; + }) + .then(null, reason => { + if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { + throw reason; + } - /** - * @inheritDoc - */ - setLevel( - // eslint-disable-next-line deprecation/deprecation - level, - ) { - this._level = level; - this._notifyScopeListeners(); - return this; + this.captureException(reason, { + data: { + __sentry__: true, + }, + originalException: reason , + }); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( + `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, + ); + }); } /** - * @inheritDoc + * Occupies the client with processing and event */ - setTransactionName(name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; + _process(promise) { + this._numProcessing++; + void promise.then( + value => { + this._numProcessing--; + return value; + }, + reason => { + this._numProcessing--; + return reason; + }, + ); } /** - * @inheritDoc + * @inheritdoc */ - setContext(key, context) { - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; + _sendEnvelope(envelope) { + if (this._transport && this._dsn) { + this._transport.send(envelope).then(null, reason => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); + }); } else { - this._contexts[key] = context; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); } - - this._notifyScopeListeners(); - return this; - } - - /** - * @inheritDoc - */ - setSpan(span) { - this._span = span; - this._notifyScopeListeners(); - return this; } /** - * @inheritDoc + * Clears outcomes on this client and returns them. */ - getSpan() { - return this._span; + _clearOutcomes() { + const outcomes = this._outcomes; + this._outcomes = {}; + return Object.keys(outcomes).map(key => { + const [reason, category] = key.split(':') ; + return { + reason, + category, + quantity: outcomes[key], + }; + }); } /** * @inheritDoc */ - getTransaction() { - // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will - // have a pointer to the currently-active transaction. - const span = this.getSpan(); - return span && span.transaction; - } + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - /** - * @inheritDoc - */ - setSession(session) { - if (!session) { - delete this._session; - } else { - this._session = session; - } - this._notifyScopeListeners(); - return this; - } +} - /** - * @inheritDoc - */ - getSession() { - return this._session; +/** + * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. + */ +function _validateBeforeSendResult( + beforeSendResult, + beforeSendProcessorName, +) { + const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { + return beforeSendResult.then( + event => { + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); + } + return event; + }, + e => { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); + }, + ); + } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); } + return beforeSendResult; +} - /** - * @inheritDoc - */ - update(captureContext) { - if (!captureContext) { - return this; - } - if (typeof captureContext === 'function') { - const updatedScope = (captureContext )(this); - return updatedScope instanceof Scope ? updatedScope : this; - } +//# sourceMappingURL=baseclient.js.map - if (captureContext instanceof Scope) { - this._tags = { ...this._tags, ...captureContext._tags }; - this._extra = { ...this._extra, ...captureContext._extra }; - this._contexts = { ...this._contexts, ...captureContext._contexts }; - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; - } - if (captureContext._level) { - this._level = captureContext._level; - } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext ; - this._tags = { ...this._tags, ...captureContext.tags }; - this._extra = { ...this._extra, ...captureContext.extra }; - this._contexts = { ...this._contexts, ...captureContext.contexts }; - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } - } - return this; - } +/***/ }), +/* 1629 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - clear() { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - this._attachments = []; - return this; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), +/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), +/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) +/* harmony export */ }); +/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1619); - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, maxBreadcrumbs) { - const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; - } +/** Regular expression used to parse a Dsn. */ +const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; - const mergedBreadcrumb = { - timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), - ...breadcrumb, - }; - this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); - this._notifyScopeListeners(); +function isValidProtocol(protocol) { + return protocol === 'http' || protocol === 'https'; +} - return this; - } +/** + * Renders the string representation of this Dsn. + * + * By default, this will render the public representation without the password + * component. To get the deprecated private representation, set `withPassword` + * to true. + * + * @param withPassword When set to true, the password will be included. + */ +function dsnToString(dsn, withPassword = false) { + const { host, path, pass, port, projectId, protocol, publicKey } = dsn; + return ( + `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + + `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` + ); +} - /** - * @inheritDoc - */ - clearBreadcrumbs() { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - } +/** + * Parses a Dsn from a given string. + * + * @param str A Dsn as string + * @returns Dsn as DsnComponents + */ +function dsnFromString(str) { + const match = DSN_REGEX.exec(str); - /** - * @inheritDoc - */ - addAttachment(attachment) { - this._attachments.push(attachment); - return this; + if (!match) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); } - /** - * @inheritDoc - */ - getAttachments() { - return this._attachments; - } + const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); + let path = ''; + let projectId = lastPath; - /** - * @inheritDoc - */ - clearAttachments() { - this._attachments = []; - return this; + const split = projectId.split('/'); + if (split.length > 1) { + path = split.slice(0, -1).join('/'); + projectId = split.pop() ; } - /** - * Applies data from the scope to the event and runs all event processors on it. - * - * @param event Event - * @param hint Object containing additional information about the original exception, for use by the event processors. - * @hidden - */ - applyToEvent(event, hint = {}) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = { ...this._extra, ...event.extra }; - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = { ...this._tags, ...event.tags }; - } - if (this._user && Object.keys(this._user).length) { - event.user = { ...this._user, ...event.user }; - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = { ...this._contexts, ...event.contexts }; - } - if (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; - } - - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relies on that. - if (this._span) { - event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; - const transactionName = this._span.transaction && this._span.transaction.name; - if (transactionName) { - event.tags = { transaction: transactionName, ...event.tags }; - } + if (projectId) { + const projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; } - - this._applyFingerprint(event); - - event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - - event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; - - return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); } - /** - * Add data which will be accessible during event processing but won't get sent to Sentry - */ - setSDKProcessingMetadata(newData) { - this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; + return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); +} - return this; +function dsnFromComponents(components) { + return { + protocol: components.protocol, + publicKey: components.publicKey || '', + pass: components.pass || '', + host: components.host, + port: components.port || '', + path: components.path || '', + projectId: components.projectId, + }; +} + +function validateDsn(dsn) { + if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + return; } - /** - * This will be called after {@link applyToEvent} is finished. - */ - _notifyEventProcessors( - processors, - event, - hint, - index = 0, - ) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { - const processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } else { - const result = processor({ ...event }, hint) ; + const { port, projectId, protocol } = dsn; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - processor.id && - result === null && - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); + const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; + requiredComponents.forEach(component => { + if (!dsn[component]) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); + } + }); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { - void result - .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) - .then(null, reject); - } else { - void this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); + if (!projectId.match(/^\d+$/)) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); } - /** - * This will be called on every set call. - */ - _notifyScopeListeners() { - // We need this check for this._notifyingListeners to be able to work on scope during updates - // If this check is not here we'll produce endless recursion when something is done with the scope - // during the callback. - if (!this._notifyingListeners) { - this._notifyingListeners = true; - this._scopeListeners.forEach(callback => { - callback(this); - }); - this._notifyingListeners = false; - } + if (!isValidProtocol(protocol)) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); } - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - _applyFingerprint(event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(event.fingerprint) : []; - - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); - } - - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; - } + if (port && isNaN(parseInt(port, 10))) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); } -} -/** - * Returns the global event processors. - */ -function getGlobalEventProcessors() { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); + return true; } -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); +/** The Sentry Dsn, identifying a Sentry instance and project. */ +function makeDsn(from) { + const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); + validateDsn(components); + return components; } -//# sourceMappingURL=scope.js.map +//# sourceMappingURL=dsn.js.map /***/ }), -/* 1642 */ +/* 1630 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "closeSession": () => (/* binding */ closeSession), -/* harmony export */ "makeSession": () => (/* binding */ makeSession), -/* harmony export */ "updateSession": () => (/* binding */ updateSession) +/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), +/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1629); -/** - * Creates a new `Session` object by setting certain default parameters. If optional @param context - * is passed, the passed properties are applied to the session object. - * - * @param context (optional) additional properties to be applied to the returned session object - * - * @returns a new `Session` object - */ -function makeSession(context) { - // Both timestamp and started are in seconds since the UNIX epoch. - const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); +const SENTRY_API_VERSION = '7'; - const session = { - sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), - init: true, - timestamp: startingTime, - started: startingTime, - duration: 0, - status: 'ok', - errors: 0, - ignoreDuration: false, - toJSON: () => sessionToJSON(session), - }; +/** Returns the prefix to construct Sentry ingestion API endpoints. */ +function getBaseApiEndpoint(dsn) { + const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; + const port = dsn.port ? `:${dsn.port}` : ''; + return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; +} - if (context) { - updateSession(session, context); - } +/** Returns the ingest API endpoint for target. */ +function _getIngestEndpoint(dsn) { + return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; +} - return session; +/** Returns a URL-encoded string with auth config suitable for a query string. */ +function _encodedAuth(dsn, sdkInfo) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.publicKey, + sentry_version: SENTRY_API_VERSION, + ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), + }); } /** - * Updates a session object with the properties passed in the context. - * - * Note that this function mutates the passed object and returns void. - * (Had to do this instead of returning a new and updated session because closing and sending a session - * makes an update to the session after it was passed to the sending logic. - * @see BaseClient.captureSession ) + * Returns the envelope endpoint URL with auth in the query string. * - * @param session the `Session` to update - * @param context the `SessionContext` holding the properties that should be updated in @param session + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. */ -// eslint-disable-next-line complexity -function updateSession(session, context = {}) { - if (context.user) { - if (!session.ipAddress && context.user.ip_address) { - session.ipAddress = context.user.ip_address; - } - - if (!session.did && !context.did) { - session.did = context.user.id || context.user.email || context.user.username; - } - } +function getEnvelopeEndpointWithUrlEncodedAuth( + dsn, + // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below + // options: ClientOptions = {} as ClientOptions, + tunnelOrOptions = {} , +) { + // TODO (v8): Use this code instead + // const { tunnel, _metadata = {} } = options; + // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; - session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); + const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; + const sdkInfo = + typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; - if (context.ignoreDuration) { - session.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); - } - if (context.init !== undefined) { - session.init = context.init; - } - if (!session.did && context.did) { - session.did = `${context.did}`; - } - if (typeof context.started === 'number') { - session.started = context.started; - } - if (session.ignoreDuration) { - session.duration = undefined; - } else if (typeof context.duration === 'number') { - session.duration = context.duration; - } else { - const duration = session.timestamp - session.started; - session.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - session.release = context.release; - } - if (context.environment) { - session.environment = context.environment; - } - if (!session.ipAddress && context.ipAddress) { - session.ipAddress = context.ipAddress; - } - if (!session.userAgent && context.userAgent) { - session.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - session.errors = context.errors; - } - if (context.status) { - session.status = context.status; - } + return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; } -/** - * Closes a session by setting its status and updating the session object with it. - * Internally calls `updateSession` to update the passed session object. - * - * Note that this function mutates the passed session (@see updateSession for explanation). - * - * @param session the `Session` object to be closed - * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, - * this function will keep the previously set status, unless it was `'ok'` in which case - * it is changed to `'exited'`. - */ -function closeSession(session, status) { - let context = {}; - if (status) { - context = { status }; - } else if (session.status === 'ok') { - context = { status: 'exited' }; - } +/** Returns the url to the report dialog endpoint. */ +function getReportDialogEndpoint( + dsnLike, + dialogOptions - updateSession(session, context); -} +, +) { + const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); + const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; -/** - * Serializes a passed session object to a JSON object with a slightly different structure. - * This is necessary because the Sentry backend requires a slightly different schema of a session - * than the one the JS SDKs use internally. - * - * @param session the session to be converted - * - * @returns a JSON object of the passed session - */ -function sessionToJSON(session) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ - sid: `${session.sid}`, - init: session.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(session.started * 1000).toISOString(), - timestamp: new Date(session.timestamp * 1000).toISOString(), - status: session.status, - errors: session.errors, - did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, - duration: session.duration, - attrs: { - release: session.release, - environment: session.environment, - ip_address: session.ipAddress, - user_agent: session.userAgent, - }, - }); + let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; + for (const key in dialogOptions) { + if (key === 'dsn') { + continue; + } + + if (key === 'user') { + const user = dialogOptions.user; + if (!user) { + continue; + } + if (user.name) { + encodedOptions += `&name=${encodeURIComponent(user.name)}`; + } + if (user.email) { + encodedOptions += `&email=${encodeURIComponent(user.email)}`; + } + } else { + encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; + } + } + + return `${endpoint}?${encodedOptions}`; } -//# sourceMappingURL=session.js.map +//# sourceMappingURL=api.js.map /***/ }), -/* 1643 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { +/* 1631 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), -/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), -/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), -/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), -/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), -/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) +/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), +/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), +/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) /* harmony export */ }); -/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1645); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); -/* module decorator */ module = __webpack_require__.hmd(module); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1601); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); -/** - * An object that can return the current timestamp in seconds since the UNIX epoch. - */ +const installedIntegrations = []; + +/** Map of integrations assigned to a client */ /** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. + * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to + * preseve the order of integrations in the array. * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + * @private */ -const dateTimestampSource = { - nowSeconds: () => Date.now() / 1000, -}; +function filterDuplicates(integrations) { + const integrationsByName = {}; -/** - * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} - * for accessing a high-resolution monotonic clock. - */ + integrations.forEach(currentInstance => { + const { name } = currentInstance; -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - const { performance } = WINDOW; - if (!performance || !performance.now) { - return undefined; - } + const existingInstance = integrationsByName[name]; - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - const timeOrigin = Date.now() - performance.now(); + // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a + // default instance to overwrite an existing user instance + if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { + return; + } - return { - now: () => performance.now(), - timeOrigin, - }; -} + integrationsByName[name] = currentInstance; + }); -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; - return perfHooks.performance; - } catch (_) { - return undefined; - } + return Object.values(integrationsByName); } -/** - * The Performance API implementation for the current platform, if available. - */ -const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); +/** Gets integrations to install */ +function getIntegrationsToSetup(options) { + const defaultIntegrations = options.defaultIntegrations || []; + const userIntegrations = options.integrations; -const timestampSource = - platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, - }; + // We flag default instances, so that later we can tell them apart from any user-created instances of the same class + defaultIntegrations.forEach(integration => { + integration.isDefaultInstance = true; + }); -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); + let integrations; -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); + if (Array.isArray(userIntegrations)) { + integrations = [...defaultIntegrations, ...userIntegrations]; + } else if (typeof userIntegrations === 'function') { + integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); + } else { + integrations = defaultIntegrations; + } -// Re-exported with an old name for backwards-compatibility. -const timestampWithMs = timestampInSeconds; + const finalIntegrations = filterDuplicates(integrations); -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -const usingPerformanceAPI = platformPerformance !== undefined; + // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or + // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event + // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore + // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. + const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); + if (debugIndex !== -1) { + const [debugInstance] = finalIntegrations.splice(debugIndex, 1); + finalIntegrations.push(debugInstance); + } -/** - * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. - */ -let _browserPerformanceTimeOriginMode; + return finalIntegrations; +} /** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations */ -const browserPerformanceTimeOrigin = (() => { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. - - const { performance } = WINDOW; - if (!performance || !performance.now) { - _browserPerformanceTimeOriginMode = 'none'; - return undefined; - } - - const threshold = 3600 * 1000; - const performanceNow = performance.now(); - const dateNow = Date.now(); - - // if timeOrigin isn't available set delta to threshold so it isn't used - const timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - const timeOriginIsReliable = timeOriginDelta < threshold; +function setupIntegrations(integrations) { + const integrationIndex = {}; - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - const navigationStart = performance.timing && performance.timing.navigationStart; - const hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - const navigationStartIsReliable = navigationStartDelta < threshold; + integrations.forEach(integration => { + integrationIndex[integration.name] = integration; - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - _browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } else { - _browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; + if (installedIntegrations.indexOf(integration.name) === -1) { + integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); + installedIntegrations.push(integration.name); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); } - } + }); - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - _browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); + return integrationIndex; +} -//# sourceMappingURL=time.js.map +//# sourceMappingURL=integration.js.map /***/ }), -/* 1644 */ +/* 1632 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), -/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), -/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) +/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), +/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) /* harmony export */ }); -/** Internal global with common properties and Sentry extensions */ +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1629); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); -// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification -// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js -// core-js has the following licence: -// -// Copyright (c) 2014-2022 Denis Pushkarev -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -/** Returns 'obj' if it's the global object, otherwise returns undefined */ -function isGlobalObj(obj) { - return obj && obj.Math == Math ? obj : undefined; +/** Extract sdk info from from the API metadata */ +function getSdkMetadataForEnvelopeHeader(metadata) { + if (!metadata || !metadata.sdk) { + return; + } + const { name, version } = metadata.sdk; + return { name, version }; } -/** Get's the global object for the current JavaScript runtime */ -const GLOBAL_OBJ = - (typeof globalThis == 'object' && isGlobalObj(globalThis)) || - // eslint-disable-next-line no-restricted-globals - (typeof window == 'object' && isGlobalObj(window)) || - (typeof self == 'object' && isGlobalObj(self)) || - (typeof global == 'object' && isGlobalObj(global)) || - (function () { - return this; - })() || - {}; - /** - * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 - */ -function getGlobalObject() { - return GLOBAL_OBJ ; + * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. + * Merge with existing data if any. + **/ +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; + } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; + event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; + return event; +} + +/** Creates an envelope from a Session */ +function createSessionEnvelope( + session, + dsn, + metadata, + tunnel, +) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const envelopeHeaders = { + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), + }; + + const envelopeItem = + 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; + + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); } /** - * Returns a global singleton contained in the global `__SENTRY__` object. - * - * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory - * function and added to the `__SENTRY__` object. - * - * @param name name of the global singleton on __SENTRY__ - * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` - * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value - * @returns the singleton + * Create an Envelope from an event. */ -function getGlobalSingleton(name, creator, obj) { - const gbl = (obj || GLOBAL_OBJ) ; - const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); - const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); - return singleton; +function createEventEnvelope( + event, + dsn, + metadata, + tunnel, +) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const eventType = event.type || 'event'; + + enhanceEventWithSdkInfo(event, metadata && metadata.sdk); + + const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); + + // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to + // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may + // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid + // of this `delete`, lest we miss putting it back in the next time the property is in use.) + delete event.sdkProcessingMetadata; + + const eventItem = [{ type: eventType }, event]; + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); +} + +function createEventEnvelopeHeaders( + event, + sdkInfo, + tunnel, + dsn, +) { + const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; + + return { + event_id: event.event_id , + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), + ...(event.type === 'transaction' && + dynamicSamplingContext && { + trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), + }), + }; } -//# sourceMappingURL=worldwide.js.map +//# sourceMappingURL=envelope.js.map /***/ }), -/* 1645 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { +/* 1633 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), -/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), -/* harmony export */ "loadModule": () => (/* binding */ loadModule) +/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) /* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1646); -/* module decorator */ module = __webpack_require__.hmd(module); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ /** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question + * @inheritdoc */ -function isNodeEnv() { - // explicitly check for browser bundles as those can be optimized statically - // by terser/rollup. - return ( - !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && - Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' - ); -} +class SessionFlusher { + __init() {this.flushTimeout = 60;} + __init2() {this._pendingAggregates = {};} -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} + __init3() {this._isEnabled = true;} -/** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. - * - * @param moduleName module name to require - * @returns possibly required module - */ -function loadModule(moduleName) { - let mod; + constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); + this._client = client; + // Call to setInterval, so that flush is called every 60 seconds + this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); + this._sessionAttrs = attrs; + } - try { - mod = dynamicRequire(module, moduleName); - } catch (e) { - // no-empty + /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ + flush() { + const sessionAggregates = this.getSessionAggregates(); + if (sessionAggregates.aggregates.length === 0) { + return; + } + this._pendingAggregates = {}; + this._client.sendSession(sessionAggregates); } - try { - const { cwd } = dynamicRequire(module, 'process'); - mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; - } catch (e) { - // no-empty + /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ + getSessionAggregates() { + const aggregates = Object.keys(this._pendingAggregates).map((key) => { + return this._pendingAggregates[parseInt(key)]; + }); + + const sessionAggregates = { + attrs: this._sessionAttrs, + aggregates, + }; + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); } - return mod; + /** JSDoc */ + close() { + clearInterval(this._intervalId); + this._isEnabled = false; + this.flush(); + } + + /** + * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then + * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to + * `_incrementSessionStatusCount` along with the start date + */ + incrementSessionStatusCount() { + if (!this._isEnabled) { + return; + } + const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); + const requestSession = scope && scope.getRequestSession(); + + if (requestSession && requestSession.status) { + this._incrementSessionStatusCount(requestSession.status, new Date()); + // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in + // case captureRequestSession is called more than once to prevent double count + if (scope) { + scope.setRequestSession(undefined); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + } + } + + /** + * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of + * the session received + */ + _incrementSessionStatusCount(status, date) { + // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys + const sessionStartedTrunc = new Date(date).setSeconds(0, 0); + this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + + // corresponds to aggregated sessions in one specific minute bucket + // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} + const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; + if (!aggregationCounts.started) { + aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); + } + + switch (status) { + case 'errored': + aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; + return aggregationCounts.errored; + case 'ok': + aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; + return aggregationCounts.exited; + default: + aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; + return aggregationCounts.crashed; + } + } } -//# sourceMappingURL=node.js.map +//# sourceMappingURL=sessionflusher.js.map /***/ }), -/* 1646 */ +/* 1634 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) +/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) /* harmony export */ }); -/* - * This module exists for optimizations in the build process through rollup and terser. We define some global - * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these - * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will - * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to - * `logger` and preventing node-related code from appearing in browser bundles. - * - * Attention: - * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by - * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) - * having issues tree-shaking these constants across package boundaries. - * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want - * users to be able to shake away expressions that it guards. - */ - -/** - * Figures out if we're building a browser bundle. - * - * @returns true if this is a browser bundle build. - */ -function isBrowserBundle() { - return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; -} +/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1635); -//# sourceMappingURL=env.js.map +; +//# sourceMappingURL=index.js.map /***/ }), -/* 1647 */ +/* 1635 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), -/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), -/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), -/* harmony export */ "arrayify": () => (/* binding */ arrayify), -/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), -/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), -/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), -/* harmony export */ "uuid4": () => (/* binding */ uuid4) +/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) /* harmony export */ }); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1648); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); - - +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1617); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); +/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; - const crypto = gbl.crypto || gbl.msCrypto; - if (crypto && crypto.randomUUID) { - return crypto.randomUUID().replace(/-/g, ''); - } - const getRandomByte = - crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - // Concatenating the following numbers as strings results in '10000000100040008000100000000000' - return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => - // eslint-disable-next-line no-bitwise - ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), - ); -} -function getFirstException(event) { - return event.exception && event.exception.values ? event.exception.values[0] : undefined; -} -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - const { message, event_id: eventId } = event; - if (message) { - return message; - } - const firstException = getFirstException(event); - if (firstException) { - if (firstException.type && firstException.value) { - return `${firstException.type}: ${firstException.value}`; - } - return firstException.type || firstException.value || eventId || '<unknown>'; - } - return eventId || '<unknown>'; -} +// Estimated maximum size for reasonable standalone event +const GZIP_THRESHOLD = 1024 * 32; /** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden + * Gets a stream from a Uint8Array or string + * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 */ -function addExceptionTypeValue(event, value, type) { - const exception = (event.exception = event.exception || {}); - const values = (exception.values = exception.values || []); - const firstException = (values[0] = values[0] || {}); - if (!firstException.value) { - firstException.value = value || ''; - } - if (!firstException.type) { - firstException.type = type || 'Error'; - } +function streamFromBody(body) { + return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ + read() { + this.push(body); + this.push(null); + }, + }); } /** - * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden + * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. */ -function addExceptionMechanism(event, newMechanism) { - const firstException = getFirstException(event); - if (!firstException) { - return; - } - - const defaultMechanism = { type: 'generic', handled: true }; - const currentMechanism = firstException.mechanism; - firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; +function makeNodeTransport(options) { + const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); + const isHttps = urlSegments.protocol === 'https:'; - if (newMechanism && 'data' in newMechanism) { - const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; - firstException.mechanism.data = mergedData; - } -} + // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` + // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` + const proxy = applyNoProxyOption( + urlSegments, + options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, + ); -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -const SEMVER_REGEXP = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; + const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; -/** - * Represents Semantic Versioning object - */ + // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node + // versions(>= 8) as they had memory leaks when using it: #2555 + const agent = proxy + ? (new (__webpack_require__(1636))(proxy) ) + : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - const match = input.match(SEMVER_REGEXP) || []; - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - const patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; + const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); + return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); } /** - * This function adds context (pre/post/line) lines to the provided frame + * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post + * @param transportUrl The URL the transport intends to send events to. + * @param proxy The client configured proxy. + * @returns A proxy the transport should use. */ -function addContextToFrame(lines, frame, linesOfContext = 5) { - const lineno = frame.lineno || 0; - const maxLines = lines.length; - const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); - - frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); -} +function applyNoProxyOption(transportUrlSegments, proxy) { + const { no_proxy } = process.env; -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (exception && (exception ).__sentry_captured__) { - return true; - } + const urlIsExemptFromProxy = + no_proxy && + no_proxy + .split(',') + .some( + exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), + ); - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); - } catch (err) { - // `exception` is a primitive, so we can't mark it seen + if (urlIsExemptFromProxy) { + return undefined; + } else { + return proxy; } - - return false; } /** - * Checks whether the given input is already an array, and if it isn't, wraps it in one. - * - * @param maybeArray Input to turn into an array, if necessary - * @returns The input, if already an array, or an array with the input as the only element, if not + * Creates a RequestExecutor to be used with `createTransport`. */ -function arrayify(maybeArray) { - return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; -} - - -//# sourceMappingURL=misc.js.map - - -/***/ }), -/* 1648 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +function createRequestExecutor( + options, + httpModule, + agent, +) { + const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); + return function makeRequest(request) { + return new Promise((resolve, reject) => { + let body = streamFromBody(request.body); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), -/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), -/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), -/* harmony export */ "snipLine": () => (/* binding */ snipLine), -/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), -/* harmony export */ "truncate": () => (/* binding */ truncate) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); + const headers = { ...options.headers }; + if (request.body.length > GZIP_THRESHOLD) { + headers['content-encoding'] = 'gzip'; + body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); + } -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string (0 = unlimited) - * @returns string Encoded - */ -function truncate(str, max = 0) { - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : `${str.substr(0, max)}...`; -} + const req = httpModule.request( + { + method: 'POST', + agent, + headers, + hostname, + path: `${pathname}${search}`, + port, + protocol, + ca: options.caCerts, + }, + res => { + res.on('data', () => { + // Drain socket + }); -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - let newLine = line; - const lineLength = newLine.length; - if (lineLength <= 150) { - return newLine; - } - if (colno > lineLength) { - // eslint-disable-next-line no-param-reassign - colno = lineLength; - } + res.on('end', () => { + // Drain socket + }); - let start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } + res.setEncoding('utf8'); - let end = Math.min(start + 140, lineLength); - if (end > lineLength - 5) { - end = lineLength; - } - if (end === lineLength) { - start = Math.max(end - 140, 0); - } + // "Key-value pairs of header names and values. Header names are lower-cased." + // https://nodejs.org/api/http.html#http_message_headers + const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); + const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = `'{snip} ${newLine}`; - } - if (end < lineLength) { - newLine += ' {snip}'; - } + resolve({ + statusCode: res.statusCode, + headers: { + 'retry-after': retryAfterHeader, + 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, + }, + }); + }, + ); - return newLine; + req.on('error', reject); + body.pipe(req); + }); + }; } -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - - const output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < input.length; i++) { - const value = input[i]; - try { - output.push(String(value)); - } catch (e) { - output.push('[value cannot be serialized]'); - } - } - - return output.join(delimiter); -} -/** - * Checks if the given value matches a regex or string - * - * @param value The string to test - * @param pattern Either a regex or a string against which `value` will be matched - * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match - * `pattern` if it contains `pattern`. Only applies to string-type patterns. - */ -function isMatchingPattern( - value, - pattern, - requireExactStringMatch = false, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { - return false; - } +//# sourceMappingURL=http.js.map - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { - return pattern.test(value); - } - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { - return requireExactStringMatch ? value === pattern : value.includes(pattern); - } - return false; -} +/***/ }), +/* 1636 */ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Test the given string against an array of strings and regexes. By default, string matching is done on a - * substring-inclusion basis rather than a strict equality basis - * - * @param testString The string to test - * @param patterns The patterns against which to test the string - * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to - * count. If false, `testString` will match a string pattern if it contains that pattern. - * @returns - */ -function stringMatchesSomePattern( - testString, - patterns = [], - requireExactStringMatch = false, -) { - return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); -} +"use strict"; -/** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped - */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__webpack_require__(1637)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); } - - -//# sourceMappingURL=string.js.map - +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map /***/ }), -/* 1649 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1637 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), -/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), -/* harmony export */ "isElement": () => (/* binding */ isElement), -/* harmony export */ "isError": () => (/* binding */ isError), -/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), -/* harmony export */ "isEvent": () => (/* binding */ isEvent), -/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), -/* harmony export */ "isNaN": () => (/* binding */ isNaN), -/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), -/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), -/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), -/* harmony export */ "isString": () => (/* binding */ isString), -/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), -/* harmony export */ "isThenable": () => (/* binding */ isThenable) -/* harmony export */ }); -// eslint-disable-next-line @typescript-eslint/unbound-method -const objectToString = Object.prototype.toString; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __importDefault(__webpack_require__(62)); +const tls_1 = __importDefault(__webpack_require__(145)); +const url_1 = __importDefault(__webpack_require__(63)); +const assert_1 = __importDefault(__webpack_require__(91)); +const debug_1 = __importDefault(__webpack_require__(1638)); +const agent_base_1 = __webpack_require__(1642); +const parse_proxy_response_1 = __importDefault(__webpack_require__(1648)); +const debug = debug_1.default('https-proxy-agent:agent'); /** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (objectToString.call(wat)) { - case '[object Error]': - case '[object Exception]': - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -/** - * Checks whether given value is an instance of the given built-in class. + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. * - * @param wat The value to be checked - * @param className - * @returns A boolean representing the result. - */ -function isBuiltin(wat, className) { - return objectToString.call(wat) === `[object ${className}]`; -} - -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @api public */ -function isErrorEvent(wat) { - return isBuiltin(wat, 'ErrorEvent'); +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } } - -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return isBuiltin(wat, 'DOMError'); +exports["default"] = HttpsProxyAgent; +function resume(socket) { + socket.resume(); } - -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return isBuiltin(wat, 'DOMException'); +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); } - -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return isBuiltin(wat, 'String'); +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } - -/** - * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; } +//# sourceMappingURL=agent.js.map -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return isBuiltin(wat, 'Object'); -} +/***/ }), +/* 1638 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __webpack_require__(1639); +} else { + module.exports = __webpack_require__(1641); } -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return isBuiltin(wat, 'RegExp'); -} -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} +/***/ }), +/* 1639 */ +/***/ ((module, exports, __webpack_require__) => { + +/* eslint-env browser */ /** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * This is the web browser implementation of `debug()`. */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Checks whether given value is NaN - * {@link isNaN}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Colors. */ -function isNaN(wat) { - return typeof wat === 'number' && wat !== wat; -} + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } catch (_e) { - return false; - } -} - - -//# sourceMappingURL=is.js.map - - -/***/ }), -/* 1650 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), -/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), -/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), -/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), -/* harmony export */ "fill": () => (/* binding */ fill), -/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), -/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), -/* harmony export */ "objectify": () => (/* binding */ objectify), -/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) -/* harmony export */ }); -/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1651); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1648); +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * Replace a method in an object with a wrapped version of itself. + * Colorize log arguments if enabled. * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other - * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. - * @returns void + * @api public */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - const original = source[name] ; - const wrapped = replacementFactory(original) ; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - markFunctionWrapped(wrapped, original); - } catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } + if (!this.useColors) { + return; + } - source[name] = wrapped; -} + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -/** - * Defines a non-enumerable property on the given object. - * - * @param obj The object on which to set the property - * @param name The name of the property to be set - * @param value The value to which to set the property - */ -function addNonEnumerableProperty(obj, name, value) { - Object.defineProperty(obj, name, { - // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it - value: value, - writable: true, - configurable: true, - }); + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } /** - * Remembers the original function on the wrapped function and - * patches up the prototype. + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. * - * @param wrapped the wrapper function - * @param original the original function that gets wrapped + * @api public */ -function markFunctionWrapped(wrapped, original) { - const proto = original.prototype || {}; - wrapped.prototype = original.prototype = proto; - addNonEnumerableProperty(wrapped, '__sentry_original__', original); -} +exports.log = console.debug || console.log || (() => {}); /** - * This extracts the original function if available. See - * `markFunctionWrapped` for more information. + * Save `namespaces`. * - * @param func the function to unwrap - * @returns the unwrapped version of the function if available. + * @param {String} namespaces + * @api private */ -function getOriginalFunction(func) { - return func.__sentry_original__; +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * Encodes given object into url-friendly format + * Load `namespaces`. * - * @param object An object that contains serializable values - * @returns string Encoded + * @return {String} returns the previously persisted debug modes + * @api private */ -function urlEncode(object) { - return Object.keys(object) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) - .join('&'); +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; } /** - * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their - * non-enumerable properties attached. + * Localstorage attempts to return the localstorage. * - * @param value Initial source that we have to transform in order for it to be usable by the serializer - * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor - * an Error. + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -function convertToPlainObject( - value, -) - - { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { - return { - message: value.message, - name: value.name, - stack: value.stack, - ...getOwnProperties(value), - }; - } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { - const newObj - - = { - type: value.type, - target: serializeEventTarget(value.target), - currentTarget: serializeEventTarget(value.currentTarget), - ...getOwnProperties(value), - }; - if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { - newObj.detail = value.detail; - } - - return newObj; - } else { - return value; - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } -/** Creates a string representation of the target of an `Event` object */ -function serializeEventTarget(target) { - try { - return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); - } catch (_oO) { - return '<unknown>'; - } -} +module.exports = __webpack_require__(1640)(exports); -/** Filters out all but an object's own properties */ -function getOwnProperties(obj) { - if (typeof obj === 'object' && obj !== null) { - const extractedProps = {}; - for (const property in obj) { - if (Object.prototype.hasOwnProperty.call(obj, property)) { - extractedProps[property] = (obj )[property]; - } - } - return extractedProps; - } else { - return {}; - } -} +const {formatters} = module.exports; /** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function extractExceptionKeysForMessage(exception, maxLength = 40) { - const keys = Object.keys(convertToPlainObject(exception)); - keys.sort(); - if (!keys.length) { - return '[object has no keys]'; - } +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; - if (keys[0].length >= maxLength) { - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); - } - for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { - const serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); - } +/***/ }), +/* 1640 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return ''; -} /** - * Given any object, return a new object having removed all fields whose value was `undefined`. - * Works recursively on objects and arrays. - * - * Attention: This function keeps circular references in the returned object. + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function dropUndefinedKeys(inputValue) { - // This map keeps track of what already visited nodes map to. - // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular - // references as the input object. - const memoizationMap = new Map(); - // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API - return _dropUndefinedKeys(inputValue, memoizationMap); -} +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(1405); + createDebug.destroy = destroy; -function _dropUndefinedKeys(inputValue, memoizationMap) { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { - // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - const returnValue = {}; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); + /** + * The currently active debug mode names, and names to skip. + */ - for (const key of Object.keys(inputValue)) { - if (typeof inputValue[key] !== 'undefined') { - returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); - } - } + createDebug.names = []; + createDebug.skips = []; - return returnValue ; - } + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - if (Array.isArray(inputValue)) { - // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - const returnValue = []; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - inputValue.forEach((item) => { - returnValue.push(_dropUndefinedKeys(item, memoizationMap)); - }); + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - return returnValue ; - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - return inputValue; -} + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -/** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. - * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods - */ -function objectify(wat) { - let objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; + const self = debug; - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new (wat ).constructor(wat); - break; + args[0] = createDebug.coerce(args[0]); - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; - } - return objectified; -} + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); -//# sourceMappingURL=object.js.map + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); -/***/ }), -/* 1651 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), -/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), -/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem, keyAttrs) { + return debug; + } - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - let currentElem = elem ; - const MAX_TRAVERSE_HEIGHT = 5; - const MAX_OUTPUT_LEN = 80; - const out = []; - let height = 0; - let len = 0; - const separator = ' > '; - const sepLength = separator.length; - let nextStr; + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem, keyAttrs); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; - out.push(nextStr); + createDebug.names = []; + createDebug.skips = []; - len += nextStr.length; - currentElem = currentElem.parentNode; - } + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; - return out.reverse().join(separator); - } catch (_oO) { - return '<unknown>'; - } -} + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el, keyAttrs) { - const elem = el + namespaces = split[i].replace(/\*/g, '.*?'); -; + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } - const out = []; - let className; - let classes; - let key; - let attr; - let i; + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - if (!elem || !elem.tagName) { - return ''; - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - out.push(elem.tagName.toLowerCase()); + let i; + let len; - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - const keyAttrPairs = - keyAttrs && keyAttrs.length - ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) - : null; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - if (keyAttrPairs && keyAttrPairs.length) { - keyAttrPairs.forEach(keyAttrPair => { - out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); - }); - } else { - if (elem.id) { - out.push(`#${elem.id}`); - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push(`.${classes[i]}`); - } - } - } - const allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push(`[${key}="${attr}"]`); - } - } - return out.join(''); -} + return false; + } -/** - * A safe form of location.href - */ -function getLocationHref() { - try { - return WINDOW.document.location.href; - } catch (oO) { - return ''; - } -} - -/** - * Gets a DOM element by using document.querySelector. - * - * This wrapper will first check for the existance of the function before - * actually calling it so that we don't have to take care of this check, - * every time we want to access the DOM. - * - * Reason: DOM/querySelector is not available in all environments. - * - * We have to cast to any because utils can be consumed by a variety of environments, - * and we don't want to break TS users. If you know what element will be selected by - * `document.querySelector`, specify it as part of the generic call. For example, - * `const element = getDomElement<Element>('selector');` - * - * @param selector the selector string passed on to document.querySelector - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getDomElement(selector) { - if (WINDOW.document && WINDOW.document.querySelector) { - return WINDOW.document.querySelector(selector) ; - } - return null; -} - - -//# sourceMappingURL=browser.js.map + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } -/***/ }), -/* 1652 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), -/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), -/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); + createDebug.enable(createDebug.load()); + return createDebug; +} -/* eslint-disable @typescript-eslint/explicit-function-return-type */ +module.exports = setup; -/** SyncPromise internal states */ -var States; (function (States) { - /** Pending */ - const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; - /** Resolved / OK */ - const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; - /** Rejected / Error */ - const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; -})(States || (States = {})); -// Overloads so we can call resolvedSyncPromise without arguments and generic argument +/***/ }), +/* 1641 */ +/***/ ((module, exports, __webpack_require__) => { /** - * Creates a resolved sync promise. - * - * @param value the value to resolve the promise with - * @returns the resolved sync promise + * Module dependencies. */ -function resolvedSyncPromise(value) { - return new SyncPromise(resolve => { - resolve(value); - }); -} -/** - * Creates a rejected sync promise. - * - * @param value the value to reject the promise with - * @returns the rejected sync promise - */ -function rejectedSyncPromise(reason) { - return new SyncPromise((_, reject) => { - reject(reason); - }); -} +const tty = __webpack_require__(1407); +const util = __webpack_require__(64); /** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally + * This is the Node.js implementation of `debug()`. */ -class SyncPromise { - __init() {this._state = States.PENDING;} - __init2() {this._handlers = [];} - - constructor( - executor, - ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); - try { - executor(this._resolve, this._reject); - } catch (e) { - this._reject(e); - } - } - - /** JSDoc */ - then( - onfulfilled, - onrejected, - ) { - return new SyncPromise((resolve, reject) => { - this._handlers.push([ - false, - result => { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result ); - } else { - try { - resolve(onfulfilled(result)); - } catch (e) { - reject(e); - } - } - }, - reason => { - if (!onrejected) { - reject(reason); - } else { - try { - resolve(onrejected(reason)); - } catch (e) { - reject(e); - } - } - }, - ]); - this._executeHandlers(); - }); - } - /** JSDoc */ - catch( - onrejected, - ) { - return this.then(val => val, onrejected); - } - - /** JSDoc */ - finally(onfinally) { - return new SyncPromise((resolve, reject) => { - let val; - let isRejected; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - return this.then( - value => { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, - reason => { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }, - ).then(() => { - if (isRejected) { - reject(val); - return; - } +/** + * Colors. + */ - resolve(val ); - }); - }); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - /** JSDoc */ - __init3() {this._resolve = (value) => { - this._setResult(States.RESOLVED, value); - };} +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __webpack_require__(1408); - /** JSDoc */ - __init4() {this._reject = (reason) => { - this._setResult(States.REJECTED, reason); - };} + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} - /** JSDoc */ - __init5() {this._setResult = (state, value) => { - if (this._state !== States.PENDING) { - return; - } +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { - void (value ).then(this._resolve, this._reject); - return; - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - this._state = state; - this._value = value; + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - this._executeHandlers(); - };} + obj[prop] = val; + return obj; +}, {}); - /** JSDoc */ - __init6() {this._executeHandlers = () => { - if (this._state === States.PENDING) { - return; - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - const cachedHandlers = this._handlers.slice(); - this._handlers = []; +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - cachedHandlers.forEach(handler => { - if (handler[0]) { - return; - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - if (this._state === States.RESOLVED) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler[1](this._value ); - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - if (this._state === States.REJECTED) { - handler[2](this._value); - } + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - handler[0] = true; - }); - };} + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } } +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} -//# sourceMappingURL=syncpromise.js.map - - -/***/ }), -/* 1653 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), -/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), -/* harmony export */ "logger": () => (/* binding */ logger) -/* harmony export */ }); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} -/** Prefix for logging strings */ -const PREFIX = 'Sentry Logger '; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; +function load() { + return process.env.DEBUG; +} /** - * Temporarily disable sentry console instrumentations. + * Init logic for `debug` instances. * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function consoleSandbox(callback) { - if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { - return callback(); - } - - const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; - const wrappedLevels = {}; - // Restore all wrapped console methods - CONSOLE_LEVELS.forEach(level => { - // TODO(v7): Remove this check as it's only needed for Node 6 - const originalWrappedFunc = - originalConsole[level] && (originalConsole[level] ).__sentry_original__; - if (level in originalConsole && originalWrappedFunc) { - wrappedLevels[level] = originalConsole[level] ; - originalConsole[level] = originalWrappedFunc ; - } - }); +function init(debug) { + debug.inspectOpts = {}; - try { - return callback(); - } finally { - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(level => { - originalConsole[level] = wrappedLevels[level ]; - }); - } + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } -function makeLogger() { - let enabled = false; - const logger = { - enable: () => { - enabled = true; - }, - disable: () => { - enabled = false; - }, - }; +module.exports = __webpack_require__(1640)(exports); - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - CONSOLE_LEVELS.forEach(name => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - logger[name] = (...args) => { - if (enabled) { - consoleSandbox(() => { - _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); - }); - } - }; - }); - } else { - CONSOLE_LEVELS.forEach(name => { - logger[name] = () => undefined; - }); - } +const {formatters} = module.exports; - return logger ; -} +/** + * Map %o to `util.inspect()`, all on a single line. + */ -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -let logger; -if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); -} else { - logger = makeLogger(); -} +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ -//# sourceMappingURL=logger.js.map +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /***/ }), -/* 1654 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1642 */ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) -/* harmony export */ }); -const SDK_VERSION = '7.23.0'; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __webpack_require__(250); +const debug_1 = __importDefault(__webpack_require__(1643)); +const promisify_1 = __importDefault(__webpack_require__(1647)); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map -//# sourceMappingURL=version.js.map +/***/ }), +/* 1643 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -/***/ }), -/* 1655 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __webpack_require__(1644); +} else { + module.exports = __webpack_require__(1646); +} -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), -/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), -/* harmony export */ "captureException": () => (/* binding */ captureException), -/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), -/* harmony export */ "configureScope": () => (/* binding */ configureScope), -/* harmony export */ "setContext": () => (/* binding */ setContext), -/* harmony export */ "setExtra": () => (/* binding */ setExtra), -/* harmony export */ "setExtras": () => (/* binding */ setExtras), -/* harmony export */ "setTag": () => (/* binding */ setTag), -/* harmony export */ "setTags": () => (/* binding */ setTags), -/* harmony export */ "setUser": () => (/* binding */ setUser), -/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), -/* harmony export */ "withScope": () => (/* binding */ withScope) -/* harmony export */ }); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); +/***/ }), +/* 1644 */ +/***/ ((module, exports, __webpack_require__) => { -// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, -// where HUB_FUNCTION is some method on the Hub class. -// -// This is done to make sure the top level SDK methods stay in sync with the hub methods. -// Although every method here has an explicit return type, some of them (that map to void returns) do not -// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. +/* eslint-env browser */ /** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @param captureContext Additional scope data to apply to exception event. - * @returns The generated eventId. + * This is the web browser implementation of `debug()`. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); -} + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param Severity Define the level of the message. - * @returns The generated eventId. + * Colors. */ -function captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - captureContext, -) { - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - const level = typeof captureContext === 'string' ? captureContext : undefined; - const context = typeof captureContext !== 'string' ? { captureContext } : undefined; - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); -} + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Captures a manually created event and sends it to Sentry. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * @param event The event to send to Sentry. - * @returns The generated eventId. + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -function captureEvent(event, hint) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); -} -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** - * Records a new breadcrumb which will be attached to future events. - * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. + * Colorize log arguments if enabled. * - * @param breadcrumb The breadcrumb to record. + * @api public */ -function addBreadcrumb(breadcrumb) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); -} -/** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); -} +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); -} + if (!this.useColors) { + return; + } -/** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. - */ -function setExtra(key, extra) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); -} + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } /** - * Set key:value that will be sent as tags data with the event. - * - * Can also be used to unset a tag, by passing `undefined`. + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. * - * @param key String key of tag - * @param value Value of tag + * @api public */ -function setTag(key, value) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); -} +exports.log = console.debug || console.log || (() => {}); /** - * Updates user context information for future events. + * Save `namespaces`. * - * @param user User context object to be set in the current context. Pass `null` to unset the user. + * @param {String} namespaces + * @api private */ -function setUser(user) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); + * Load `namespaces`. * - * @param callback that will be enclosed into push/popScope. + * @return {String} returns the previously persisted debug modes + * @api private */ -function withScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; } /** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call - * `startTransaction` directly on the hub. + * Localstorage attempts to return the localstorage. * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. * - * @returns The transaction which was just started + * @return {LocalStorage} + * @api private */ -function startTransaction( - context, - customSamplingContext, -) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = __webpack_require__(1645)(exports); -//# sourceMappingURL=exports.js.map +const {formatters} = module.exports; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -/***/ }), -/* 1656 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), -/* harmony export */ "createTransport": () => (/* binding */ createTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1664); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1658); +/***/ }), +/* 1645 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; /** - * Creates an instance of a Sentry `Transport` - * - * @param options - * @param makeRequest + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function createTransport( - options, - makeRequest, - buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), -) { - let rateLimits = {}; - const flush = (timeout) => buffer.drain(timeout); +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(1405); + createDebug.destroy = destroy; - function send(envelope) { - const filteredEnvelopeItems = []; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); - // Drop rate limited items from envelope - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { - const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); - } else { - filteredEnvelopeItems.push(item); - } - }); + /** + * The currently active debug mode names, and names to skip. + */ - // Skip sending if envelope is empty after filtering out rate limited events - if (filteredEnvelopeItems.length === 0) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } + createDebug.names = []; + createDebug.skips = []; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - // Creates client report for each item in an envelope - const recordEnvelopeLoss = (reason) => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); - }); - }; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - const requestTask = () => - makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( - response => { - // We don't want to throw on NOK responses, but we want to at least log them - if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); - recordEnvelopeLoss('network_error'); - }, - ); + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - return buffer.add(requestTask).then( - result => result, - error => { - if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); - recordEnvelopeLoss('queue_overflow'); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } else { - throw error; - } - }, - ); - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - return { - send, - flush, - }; -} + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -function getEventForEnvelopeItem(item, type) { - if (type !== 'event' && type !== 'transaction') { - return undefined; - } + createDebug.enable(createDebug.load()); - return Array.isArray(item) ? (item )[1] : undefined; + return createDebug; } - -//# sourceMappingURL=base.js.map +module.exports = setup; /***/ }), -/* 1657 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1658); -/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1652); - - +/* 1646 */ +/***/ ((module, exports, __webpack_require__) => { /** - * Creates an new PromiseBuffer object with the specified limit - * @param limit max number of promises that can be stored in the buffer + * Module dependencies. */ -function makePromiseBuffer(limit) { - const buffer = []; - - function isReady() { - return limit === undefined || buffer.length < limit; - } - /** - * Remove a promise from the queue. - * - * @param task Can be any PromiseLike<T> - * @returns Removed promise. - */ - function remove(task) { - return buffer.splice(buffer.indexOf(task), 1)[0]; - } - - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: - * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - function add(taskProducer) { - if (!isReady()) { - return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); - } +const tty = __webpack_require__(1407); +const util = __webpack_require__(64); - // start the task and add its promise to the queue - const task = taskProducer(); - if (buffer.indexOf(task) === -1) { - buffer.push(task); - } - void task - .then(() => remove(task)) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, () => - remove(task).then(null, () => { - // We have to add another catch here because `remove()` starts a new promise chain. - }), - ); - return task; - } +/** + * This is the Node.js implementation of `debug()`. + */ - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - function drain(timeout) { - return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { - let counter = buffer.length; +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - if (!counter) { - return resolve(true); - } +/** + * Colors. + */ - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - const capturedSetTimeout = setTimeout(() => { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); +exports.colors = [6, 2, 3, 4, 5, 1]; - // if all promises resolve in time, cancel the timer and resolve to `true` - buffer.forEach(item => { - void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { - if (!--counter) { - clearTimeout(capturedSetTimeout); - resolve(true); - } - }, reject); - }); - }); - } +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __webpack_require__(1408); - return { - $: buffer, - add, - drain, - }; + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -//# sourceMappingURL=promisebuffer.js.map - +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); -/***/ }), -/* 1658 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SentryError": () => (/* binding */ SentryError) -/* harmony export */ }); -/** An error emitted by Sentry SDKs and related utilities. */ -class SentryError extends Error { - /** Display name of this error instance. */ + obj[prop] = val; + return obj; +}, {}); - constructor( message, logLevel = 'warn') { - super(message);this.message = message;; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - this.name = new.target.prototype.constructor.name; - // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line - // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes - // instances of `SentryError` fail `obj instanceof SentryError` checks. - Object.setPrototypeOf(this, new.target.prototype); - this.logLevel = logLevel; - } +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -//# sourceMappingURL=error.js.map - - -/***/ }), -/* 1659 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +function formatArgs(args) { + const {namespace: name, useColors} = this; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), -/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), -/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), -/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), -/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), -/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) -/* harmony export */ }); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1660); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} /** - * Creates an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -function createEnvelope(headers, items = []) { - return [headers, items] ; + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } /** - * Add an item to an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ -function addItemToEnvelope(envelope, newItem) { - const [headers, items] = envelope; - return [headers, [...items, newItem]] ; +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } /** - * Convenience function to loop through the items and item types of an envelope. - * (This function was mostly created because working with envelope types is painful at the moment) + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -function forEachEnvelopeItem( - envelope, - callback, -) { - const envelopeItems = envelope[1]; - envelopeItems.forEach((envelopeItem) => { - const envelopeItemType = envelopeItem[0].type; - callback(envelopeItem, envelopeItemType); - }); -} -function encodeUTF8(input, textEncoder) { - const utf8 = textEncoder || new TextEncoder(); - return utf8.encode(input); +function load() { + return process.env.DEBUG; } /** - * Serializes an envelope. + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function serializeEnvelope(envelope, textEncoder) { - const [envHeaders, items] = envelope; - - // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data - let parts = JSON.stringify(envHeaders); - - function append(next) { - if (typeof parts === 'string') { - parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; - } else { - parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); - } - } - - for (const item of items) { - const [itemHeaders, payload] = item; - - append(`\n${JSON.stringify(itemHeaders)}\n`); - if (typeof payload === 'string' || payload instanceof Uint8Array) { - append(payload); - } else { - let stringifiedPayload; - try { - stringifiedPayload = JSON.stringify(payload); - } catch (e) { - // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still - // fails, we try again after normalizing it again with infinite normalization depth. This of course has a - // performance impact but in this case a performance hit is better than throwing. - stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); - } - append(stringifiedPayload); - } - } +function init(debug) { + debug.inspectOpts = {}; - return typeof parts === 'string' ? parts : concatBuffers(parts); + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } -function concatBuffers(buffers) { - const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); - - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const buffer of buffers) { - merged.set(buffer, offset); - offset += buffer.length; - } +module.exports = __webpack_require__(1645)(exports); - return merged; -} +const {formatters} = module.exports; /** - * Creates attachment envelope items + * Map %o to `util.inspect()`, all on a single line. */ -function createAttachmentEnvelopeItem( - attachment, - textEncoder, -) { - const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; - - return [ - (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ - type: 'attachment', - length: buffer.length, - filename: attachment.filename, - content_type: attachment.contentType, - attachment_type: attachment.attachmentType, - }), - buffer, - ]; -} -const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { - session: 'session', - sessions: 'session', - attachment: 'attachment', - transaction: 'transaction', - event: 'error', - client_report: 'internal', - user_report: 'default', +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); }; /** - * Maps the type of an envelope item to a data category. + * Map %O to `util.inspect()`, allowing multiple lines if needed. */ -function envelopeItemTypeToDataCategory(type) { - return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), +/* 1647 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; } +exports["default"] = promisify; +//# sourceMappingURL=promisify.js.map +/***/ }), +/* 1648 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -//# sourceMappingURL=envelope.js.map +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __importDefault(__webpack_require__(1638)); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports["default"] = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map /***/ }), -/* 1660 */ +/* 1649 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "normalize": () => (/* binding */ normalize), -/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), -/* harmony export */ "walk": () => (/* binding */ visit) +/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) /* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1661); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1662); - - - - - /** - * Recursively normalizes the given object. + * Polyfill for the nullish coalescing operator (`??`). * - * - Creates a copy to prevent original input mutation - * - Skips non-enumerable properties - * - When stringifying, calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format - * - Translates known global objects/classes to a string representations - * - Takes care of `Error` object serialization - * - Optionally limits depth of final output - * - Optionally limits number of properties/elements included in any single object/array + * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the + * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. * - * @param input The object to be normalized. - * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) - * @param maxProperties The max number of elements or properties to be included in any single array or - * object in the normallized output. - * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function normalize(input, depth = +Infinity, maxProperties = +Infinity) { - try { - // since we're at the outermost level, we don't provide a key - return visit('', input, depth, maxProperties); - } catch (err) { - return { ERROR: `**non-serializable** (${err})` }; - } -} - -/** JSDoc */ -function normalizeToSize( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object, - // Default Node.js REPL depth - depth = 3, - // 100kB, as 200kB is max payload size, so half sounds reasonable - maxSize = 100 * 1024, -) { - const normalized = normalize(object, depth); - - if (jsonSize(normalized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - - return normalized ; -} - -/** - * Visits a node to perform normalization on it + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) * - * @param key The key corresponding to the given node - * @param value The node to be visited - * @param depth Optional number indicating the maximum recursion depth - * @param maxProperties Optional maximum number of properties/elements included in any single object/array - * @param memo Optional Memo class handling decycling + * @param lhs The value of the expression to the left of the `??` + * @param rhsFn A function returning the value of the expression to the right of the `??` + * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value */ -function visit( - key, - value, - depth = +Infinity, - maxProperties = +Infinity, - memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), -) { - const [memoize, unmemoize] = memo; +function _nullishCoalesce(lhs, rhsFn) { + // by checking for loose equality to `null`, we catch both `null` and `undefined` + return lhs != null ? lhs : rhsFn(); +} - // Get the simple cases out of the way first - if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { - return value ; - } +// Sucrase version: +// function _nullishCoalesce(lhs, rhsFn) { +// if (lhs != null) { +// return lhs; +// } else { +// return rhsFn(); +// } +// } - const stringified = stringifyValue(key, value); - // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. - // Everything else will have already been serialized, so if we don't see that pattern, we're done. - if (!stringified.startsWith('[object ')) { - return stringified; - } +//# sourceMappingURL=_nullishCoalesce.js.map - // From here on, we can assert that `value` is either an object or an array. - // Do not normalize objects that we know have already been normalized. As a general rule, the - // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that - // have already been normalized. - if ((value )['__sentry_skip_normalization__']) { - return value ; - } +/***/ }), +/* 1650 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // We're also done if we've reached the max depth - if (depth === 0) { - // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. - return stringified.replace('object ', ''); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "close": () => (/* binding */ close), +/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), +/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), +/* harmony export */ "flush": () => (/* binding */ flush), +/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), +/* harmony export */ "init": () => (/* binding */ init), +/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), +/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1672); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1673); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1631); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1674); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1623); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1605); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1626); +/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1651); +/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1670); +/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1634); +/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1652); +/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1654); +/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1657); +/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1659); +/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1661); +/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1664); +/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1663); +/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1665); +/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1660); +/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1635); - // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. - if (memoize(value)) { - return '[Circular ~]'; - } - // If the value has a `toJSON` method, we call it to extract more information - const valueWithToJSON = value ; - if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { - try { - const jsonValue = valueWithToJSON.toJSON(); - // We need to normalize the return value of `.toJSON()` in case it has circular references - return visit('', jsonValue, depth - 1, maxProperties, memo); - } catch (err) { - // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) - } - } - // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse - // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each - // property/entry, and keep track of the number of items we add to it. - const normalized = (Array.isArray(value) ? [] : {}) ; - let numAdded = 0; - // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant - // properties are non-enumerable and otherwise would get missed. - const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); - for (const visitKey in visitable) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { - continue; - } - if (numAdded >= maxProperties) { - normalized[visitKey] = '[MaxProperties ~]'; - break; - } - // Recursively visit all the child nodes - const visitValue = visitable[visitKey]; - normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); - numAdded++; - } - // Once we've visited all the branches, remove the parent from memo storage - unmemoize(value); - // Return accumulated values - return normalized; -} -/** - * Stringify the given value. Handles various known special values and types. - * - * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn - * the number 1231 into "[Object Number]", nor on `null`, as it will throw. - * - * @param value The value to stringify - * @returns A stringified representation of the given value - */ -function stringifyValue( - key, - // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for - // our internal use, it'll do - value, -) { - try { - if (key === 'domain' && value && typeof value === 'object' && (value )._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - // eslint-disable-next-line no-restricted-globals - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - // React's SyntheticEvent thingy - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { - return '[SyntheticEvent]'; - } - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) - if (value === void 0) { - return '[undefined]'; - } +/* eslint-disable max-lines */ - if (typeof value === 'function') { - return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; - } +const defaultIntegrations = [ + // Common + new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), + new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), + // Native Wrappers + new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), + new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), + // Global Handlers + new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), + new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), + // Event Info + new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), + new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), + new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), + new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), + // Misc + new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), +]; - if (typeof value === 'symbol') { - return `[${String(value)}]`; - } +/** + * The Sentry Node SDK Client. + * + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. + * + * @example + * ``` + * + * const { init } = require('@sentry/node'); + * + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` + * + * @example + * ``` + * + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` + * + * @see {@link NodeOptions} for documentation on configuration options. + */ +function init(options = {}) { + const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); + const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion - if (typeof value === 'bigint') { - return `[BigInt: ${String(value)}]`; - } + options.defaultIntegrations = + options.defaultIntegrations === false + ? [] + : [ + ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), + ...autoloadedIntegrations, + ]; - // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting - // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as - // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), - // we can make sure that only plain objects come out that way. - return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; - } catch (err) { - return `**non-serializable** (${err})`; + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; } -} - -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} - -/** Calculates bytes size of input object */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} - - -//# sourceMappingURL=normalize.js.map - - -/***/ }), -/* 1661 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) -/* harmony export */ }); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/** - * Helper to decycle json objects - */ -function memoBuilder() { - const hasWeakSet = typeof WeakSet === 'function'; - const inner = hasWeakSet ? new WeakSet() : []; - function memoize(obj) { - if (hasWeakSet) { - if (inner.has(obj)) { - return true; - } - inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < inner.length; i++) { - const value = inner[i]; - if (value === obj) { - return true; - } + if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { + const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); + if (isFinite(tracesSampleRate)) { + options.tracesSampleRate = tracesSampleRate; } - inner.push(obj); - return false; } - function unmemoize(obj) { - if (hasWeakSet) { - inner.delete(obj); + if (options.release === undefined) { + const detectedRelease = getSentryRelease(); + if (detectedRelease !== undefined) { + options.release = detectedRelease; } else { - for (let i = 0; i < inner.length; i++) { - if (inner[i] === obj) { - inner.splice(i, 1); - break; - } - } + // If release is not provided, then we should disable autoSessionTracking + options.autoSessionTracking = false; } } - return [memoize, unmemoize]; -} + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } -//# sourceMappingURL=memo.js.map + if (options.autoSessionTracking === undefined && options.dsn !== undefined) { + options.autoSessionTracking = true; + } + if (options.instrumenter === undefined) { + options.instrumenter = 'sentry'; + } -/***/ }), -/* 1662 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), -/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), -/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), -/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), -/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1663); + // TODO(v7): Refactor this to reduce the logic above + const clientOptions = { + ...options, + stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), + integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), + transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, + }; + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); -const STACKTRACE_LIMIT = 50; + if (options.autoSessionTracking) { + startSessionTracking(); + } +} /** - * Creates a stack parser with the supplied line parsers - * - * StackFrames are returned in the correct order for Sentry Exception - * frames and with Sentry SDK internal frames removed from the top and bottom + * This is the getter for lastEventId. * + * @returns The last event id of a captured event. */ -function createStackParser(...parsers) { - const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); - - return (stack, skipFirst = 0) => { - const frames = []; - - for (const line of stack.split('\n').slice(skipFirst)) { - // https://github.com/getsentry/sentry-javascript/issues/5459 - // Remove webpack (error: *) wrappers - const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); - - for (const parser of sortedParsers) { - const frame = parser(cleanedLine); - - if (frame) { - frames.push(frame); - break; - } - } - } +function lastEventId() { + return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); +} - return stripSentryFramesAndReverse(frames); - }; +/** + * Call `flush()` on the current client, if there is one. See {@link Client.flush}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause + * the client to wait until all events are sent before resolving the promise. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +async function flush(timeout) { + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); + if (client) { + return client.flush(timeout); + } + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); + return Promise.resolve(false); } /** - * Gets a stack parser implementation from Options.stackParser - * @see Options + * Call `close()` on the current client, if there is one. See {@link Client.close}. * - * If options contains an array of line parsers, it is converted into a parser + * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this + * parameter will cause the client to wait until all events are sent before disabling itself. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). */ -function stackParserFromStackParserOptions(stackParser) { - if (Array.isArray(stackParser)) { - return createStackParser(...stackParser); +async function close(timeout) { + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); + if (client) { + return client.close(timeout); } - return stackParser; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); + return Promise.resolve(false); } /** - * @hidden + * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client */ -function stripSentryFramesAndReverse(stack) { - if (!stack.length) { - return []; +function isAutoSessionTrackingEnabled(client) { + if (client === undefined) { + return false; } + const clientOptions = client && client.getOptions(); + if (clientOptions && clientOptions.autoSessionTracking !== undefined) { + return clientOptions.autoSessionTracking; + } + return false; +} - let localStack = stack; - - const firstFrameFunction = localStack[0].function || ''; - const lastFrameFunction = localStack[localStack.length - 1].function || ''; - - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); +/** + * Returns a release dynamically from environment variables. + */ +function getSentryRelease(fallback) { + // Always read first as Sentry takes this as precedence + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; } - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); + // This supports the variable that sentry-webpack-plugin injects + if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { + return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; } - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(frame => ({ - ...frame, - filename: frame.filename || localStack[0].filename, - function: frame.function || '?', - })) - .reverse(); + return ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env.GITHUB_SHA || + // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env.COMMIT_REF || + // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env.VERCEL_GIT_COMMIT_SHA || + process.env.VERCEL_GITHUB_COMMIT_SHA || + process.env.VERCEL_GITLAB_COMMIT_SHA || + process.env.VERCEL_BITBUCKET_COMMIT_SHA || + // Zeit (now known as Vercel) + process.env.ZEIT_GITHUB_COMMIT_SHA || + process.env.ZEIT_GITLAB_COMMIT_SHA || + process.env.ZEIT_BITBUCKET_COMMIT_SHA || + fallback + ); } -const defaultFunctionName = '<anonymous>'; +/** Node.js stack parser */ +const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); /** - * Safely extract function name from itself + * Enable automatic Session Tracking for the node process. */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } +function startSessionTracking() { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); + hub.startSession(); + // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because + // The 'beforeExit' event is not emitted for conditions causing explicit termination, + // such as calling process.exit() or uncaught exceptions. + // Ref: https://nodejs.org/api/process.html#process_event_beforeexit + process.on('beforeExit', () => { + const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); + const terminalStates = ['exited', 'crashed']; + // Only call endSession, if the Session exists on Scope and SessionStatus is not a + // Terminal Status i.e. Exited or Crashed because + // "When a session is moved away from ok it must not be updated anymore." + // Ref: https://develop.sentry.dev/sdk/sessions/ + if (session && !terminalStates.includes(session.status)) hub.endSession(); + }); } -// eslint-disable-next-line complexity -function node(getModule) { - const FILENAME_MATCH = /^\s*[-]{4,}$/; - const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; - - // eslint-disable-next-line complexity - return (line) => { - if (line.match(FILENAME_MATCH)) { - return { - filename: line, - }; - } - - const lineMatch = line.match(FULL_MATCH); - if (!lineMatch) { - return undefined; - } - let object; - let method; - let functionName; - let typeName; - let methodName; +//# sourceMappingURL=sdk.js.map - if (lineMatch[1]) { - functionName = lineMatch[1]; - let methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - methodStart--; - } +/***/ }), +/* 1651 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - const objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = undefined; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), +/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), +/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), +/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), +/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), +/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), +/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), +/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), +/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) +/* harmony export */ }); +/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1652); +/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1654); +/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1657); +/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1659); +/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1660); +/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); +/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1661); +/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1664); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1665); - if (method) { - typeName = object; - methodName = method; - } - if (method === '<anonymous>') { - methodName = undefined; - functionName = undefined; - } - if (functionName === undefined) { - methodName = methodName || '<anonymous>'; - functionName = typeName ? `${typeName}.${methodName}` : methodName; - } - const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; - const isNative = lineMatch[5] === 'native'; - const isInternal = - isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); - return { - filename, - module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), - function: functionName, - lineno: parseInt(lineMatch[3], 10) || undefined, - colno: parseInt(lineMatch[4], 10) || undefined, - in_app, - }; - }; -} -/** - * Node.js stack line parser - * - * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. - * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain - */ -function nodeStackLineParser(getModule) { - return [90, node(getModule)]; -} -//# sourceMappingURL=stacktrace.js.map +//# sourceMappingURL=index.js.map /***/ }), -/* 1663 */ +/* 1652 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) +/* harmony export */ "Console": () => (/* binding */ Console) /* harmony export */ }); -/** - * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, - * descriptors, and functions. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 - * - * @param ops Array result of expression conversion - * @returns The value of the expression - */ -function _optionalChain(ops) { - let lastAccessLHS = undefined; - let value = ops[0]; - let i = 1; - while (i < ops.length) { - const op = ops[i] ; - const fn = ops[i + 1] ; - i += 2; - // by checking for loose equality to `null`, we catch both `null` and `undefined` - if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { - // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it - return; - } - if (op === 'access' || op === 'optionalAccess') { - lastAccessLHS = value; - value = fn(value); - } else if (op === 'call' || op === 'optionalCall') { - value = fn((...args) => (value ).call(lastAccessLHS, ...args)); - lastAccessLHS = undefined; +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); + + + + +/** Console module integration */ +class Console {constructor() { Console.prototype.__init.call(this); } + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Console';} + + /** + * @inheritDoc + */ + __init() {this.name = Console.id;} + + /** + * @inheritDoc + */ + setupOnce() { + for (const level of ['debug', 'info', 'warn', 'error', 'log']) { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); } } - return value; -} +} Console.__initStatic(); -// Sucrase version -// function _optionalChain(ops) { -// let lastAccessLHS = undefined; -// let value = ops[0]; -// let i = 1; -// while (i < ops.length) { -// const op = ops[i]; -// const fn = ops[i + 1]; -// i += 2; -// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { -// return undefined; -// } -// if (op === 'access' || op === 'optionalAccess') { -// lastAccessLHS = value; -// value = fn(value); -// } else if (op === 'call' || op === 'optionalCall') { -// value = fn((...args) => value.call(lastAccessLHS, ...args)); -// lastAccessLHS = undefined; -// } -// } -// return value; -// } +/** + * Wrapper function that'll be used for every console level + */ +function createConsoleWrapper(level) { + return function consoleWrapper(originalConsoleMethod) { + const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); + /* eslint-disable prefer-rest-params */ + return function () { + if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( + { + category: 'console', + level: sentryLevel, + message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), + }, + { + input: [...arguments], + level, + }, + ); + } -//# sourceMappingURL=_optionalChain.js.map + originalConsoleMethod.apply(this, arguments); + }; + /* eslint-enable prefer-rest-params */ + }; +} + + +//# sourceMappingURL=console.js.map /***/ }), -/* 1664 */ +/* 1653 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), -/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), -/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), -/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), -/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) +/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), +/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), +/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) /* harmony export */ }); -// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend +// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either +// +// a) moving `validSeverityLevels` to `@sentry/types`, +// b) moving the`SeverityLevel` type here, or +// c) importing `validSeverityLevels` from here into `@sentry/types`. +// +// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would +// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the +// type, reminding anyone who changes it to change this list also, will have to do. -const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds +const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; /** - * Extracts Retry-After value from the request header or returns default value - * @param header string representation of 'Retry-After' header - * @param now current unix timestamp + * Converts a string-based level into a member of the deprecated {@link Severity} enum. * + * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. + * + * @param level String representation of Severity + * @returns Severity */ -function parseRetryAfterHeader(header, now = Date.now()) { - const headerDelay = parseInt(`${header}`, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - - const headerDate = Date.parse(`${header}`); - if (!isNaN(headerDate)) { - return headerDate - now; - } - - return DEFAULT_RETRY_AFTER; -} - -/** - * Gets the time that given category is disabled until for rate limiting - */ -function disabledUntil(limits, category) { - return limits[category] || limits.all || 0; -} - -/** - * Checks if a category is rate limited - */ -function isRateLimited(limits, category, now = Date.now()) { - return disabledUntil(limits, category) > now; +function severityFromString(level) { + return severityLevelFromString(level) ; } /** - * Update ratelimits from incoming headers. - * Returns true if headers contains a non-empty rate limiting header. + * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. + * + * @param level String representation of desired `SeverityLevel`. + * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. */ -function updateRateLimits( - limits, - { statusCode, headers }, - now = Date.now(), -) { - const updatedRateLimits = { - ...limits, - }; - - // "The name is case-insensitive." - // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - const rateLimitHeader = headers && headers['x-sentry-rate-limits']; - const retryAfterHeader = headers && headers['retry-after']; - - if (rateLimitHeader) { - /** - * rate limit headers are of the form - * <header>,<header>,.. - * where each <header> is of the form - * <retry_after>: <categories>: <scope>: <reason_code> - * where - * <retry_after> is a delay in seconds - * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form - * <category>;<category>;... - * <scope> is what's being limited (org, project, or key) - ignored by SDK - * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK - */ - for (const limit of rateLimitHeader.trim().split(',')) { - const [retryAfter, categories] = limit.split(':', 2); - const headerDelay = parseInt(retryAfter, 10); - const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - if (!categories) { - updatedRateLimits.all = now + delay; - } else { - for (const category of categories.split(';')) { - updatedRateLimits[category] = now + delay; - } - } - } - } else if (retryAfterHeader) { - updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); - } else if (statusCode === 429) { - updatedRateLimits.all = now + 60 * 1000; - } - - return updatedRateLimits; +function severityLevelFromString(level) { + return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; } -//# sourceMappingURL=ratelimit.js.map +//# sourceMappingURL=severity.js.map /***/ }), -/* 1665 */ +/* 1654 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) +/* harmony export */ "Http": () => (/* binding */ Http) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1667); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1654); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1672); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1652); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1666); - +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1609); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1656); +/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1655); +const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); /** - * The Sentry Node SDK Client. - * - * @see NodeClientOptions for documentation on configuration options. - * @see SentryClient for usage documentation. + * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing + * http requests and attaches trace data when tracing is enabled via its `tracing` option. */ -class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { - +class Http { /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. + * @inheritDoc */ - constructor(options) { - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }, - ], - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }; + static __initStatic() {this.id = 'Http';} - // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util - options.transportOptions = { - textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), - ...options.transportOptions, - }; + /** + * @inheritDoc + */ + __init() {this.name = Http.id;} - super(options); + /** + * @inheritDoc + */ + constructor(options = {}) {;Http.prototype.__init.call(this); + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; } /** * @inheritDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const requestSession = scope.getRequestSession(); + setupOnce( + _addGlobalEventProcessor, + setupOnceGetCurrentHub, + ) { + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !this._tracing) { + return; + } - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } + const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); + + // Do not auto-instrument for other instrumenter + if (clientOptions && clientOptions.instrumenter !== 'sentry') { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); + return; } - return super.captureException(exception, hint, scope); + // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions + // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. + const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; + + const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); + + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpModule = __webpack_require__(80); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); + + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpsModule = __webpack_require__(81); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); + } } +}Http.__initStatic(); - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const eventType = event.type || 'exception'; - const isException = - eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; +// for ease of reading below - // If the event is of type Exception, then a request session should be captured - if (isException) { - const requestSession = scope.getRequestSession(); +/** + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) + * + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * + * @returns A function which accepts the exiting handler and returns a wrapped handler + */ +function _createWrappedRequestMethodFactory( + breadcrumbsEnabled, + tracingOptions, +) { + // We're caching results so we don't have to recompute regexp every time we create a request. + const createSpanUrlMap = {}; + const headersUrlMap = {}; - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } + const shouldCreateSpan = (url) => { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { + return true; } - return super.captureEvent(event, hint, scope); - } + if (createSpanUrlMap[url]) { + return createSpanUrlMap[url]; + } - /** - * - * @inheritdoc - */ - close(timeout) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); - return super.close(timeout); - } + createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); - /** Method that initialises an instance of SessionFlusher on Client */ - initSessionFlusher() { - const { release, environment } = this._options; - if (!release) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } else { - this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { - release, - environment, - }); + return createSpanUrlMap[url]; + }; + + const shouldAttachTraceData = (url) => { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { + return true; } - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - eventFromException(exception, hint) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); - } + if (headersUrlMap[url]) { + return headersUrlMap[url]; + } - /** - * @inheritDoc - */ - eventFromMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - ) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( - (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), - ); - } + headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); - /** - * @inheritDoc - */ - _prepareEvent(event, hint, scope) { - event.platform = event.platform || 'node'; - event.contexts = { - ...event.contexts, - runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { - name: 'node', - version: global.process.version, - }, + return headersUrlMap[url]; + }; + + return function wrappedRequestMethodFactory(originalRequestMethod) { + return function wrappedMethod( ...args) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const httpModule = this; + + const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); + const requestOptions = requestArgs[0]; + const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); + + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method + if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { + return originalRequestMethod.apply(httpModule, requestArgs); + } + + let requestSpan; + let parentSpan; + + const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); + + if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { + parentSpan = scope.getSpan(); + + if (parentSpan) { + requestSpan = parentSpan.startChild({ + description: `${requestOptions.method || 'GET'} ${requestUrl}`, + op: 'http.client', + }); + + if (shouldAttachTraceData(requestUrl)) { + const sentryTraceHeader = requestSpan.toTraceparent(); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( + `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, + ); + + requestOptions.headers = { + ...requestOptions.headers, + 'sentry-trace': sentryTraceHeader, + }; + + if (parentSpan.transaction) { + const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); + const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); + + let newBaggageHeaderField; + if (!requestOptions.headers || !requestOptions.headers.baggage) { + newBaggageHeaderField = sentryBaggageHeader; + } else if (!sentryBaggageHeader) { + newBaggageHeaderField = requestOptions.headers.baggage; + } else if (Array.isArray(requestOptions.headers.baggage)) { + newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; + } else { + // Type-cast explanation: + // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity + // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. + newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; + } + + requestOptions.headers = { + ...requestOptions.headers, + // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined + ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), + }; + } + } else { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( + `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, + ); + } + + const transaction = parentSpan.transaction; + if (transaction) { + transaction.metadata.propagations++; + } + } + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalRequestMethod + .apply(httpModule, requestArgs) + .once('response', function ( res) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', requestUrl, req, res); + } + if (requestSpan) { + if (res.statusCode) { + requestSpan.setHttpStatus(res.statusCode); + } + requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); + requestSpan.finish(); + } + }) + .once('error', function () { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; + + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', requestUrl, req); + } + if (requestSpan) { + requestSpan.setHttpStatus(500); + requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); + requestSpan.finish(); + } + }); }; - event.server_name = - event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); - return super._prepareEvent(event, hint, scope); - } + }; +} - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - _captureRequestSession() { - if (!this._sessionFlusher) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } else { - this._sessionFlusher.incrementSessionStatusCount(); - } +/** + * Captures Breadcrumb based on provided request/response pair + */ +function addRequestBreadcrumb(event, url, req, res) { + if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { + return; } + + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( + { + category: 'http', + data: { + method: req.method, + status_code: res && res.statusCode, + url, + }, + type: 'http', + }, + { + event, + request: req, + response: res, + }, + ); } -//# sourceMappingURL=client.js.map +//# sourceMappingURL=http.js.map /***/ }), -/* 1666 */ +/* 1655 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), -/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), -/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), -/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) +/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), +/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), +/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), +/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), +/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1660); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1647); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); + + + +const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); /** - * Extracts stack frames from the error.stack string + * Checks whether given url points to Sentry server + * @param url url to verify */ -function parseStackFrames(stackParser, error) { - return stackParser(error.stack || '', 1); +function isSentryRequest(url) { + const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); + return dsn ? url.includes(dsn.host) : false; } /** - * Extracts stack frames from the error and builds a Sentry Exception + * Assemble a URL to be used for breadcrumbs and spans. + * + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL */ -function exceptionFromError(stackParser, error) { - const exception = { - type: error.name || error.constructor.name, - value: error.message, - }; - - const frames = parseStackFrames(stackParser, error); - if (frames.length) { - exception.stacktrace = { frames }; - } +function extractUrl(requestOptions) { + const protocol = requestOptions.protocol || ''; + const hostname = requestOptions.hostname || requestOptions.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + const port = + !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; + const path = requestOptions.path ? requestOptions.path : '/'; - return exception; + return `${protocol}//${hostname}${port}${path}`; } /** - * Builds and Event from a Exception - * @hidden + * Handle various edge cases in the span description (for spans representing http(s) requests). + * + * @param description current `description` property of the span representing the request + * @param requestOptions Configuration data for the request + * @param Request Request object + * + * @returns The cleaned description */ -function eventFromUnknownInput(stackParser, exception, hint) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let ex = exception; - const providedMechanism = - hint && hint.data && (hint.data ).mechanism; - const mechanism = providedMechanism || { - handled: true, - type: 'generic', - }; +function cleanSpanDescription( + description, + requestOptions, + request, +) { + // nothing to clean + if (!description) { + return description; + } - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(exception)) { - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; + // eslint-disable-next-line prefer-const + let [method, requestUrl] = description.split(' '); - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); - const client = hub.getClient(); - const normalizeDepth = client && client.getOptions().normalizeDepth; - hub.configureScope(scope => { - scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); - }); + // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, + // we're likely dealing with an internal route and this doesn't apply) + if (requestOptions.host && !requestOptions.protocol) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes + requestUrl = extractUrl(requestOptions); + } - ex = (hint && hint.syntheticException) || new Error(message); - (ex ).message = message; - } else { - // This handles when someone does: `throw "something awesome";` - // We use synthesized Error here so we can extract a (rough) stack trace. - ex = (hint && hint.syntheticException) || new Error(exception ); - (ex ).message = exception ; - } - mechanism.synthetic = true; + // internal routes can end up starting with a triple slash rather than a single one + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { + requestUrl = requestUrl.slice(2); } - const event = { - exception: { - values: [exceptionFromError(stackParser, ex )], - }, - }; + return `${method} ${requestUrl}`; +} - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); +// the node types are missing a few properties which node's `urlToOptions` function spits out - return { - ...event, - event_id: hint && hint.event_id, +/** + * Convert a URL object into a RequestOptions object. + * + * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the + * RequestOptions type above. + * + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + */ +function urlToOptions(url) { + const options = { + protocol: url.protocol, + hostname: + typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: `${url.pathname || ''}${url.search || ''}`, + href: url.href, }; + if (url.port !== '') { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; + } + return options; } /** - * Builds and Event from a Message - * @hidden + * Normalize inputs to `http(s).request()` and `http(s).get()`. + * + * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: + * [ RequestOptions | string | URL ], + * [ RequestOptions | string | URL, RequestCallback ], + * [ string | URL, RequestOptions ], and + * [ string | URL, RequestOptions, RequestCallback ]. + * + * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is + * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact + * with the args in a standard way. + * + * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. */ -function eventFromMessage( - stackParser, - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - attachStacktrace, +function normalizeRequestArgs( + httpModule, + requestArgs, ) { - const event = { - event_id: hint && hint.event_id, - level, - message, - }; + let callback, requestOptions; - if (attachStacktrace && hint && hint.syntheticException) { - const frames = parseStackFrames(stackParser, hint.syntheticException); - if (frames.length) { - event.exception = { - values: [ - { - value: message, - stacktrace: { frames }, - }, - ], - }; + // pop off the callback, if there is one + if (typeof requestArgs[requestArgs.length - 1] === 'function') { + callback = requestArgs.pop() ; + } + + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); + } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { + requestOptions = urlToOptions(requestArgs[0]); + } else { + requestOptions = requestArgs[0]; + } + + // if the options were given separately from the URL, fold them in + if (requestArgs.length === 2) { + requestOptions = { ...requestOptions, ...requestArgs[1] }; + } + + // Figure out the protocol if it's currently missing + if (requestOptions.protocol === undefined) { + // Worst case we end up populating protocol with undefined, which it already is + /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ + + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, + // as it will always return `http`, even when using `https` module. + // + // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + requestOptions.protocol = + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); + } else { + requestOptions.protocol = + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); } + /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ } - return event; + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } else { + return [requestOptions]; + } } -//# sourceMappingURL=eventbuilder.js.map +//# sourceMappingURL=http.js.map /***/ }), -/* 1667 */ +/* 1656 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) +/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), +/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), +/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), +/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), +/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), +/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1660); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1648); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1658); -/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1669); -/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1671); -/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1670); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1641); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1642); - - +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +const BAGGAGE_HEADER_NAME = 'baggage'; +const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; -const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; +const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; /** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. - * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. - * - * Before sending an event, it is passed through - * {@link BaseClient._prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. - * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. - * - * @example - * class NodeClient extends BaseClient<NodeOptions> { - * public constructor(options: NodeOptions) { - * super(options); - * } + * Max length of a serialized baggage string * - * // ... - * } + * https://www.w3.org/TR/baggage/#limits */ -class BaseClient { - /** Options passed to the SDK. */ - - /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ - - /** Array of set up integrations. */ - __init() {this._integrations = {};} - - /** Indicates whether this client's integrations have been set up. */ - __init2() {this._integrationsInitialized = false;} +const MAX_BAGGAGE_STRING_LENGTH = 8192; - /** Number of calls being processed */ - __init3() {this._numProcessing = 0;} +/** + * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values + * from it. + * + * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. + * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. + */ +function baggageHeaderToDynamicSamplingContext( + // Very liberal definition of what any incoming header might look like + baggageHeader, +) { + if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { + return undefined; + } - /** Holds flushable */ - __init4() {this._outcomes = {};} + // Intermediary object to store baggage key value pairs of incoming baggage headers on. + // It is later used to read Sentry-DSC-values from. + let baggageObject = {}; - /** - * Initializes this client instance. - * - * @param options Options for the client. - */ - constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); - this._options = options; - if (options.dsn) { - this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); - const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); - this._transport = options.transport({ - recordDroppedEvent: this.recordDroppedEvent.bind(this), - ...options.transportOptions, - url, - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); + if (Array.isArray(baggageHeader)) { + // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it + baggageObject = baggageHeader.reduce((acc, curr) => { + const currBaggageObject = baggageHeaderToObject(curr); + return { + ...acc, + ...currBaggageObject, + }; + }, {}); + } else { + // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but + // this is how we choose to handle it) + if (!baggageHeader) { + return undefined; } + + baggageObject = baggageHeaderToObject(baggageHeader); } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // ensure we haven't captured this very object before - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; + // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. + const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { + if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { + const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); + acc[nonPrefixedKey] = value; } + return acc; + }, {}); - let eventId; - this._process( - this.eventFromException(exception, hint) - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - - return eventId; + // Only return a dynamic sampling context object if there are keys in it. + // A keyless object means there were no sentry values on the header, which means that there is no DSC. + if (Object.keys(dynamicSamplingContext).length > 0) { + return dynamicSamplingContext ; + } else { + return undefined; } +} - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - scope, - ) { - let eventId; +/** + * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". + * + * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility + * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is + * `undefined` the function will return `undefined`. + * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` + * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. + */ +function dynamicSamplingContextToSentryBaggageHeader( + // this also takes undefined for convenience and bundle size in other places + dynamicSamplingContext, +) { + // Prefix all DSC keys with "sentry-" and put them into a new object + const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( + (acc, [dscKey, dscValue]) => { + if (dscValue) { + acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; + } + return acc; + }, + {}, + ); - const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) - ? this.eventFromMessage(String(message), level, hint) - : this.eventFromException(message, hint); + return objectToBaggageHeader(sentryPrefixedDSC); +} - this._process( - promisedEvent - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); +/** + * Will parse a baggage header, which is a simple key-value map, into a flat object. + * + * @param baggageHeader The baggage header to parse. + * @returns a flat object containing all the key-value pairs from `baggageHeader`. + */ +function baggageHeaderToObject(baggageHeader) { + return baggageHeader + .split(',') + .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) + .reduce((acc, [key, value]) => { + acc[key] = value; + return acc; + }, {}); +} - return eventId; +/** + * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. + * + * @param object The object to turn into a baggage header. + * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header + * is not spec compliant. + */ +function objectToBaggageHeader(object) { + if (Object.keys(object).length === 0) { + // An empty baggage header is not spec compliant: We return undefined. + return undefined; } - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // ensure we haven't captured this very object before - if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; + return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { + const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; + const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; + if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( + `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, + ); + return baggageHeader; + } else { + return newBaggageHeader; } + }, ''); +} - let eventId; - - this._process( - this._captureEvent(event, hint, scope).then(result => { - eventId = result; - }), - ); - return eventId; - } +//# sourceMappingURL=baggage.js.map - /** - * @inheritDoc - */ - captureSession(session) { - if (!this._isEnabled()) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); - return; - } - if (!(typeof session.release === 'string')) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); - } else { - this.sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); - } - } +/***/ }), +/* 1657 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - getDsn() { - return this._dsn; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); - /** - * @inheritDoc - */ - getOptions() { - return this._options; - } - /** - * @inheritDoc - */ - getTransport() { - return this._transport; - } - /** - * @inheritDoc - */ - flush(timeout) { - const transport = this._transport; - if (transport) { - return this._isClientDoneProcessing(timeout).then(clientFinished => { - return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); - }); - } else { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); - } - } +/** Global Exception handler */ +class OnUncaughtException { /** * @inheritDoc */ - close(timeout) { - return this.flush(timeout).then(result => { - this.getOptions().enabled = false; - return result; - }); - } - - /** - * Sets up the integrations - */ - setupIntegrations() { - if (this._isEnabled() && !this._integrationsInitialized) { - this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); - this._integrationsInitialized = true; - } - } - - /** - * Gets an installed integration by its `id`. - * - * @returns The installed integration or `undefined` if no integration with that `id` was installed. - */ - getIntegrationById(integrationId) { - return this._integrations[integrationId]; - } + static __initStatic() {this.id = 'OnUncaughtException';} /** * @inheritDoc */ - getIntegration(integration) { - try { - return (this._integrations[integration.id] ) || null; - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); - return null; - } - } + __init() {this.name = OnUncaughtException.id;} /** * @inheritDoc */ - sendEvent(event, hint = {}) { - if (this._dsn) { - let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); - - for (const attachment of hint.attachments || []) { - env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( - env, - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( - attachment, - this._options.transportOptions && this._options.transportOptions.textEncoder, - ), - ); - } + __init2() {this.handler = this._makeErrorHandler();} - this._sendEnvelope(env); - } - } + // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` /** * @inheritDoc */ - sendSession(session) { - if (this._dsn) { - const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); - this._sendEnvelope(env); - } + constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); + this._options = { + exitEvenIfOtherHandlersAreRegistered: true, + ...options, + }; } /** * @inheritDoc */ - recordDroppedEvent(reason, category, _event) { - // Note: we use `event` in replay, where we overwrite this hook. - - if (this._options.sendClientReports) { - // We want to track each category (error, transaction, session) separately - // but still keep the distinction between different type of outcomes. - // We could use nested maps, but it's much easier to read and type this way. - // A correct type for map-based implementation if we want to go that route - // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` - // With typescript 4.1 we could even use template literal types - const key = `${reason}:${category}`; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); - - // The following works because undefined + 1 === NaN and NaN is falsy - this._outcomes[key] = this._outcomes[key] + 1 || 1; - } - } - - /** Updates existing session based on the provided event */ - _updateSessionFromEvent(session, event) { - let crashed = false; - let errored = false; - const exceptions = event.exception && event.exception.values; - - if (exceptions) { - errored = true; - - for (const ex of exceptions) { - const mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - const sessionNonTerminal = session.status === 'ok'; - const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); - - if (shouldUpdateAndSend) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { - ...(crashed && { status: 'crashed' }), - errors: session.errors || Number(errored || crashed), - }); - this.captureSession(session); - } - } - - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - _isClientDoneProcessing(timeout) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { - let ticked = 0; - const tick = 1; - - const interval = setInterval(() => { - if (this._numProcessing == 0) { - clearInterval(interval); - resolve(true); - } else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - } - - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - _isEnabled() { - return this.getOptions().enabled !== false && this._dsn !== undefined; - } - - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - _prepareEvent(event, hint, scope) { - const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); - const prepared = { - ...event, - event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), - timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.dateTimestampInSeconds)(), - }; - - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); - - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - let finalScope = scope; - if (hint.captureContext) { - finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); - } - - // We prepare the result here with a resolved Event. - let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); - - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - // - // We need to check for the existence of `finalScope.getAttachments` - // because `getAttachments` can be undefined if users are using an older version - // of `@sentry/core` that does not have the `getAttachments` method. - // See: https://github.com/getsentry/sentry-javascript/issues/5229 - if (finalScope && finalScope.getAttachments) { - // Collect attachments from the hint and scope - const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; - - if (attachments.length) { - hint.attachments = attachments; - } - - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - - return result.then(evt => { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - return evt; - }); + setupOnce() { + global.process.on('uncaughtException', this.handler); } /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event + * @hidden */ - _normalizeEvent(event, depth, maxBreadth) { - if (!event) { - return null; - } - - const normalized = { - ...event, - ...(event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(b => ({ - ...b, - ...(b.data && { - data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), - }), - })), - }), - ...(event.user && { - user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), - }), - ...(event.contexts && { - contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), - }), - ...(event.extra && { - extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), - }), - }; + _makeErrorHandler() { + const timeout = 2000; + let caughtFirstError = false; + let caughtSecondError = false; + let calledFatalError = false; + let firstError; - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace && normalized.contexts) { - normalized.contexts.trace = event.contexts.trace; + return (error) => { + let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); - // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it - if (event.contexts.trace.data) { - normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); + if (this._options.onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = this._options.onFatalError; + } else if (client && client.getOptions().onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = client.getOptions().onFatalError ; } - } - - // event.spans[].data may contain circular/dangerous data so we need to normalize it - if (event.spans) { - normalized.spans = event.spans.map(span => { - // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable - if (span.data) { - span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); - } - return span; - }); - } - - return normalized; - } - - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - _applyClientOptions(event) { - const options = this.getOptions(); - const { environment, release, dist, maxValueLength = 250 } = options; - - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; - } - - if (event.release === undefined && release !== undefined) { - event.release = release; - } - - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; - } - - if (event.message) { - event.message = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); - } - - const exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); - } - - const request = event.request; - if (request && request.url) { - request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); - } - } - /** - * This function adds all used integrations to the SDK info in the event. - * @param event The event that will be filled with all integrations. - */ - _applyIntegrationsMetadata(event) { - const integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; - } - } - - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - _captureEvent(event, hint = {}, scope) { - return this._processEvent(event, hint, scope).then( - finalEvent => { - return finalEvent.event_id; - }, - reason => { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for - // control flow, log just the message (no stack) as a log-level log. - const sentryError = reason ; - if (sentryError.logLevel === 'log') { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); + // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not + // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust + // exit behaviour of the SDK accordingly: + // - If other listeners are attached, do not exit. + // - If the only listener attached is ours, exit. + const userProvidedListenersCount = global.process + .listeners('uncaughtException') + .reduce((acc, listener) => { + if ( + listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself + listener === this.handler // filter the handler we registered ourselves) + ) { + return acc; } else { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); + return acc + 1; } - } - return undefined; - }, - ); - } - - /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. - */ - _processEvent(event, hint, scope) { - const options = this.getOptions(); - const { sampleRate } = options; - - if (!this._isEnabled()) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); - } - - const isTransaction = event.type === 'transaction'; - const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; - const beforeSendProcessor = options[beforeSendProcessorName]; - - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - this.recordDroppedEvent('sample_rate', 'error', event); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( - new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, - 'log', - ), - ); - } - - return this._prepareEvent(event, hint, scope) - .then(prepared => { - if (prepared === null) { - this.recordDroppedEvent('event_processor', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); - } - - const isInternalException = hint.data && (hint.data ).__sentry__ === true; - if (isInternalException || !beforeSendProcessor) { - return prepared; - } + }, 0); - const beforeSendResult = beforeSendProcessor(prepared, hint); - return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); - }) - .then(processedEvent => { - if (processedEvent === null) { - this.recordDroppedEvent('before_send', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); - } + const processWouldExit = userProvidedListenersCount === 0; + const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; - const session = scope && scope.getSession(); - if (!isTransaction && session) { - this._updateSessionFromEvent(session, processedEvent); - } + if (!caughtFirstError) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - // None of the Sentry built event processor will update transaction name, - // so if the transaction name has been changed by an event processor, we know - // it has to come from custom event processor added by a user - const transactionInfo = processedEvent.transaction_info; - if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { - const source = 'custom'; - processedEvent.transaction_info = { - ...transactionInfo, - source, - changes: [ - ...transactionInfo.changes, - { - source, - // use the same timestamp as the processed event. - timestamp: processedEvent.timestamp , - propagations: transactionInfo.propagations, - }, - ], - }; - } + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; - this.sendEvent(processedEvent, hint); - return processedEvent; - }) - .then(null, reason => { - if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { - throw reason; + if (hub.getIntegration(OnUncaughtException)) { + hub.withScope((scope) => { + scope.setLevel('fatal'); + hub.captureException(error, { + originalException: error, + data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, + }); + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } + }); + } else { + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } } - - this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason , - }); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, - ); - }); - } - - /** - * Occupies the client with processing and event - */ - _process(promise) { - this._numProcessing++; - void promise.then( - value => { - this._numProcessing--; - return value; - }, - reason => { - this._numProcessing--; - return reason; - }, - ); - } - - /** - * @inheritdoc - */ - _sendEnvelope(envelope) { - if (this._transport && this._dsn) { - this._transport.send(envelope).then(null, reason => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); - } - } - - /** - * Clears outcomes on this client and returns them. - */ - _clearOutcomes() { - const outcomes = this._outcomes; - this._outcomes = {}; - return Object.keys(outcomes).map(key => { - const [reason, category] = key.split(':') ; - return { - reason, - category, - quantity: outcomes[key], - }; - }); - } - - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - -} - -/** - * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. - */ -function _validateBeforeSendResult( - beforeSendResult, - beforeSendProcessorName, -) { - const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { - return beforeSendResult.then( - event => { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); + } else { + if (shouldApplyFatalHandlingLogic) { + if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( + 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', + ); + (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); + } else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(() => { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } else { + // it was probably case 2, our first error finished capturing while we waited, cool, do nothing + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc + } } - return event; - }, - e => { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); - }, - ); - } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); + } + }; } - return beforeSendResult; -} +} OnUncaughtException.__initStatic(); -//# sourceMappingURL=baseclient.js.map +//# sourceMappingURL=onuncaughtexception.js.map /***/ }), -/* 1668 */ +/* 1658 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), -/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), -/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) +/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) /* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); -/** Regular expression used to parse a Dsn. */ -const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; - -function isValidProtocol(protocol) { - return protocol === 'http' || protocol === 'https'; -} -/** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ -function dsnToString(dsn, withPassword = false) { - const { host, path, pass, port, projectId, protocol, publicKey } = dsn; - return ( - `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + - `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` - ); -} +const DEFAULT_SHUTDOWN_TIMEOUT = 2000; /** - * Parses a Dsn from a given string. - * - * @param str A Dsn as string - * @returns Dsn as DsnComponents - */ -function dsnFromString(str) { - const match = DSN_REGEX.exec(str); - - if (!match) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); - } - - const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); - let path = ''; - let projectId = lastPath; - - const split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop() ; - } - - if (projectId) { - const projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - - return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); -} - -function dsnFromComponents(components) { - return { - protocol: components.protocol, - publicKey: components.publicKey || '', - pass: components.pass || '', - host: components.host, - port: components.port || '', - path: components.path || '', - projectId: components.projectId, - }; -} - -function validateDsn(dsn) { - if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - return; - } - - const { port, projectId, protocol } = dsn; - - const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; - requiredComponents.forEach(component => { - if (!dsn[component]) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); - } - }); - - if (!projectId.match(/^\d+$/)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); - } + * @hidden + */ +function logAndExitProcess(error) { + // eslint-disable-next-line no-console + console.error(error && error.stack ? error.stack : error); - if (!isValidProtocol(protocol)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); - } + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); - if (port && isNaN(parseInt(port, 10))) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); + if (client === undefined) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); } - return true; -} - -/** The Sentry Dsn, identifying a Sentry instance and project. */ -function makeDsn(from) { - const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); - validateDsn(components); - return components; + const options = client.getOptions(); + const timeout = + (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + client.close(timeout).then( + (result) => { + if (!result) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); + } + global.process.exit(1); + }, + error => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); + }, + ); } -//# sourceMappingURL=dsn.js.map +//# sourceMappingURL=errorhandling.js.map /***/ }), -/* 1669 */ +/* 1659 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), -/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) +/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1668); - - -const SENTRY_API_VERSION = '7'; +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); -/** Returns the prefix to construct Sentry ingestion API endpoints. */ -function getBaseApiEndpoint(dsn) { - const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; - const port = dsn.port ? `:${dsn.port}` : ''; - return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; -} -/** Returns the ingest API endpoint for target. */ -function _getIngestEndpoint(dsn) { - return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; -} -/** Returns a URL-encoded string with auth config suitable for a query string. */ -function _encodedAuth(dsn, sdkInfo) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - sentry_version: SENTRY_API_VERSION, - ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), - }); -} -/** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ -function getEnvelopeEndpointWithUrlEncodedAuth( - dsn, - // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below - // options: ClientOptions = {} as ClientOptions, - tunnelOrOptions = {} , -) { - // TODO (v8): Use this code instead - // const { tunnel, _metadata = {} } = options; - // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; +/** Global Promise Rejection handler */ +class OnUnhandledRejection { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'OnUnhandledRejection';} - const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; - const sdkInfo = - typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; + /** + * @inheritDoc + */ + __init() {this.name = OnUnhandledRejection.id;} - return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; -} + /** + * @inheritDoc + */ + constructor( + _options -/** Returns the url to the report dialog endpoint. */ -function getReportDialogEndpoint( - dsnLike, - dialogOptions + = { mode: 'warn' }, + ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} -, -) { - const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); - const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; + /** + * @inheritDoc + */ + setupOnce() { + global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + } - let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; - for (const key in dialogOptions) { - if (key === 'dsn') { - continue; + /** + * Send an exception with reason + * @param reason string + * @param promise promise + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any + sendUnhandledPromise(reason, promise) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); + if (hub.getIntegration(OnUnhandledRejection)) { + hub.withScope((scope) => { + scope.setExtra('unhandledPromiseRejection', true); + hub.captureException(reason, { + originalException: promise, + data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, + }); + }); } + this._handleRejection(reason); + } - if (key === 'user') { - const user = dialogOptions.user; - if (!user) { - continue; - } - if (user.name) { - encodedOptions += `&name=${encodeURIComponent(user.name)}`; - } - if (user.email) { - encodedOptions += `&email=${encodeURIComponent(user.email)}`; - } - } else { - encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; + /** + * Handler for `mode` option + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _handleRejection(reason) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + const rejectionWarning = + 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + + /* eslint-disable no-console */ + if (this._options.mode === 'warn') { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); + } else if (this._options.mode === 'strict') { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { + console.warn(rejectionWarning); + }); + (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); } + /* eslint-enable no-console */ } - - return `${endpoint}?${encodedOptions}`; -} +} OnUnhandledRejection.__initStatic(); -//# sourceMappingURL=api.js.map +//# sourceMappingURL=onunhandledrejection.js.map /***/ }), -/* 1670 */ +/* 1660 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), -/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), -/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) +/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1640); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1641); - - +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1613); +/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1627); +/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1661); -const installedIntegrations = []; - -/** Map of integrations assigned to a client */ -/** - * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to - * preseve the order of integrations in the array. - * - * @private - */ -function filterDuplicates(integrations) { - const integrationsByName = {}; - integrations.forEach(currentInstance => { - const { name } = currentInstance; - const existingInstance = integrationsByName[name]; - // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a - // default instance to overwrite an existing user instance - if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { - return; - } +const DEFAULT_KEY = 'cause'; +const DEFAULT_LIMIT = 5; - integrationsByName[name] = currentInstance; - }); +/** Adds SDK info to an event. */ +class LinkedErrors { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'LinkedErrors';} - return Object.values(integrationsByName); -} + /** + * @inheritDoc + */ + __init() {this.name = LinkedErrors.id;} -/** Gets integrations to install */ -function getIntegrationsToSetup(options) { - const defaultIntegrations = options.defaultIntegrations || []; - const userIntegrations = options.integrations; + /** + * @inheritDoc + */ - // We flag default instances, so that later we can tell them apart from any user-created instances of the same class - defaultIntegrations.forEach(integration => { - integration.isDefaultInstance = true; - }); + /** + * @inheritDoc + */ - let integrations; + /** + * @inheritDoc + */ + constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); + this._key = options.key || DEFAULT_KEY; + this._limit = options.limit || DEFAULT_LIMIT; + } - if (Array.isArray(userIntegrations)) { - integrations = [...defaultIntegrations, ...userIntegrations]; - } else if (typeof userIntegrations === 'function') { - integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); - } else { - integrations = defaultIntegrations; + /** + * @inheritDoc + */ + setupOnce() { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); + const self = hub.getIntegration(LinkedErrors); + const client = hub.getClient(); + if (client && self && self._handler && typeof self._handler === 'function') { + await self._handler(client.getOptions().stackParser, event, hint); + } + return event; + }); } - const finalIntegrations = filterDuplicates(integrations); + /** + * @inheritDoc + */ + _handler(stackParser, event, hint) { + if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); + } - // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or - // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event - // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore - // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. - const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); - if (debugIndex !== -1) { - const [debugInstance] = finalIntegrations.splice(debugIndex, 1); - finalIntegrations.push(debugInstance); + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { + void this._walkErrorTree(stackParser, hint.originalException , this._key) + .then((linkedErrors) => { + if (event && event.exception && event.exception.values) { + event.exception.values = [...linkedErrors, ...event.exception.values]; + } + resolve(event); + }) + .then(null, () => { + resolve(event); + }); + }); } - return finalIntegrations; -} - -/** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations - */ -function setupIntegrations(integrations) { - const integrationIndex = {}; + /** + * @inheritDoc + */ + async _walkErrorTree( + stackParser, + error, + key, + stack = [], + ) { + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { + return Promise.resolve(stack); + } - integrations.forEach(integration => { - integrationIndex[integration.name] = integration; + const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); - if (installedIntegrations.indexOf(integration.name) === -1) { - integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); - installedIntegrations.push(integration.name); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); + // If the ContextLines integration is enabled, we add source code context to linked errors + // because we can't guarantee the order that integrations are run. + const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); + if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { + await contextLines.addSourceContextToFrames(exception.stacktrace.frames); } - }); - return integrationIndex; -} + return new Promise((resolve, reject) => { + void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) + .then(resolve) + .then(null, () => { + reject(); + }); + }); + } +}LinkedErrors.__initStatic(); -//# sourceMappingURL=integration.js.map +//# sourceMappingURL=linkederrors.js.map /***/ }), -/* 1671 */ +/* 1661 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), -/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) +/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), +/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1608); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1662); +/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(metadata) { - if (!metadata || !metadata.sdk) { - return; - } - const { name, version } = metadata.sdk; - return { name, version }; -} -/** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. - **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; - } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; - event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; - return event; -} -/** Creates an envelope from a Session */ -function createSessionEnvelope( - session, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const envelopeHeaders = { - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - }; - const envelopeItem = - 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; +const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); +const DEFAULT_LINES_OF_CONTEXT = 7; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); +// TODO: Replace with promisify when minimum supported node >= v8 +function readTextFileAsync(path) { + return new Promise((resolve, reject) => { + (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { + if (err) reject(err); + else resolve(data); + }); + }); } /** - * Create an Envelope from an event. + * Resets the file cache. Exists for testing purposes. + * @hidden */ -function createEventEnvelope( - event, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const eventType = event.type || 'event'; +function resetFileContentCache() { + FILE_CONTENT_CACHE.clear(); +} - enhanceEventWithSdkInfo(event, metadata && metadata.sdk); +/** Add node modules / packages to the event */ +class ContextLines { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'ContextLines';} - const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); + /** + * @inheritDoc + */ + __init() {this.name = ContextLines.id;} - // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to - // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may - // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid - // of this `delete`, lest we miss putting it back in the next time the property is in use.) - delete event.sdkProcessingMetadata; + constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} - const eventItem = [{ type: eventType }, event]; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); -} + /** Get's the number of context lines to add */ + get _contextLines() { + return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + } -function createEventEnvelopeHeaders( - event, - sdkInfo, - tunnel, - dsn, -) { - const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor) { + addGlobalEventProcessor(event => this.addSourceContext(event)); + } - return { - event_id: event.event_id , - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - ...(event.type === 'transaction' && - dynamicSamplingContext && { - trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), - }), - }; -} + /** Processes an event and adds context lines */ + async addSourceContext(event) { + if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { + for (const exception of event.exception.values) { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { + await this.addSourceContextToFrames(exception.stacktrace.frames); + } + } + } + return event; + } -//# sourceMappingURL=envelope.js.map + /** Adds context lines to frames */ + async addSourceContextToFrames(frames) { + const contextLines = this._contextLines; + for (const frame of frames) { + // Only add context if we have a filename and it hasn't already been added + if (frame.filename && frame.context_line === undefined) { + const sourceFile = await _readSourceFile(frame.filename); -/***/ }), -/* 1672 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + if (sourceFile) { + try { + const lines = sourceFile.split('\n'); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); + } catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + } + } + } +}ContextLines.__initStatic(); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); +/** + * Reads file contents and caches them in a global LRU cache. + * + * @param filename filepath to read content from. + */ +async function _readSourceFile(filename) { + const cachedFile = FILE_CONTENT_CACHE.get(filename); + // We have a cache hit + if (cachedFile !== undefined) { + return cachedFile; + } + let content = null; + try { + content = await readTextFileAsync(filename); + } catch (_) { + // + } + FILE_CONTENT_CACHE.set(filename, content); + return content; +} -/** - * @inheritdoc + +//# sourceMappingURL=contextlines.js.map + + +/***/ }), +/* 1662 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most + * recently used items while discarding least recently used items when its limit + * is reached. + * + * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/> + * See README.md for details. + * + * Illustration of the design: + * + * entry entry entry entry + * ______ ______ ______ ______ + * | head |.newer => | |.newer => | |.newer => | tail | + * | A | | B | | C | | D | + * |______| <= older.|______| <= older.|______| <= older.|______| + * + * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added */ -class SessionFlusher { - __init() {this.flushTimeout = 60;} - __init2() {this._pendingAggregates = {};} +(function(g,f){ + const e = true ? exports : 0; + f(e); + if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } +})(this, function(exports) { - __init3() {this._isEnabled = true;} +const NEWER = Symbol('newer'); +const OLDER = Symbol('older'); - constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); - this._client = client; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); - this._sessionAttrs = attrs; +function LRUMap(limit, entries) { + if (typeof limit !== 'number') { + // called as (entries) + entries = limit; + limit = 0; } - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ - flush() { - const sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; + this.size = 0; + this.limit = limit; + this.oldest = this.newest = undefined; + this._keymap = new Map(); + + if (entries) { + this.assign(entries); + if (limit < 1) { + this.limit = this.size; } - this._pendingAggregates = {}; - this._client.sendSession(sessionAggregates); } +} - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - getSessionAggregates() { - const aggregates = Object.keys(this._pendingAggregates).map((key) => { - return this._pendingAggregates[parseInt(key)]; - }); +exports.LRUMap = LRUMap; - const sessionAggregates = { - attrs: this._sessionAttrs, - aggregates, - }; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); - } +function Entry(key, value) { + this.key = key; + this.value = value; + this[NEWER] = undefined; + this[OLDER] = undefined; +} - /** JSDoc */ - close() { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); - } - /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date - */ - incrementSessionStatusCount() { - if (!this._isEnabled) { - return; +LRUMap.prototype._markEntryAsUsed = function(entry) { + if (entry === this.newest) { + // Already the most recenlty used entry, so no need to update the list + return; + } + // HEAD--------------TAIL + // <.older .newer> + // <--- add direction -- + // A B C <D> E + if (entry[NEWER]) { + if (entry === this.oldest) { + this.oldest = entry[NEWER]; } - const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); - const requestSession = scope && scope.getRequestSession(); + entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. + } + if (entry[OLDER]) { + entry[OLDER][NEWER] = entry[NEWER]; // C. --> E + } + entry[NEWER] = undefined; // D --x + entry[OLDER] = this.newest; // D. --> E + if (this.newest) { + this.newest[NEWER] = entry; // E. <-- D + } + this.newest = entry; +}; - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - if (scope) { - scope.setRequestSession(undefined); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ +LRUMap.prototype.assign = function(entries) { + let entry, limit = this.limit || Number.MAX_VALUE; + this._keymap.clear(); + let it = entries[Symbol.iterator](); + for (let itv = it.next(); !itv.done; itv = it.next()) { + let e = new Entry(itv.value[0], itv.value[1]); + this._keymap.set(e.key, e); + if (!entry) { + this.oldest = e; + } else { + entry[NEWER] = e; + e[OLDER] = entry; + } + entry = e; + if (limit-- == 0) { + throw new Error('overflow'); } } + this.newest = entry; + this.size = this._keymap.size; +}; - /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received - */ - _incrementSessionStatusCount(status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - const sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; +LRUMap.prototype.get = function(key) { + // First, find our cache entry + var entry = this._keymap.get(key); + if (!entry) return; // Not cached. Sorry. + // As <key> was found in the cache, register it as being requested recently + this._markEntryAsUsed(entry); + return entry.value; +}; - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); - } +LRUMap.prototype.set = function(key, value) { + var entry = this._keymap.get(key); - switch (status) { - case 'errored': - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case 'ok': - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - default: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; + if (entry) { + // update existing + entry.value = value; + this._markEntryAsUsed(entry); + return this; + } + + // new entry + this._keymap.set(key, (entry = new Entry(key, value))); + + if (this.newest) { + // link previous tail to the new tail (entry) + this.newest[NEWER] = entry; + entry[OLDER] = this.newest; + } else { + // we're first in -- yay + this.oldest = entry; + } + + // add new entry to the end of the linked list -- it's now the freshest entry. + this.newest = entry; + ++this.size; + if (this.size > this.limit) { + // we hit the limit -- remove the head + this.shift(); + } + + return this; +}; + +LRUMap.prototype.shift = function() { + // todo: handle special case when limit == 1 + var entry = this.oldest; + if (entry) { + if (this.oldest[NEWER]) { + // advance the list + this.oldest = this.oldest[NEWER]; + this.oldest[OLDER] = undefined; + } else { + // the cache is exhausted + this.oldest = undefined; + this.newest = undefined; } + // Remove last strong reference to <entry> and remove links from the purged + // entry being returned: + entry[NEWER] = entry[OLDER] = undefined; + this._keymap.delete(entry.key); + --this.size; + return [entry.key, entry.value]; } -} +}; +// ---------------------------------------------------------------------------- +// Following code is optional and can be removed without breaking the core +// functionality. -//# sourceMappingURL=sessionflusher.js.map +LRUMap.prototype.find = function(key) { + let e = this._keymap.get(key); + return e ? e.value : undefined; +}; +LRUMap.prototype.has = function(key) { + return this._keymap.has(key); +}; -/***/ }), -/* 1673 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +LRUMap.prototype['delete'] = function(key) { + var entry = this._keymap.get(key); + if (!entry) return; + this._keymap.delete(entry.key); + if (entry[NEWER] && entry[OLDER]) { + // relink the older entry with the newer entry + entry[OLDER][NEWER] = entry[NEWER]; + entry[NEWER][OLDER] = entry[OLDER]; + } else if (entry[NEWER]) { + // remove the link to us + entry[NEWER][OLDER] = undefined; + // link the newer entry to head + this.oldest = entry[NEWER]; + } else if (entry[OLDER]) { + // remove the link to us + entry[OLDER][NEWER] = undefined; + // link the newer entry to head + this.newest = entry[OLDER]; + } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { + this.oldest = this.newest = undefined; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1674); + this.size--; + return entry.value; +}; +LRUMap.prototype.clear = function() { + // Not clearing links should be safe, as we don't expose live links to user + this.oldest = this.newest = undefined; + this.size = 0; + this._keymap.clear(); +}; -; -//# sourceMappingURL=index.js.map +function EntryIterator(oldestEntry) { this.entry = oldestEntry; } +EntryIterator.prototype[Symbol.iterator] = function() { return this; } +EntryIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: [ent.key, ent.value] }; + } else { + return { done: true, value: undefined }; + } +}; -/***/ }), -/* 1674 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1688); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1656); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); +function KeyIterator(oldestEntry) { this.entry = oldestEntry; } +KeyIterator.prototype[Symbol.iterator] = function() { return this; } +KeyIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.key }; + } else { + return { done: true, value: undefined }; + } +}; +function ValueIterator(oldestEntry) { this.entry = oldestEntry; } +ValueIterator.prototype[Symbol.iterator] = function() { return this; } +ValueIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.value }; + } else { + return { done: true, value: undefined }; + } +}; +LRUMap.prototype.keys = function() { + return new KeyIterator(this.oldest); +}; +LRUMap.prototype.values = function() { + return new ValueIterator(this.oldest); +}; +LRUMap.prototype.entries = function() { + return this; +}; +LRUMap.prototype[Symbol.iterator] = function() { + return new EntryIterator(this.oldest); +}; +LRUMap.prototype.forEach = function(fun, thisObj) { + if (typeof thisObj !== 'object') { + thisObj = this; + } + let entry = this.oldest; + while (entry) { + fun.call(thisObj, entry.value, entry.key, this); + entry = entry[NEWER]; + } +}; -// Estimated maximum size for reasonable standalone event -const GZIP_THRESHOLD = 1024 * 32; +/** Returns a JSON (array) representation */ +LRUMap.prototype.toJSON = function() { + var s = new Array(this.size), i = 0, entry = this.oldest; + while (entry) { + s[i++] = { key: entry.key, value: entry.value }; + entry = entry[NEWER]; + } + return s; +}; -/** - * Gets a stream from a Uint8Array or string - * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 - */ -function streamFromBody(body) { - return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ - read() { - this.push(body); - this.push(null); - }, - }); -} +/** Returns a String representation */ +LRUMap.prototype.toString = function() { + var s = '', entry = this.oldest; + while (entry) { + s += String(entry.key)+':'+entry.value; + entry = entry[NEWER]; + if (entry) { + s += ' < '; + } + } + return s; +}; -/** - * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. - */ -function makeNodeTransport(options) { - const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - const isHttps = urlSegments.protocol === 'https:'; +}); - // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` - // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` - const proxy = applyNoProxyOption( - urlSegments, - options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, - ); - const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; - const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; +/***/ }), +/* 1663 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { - // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node - // versions(>= 8) as they had memory leaks when using it: #2555 - const agent = proxy - ? (new (__webpack_require__(1675))(proxy) ) - : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Modules": () => (/* binding */ Modules) +/* harmony export */ }); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); -} -/** - * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. - * - * @param transportUrl The URL the transport intends to send events to. - * @param proxy The client configured proxy. - * @returns A proxy the transport should use. - */ -function applyNoProxyOption(transportUrlSegments, proxy) { - const { no_proxy } = process.env; - const urlIsExemptFromProxy = - no_proxy && - no_proxy - .split(',') - .some( - exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), - ); +let moduleCache; - if (urlIsExemptFromProxy) { - return undefined; - } else { - return proxy; +/** Extract information about paths */ +function getPaths() { + try { + return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; + } catch (e) { + return []; } } -/** - * Creates a RequestExecutor to be used with `createTransport`. - */ -function createRequestExecutor( - options, - httpModule, - agent, -) { - const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - return function makeRequest(request) { - return new Promise((resolve, reject) => { - let body = streamFromBody(request.body); +/** Extract information about package.json modules */ +function collectModules() + + { + const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; + const paths = getPaths(); + const infos + + = {}; + const seen + + = {}; + + paths.forEach(path => { + let dir = path; + + /** Traverse directories upward in the search of package.json file */ + const updir = () => { + const orig = dir; + dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); + + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } + + const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); + seen[orig] = true; - const headers = { ...options.headers }; + if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { + return updir(); + } - if (request.body.length > GZIP_THRESHOLD) { - headers['content-encoding'] = 'gzip'; - body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); + try { + const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) + +; + infos[info.name] = info.version; + } catch (_oO) { + // no-empty } + }; - const req = httpModule.request( - { - method: 'POST', - agent, - headers, - hostname, - path: `${pathname}${search}`, - port, - protocol, - ca: options.caCerts, - }, - res => { - res.on('data', () => { - // Drain socket - }); + updir(); + }); - res.on('end', () => { - // Drain socket - }); + return infos; +} - res.setEncoding('utf8'); +/** Add node modules / packages to the event */ +class Modules {constructor() { Modules.prototype.__init.call(this); } + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Modules';} - // "Key-value pairs of header names and values. Header names are lower-cased." - // https://nodejs.org/api/http.html#http_message_headers - const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); - const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); + /** + * @inheritDoc + */ + __init() {this.name = Modules.id;} - resolve({ - statusCode: res.statusCode, - headers: { - 'retry-after': retryAfterHeader, - 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, - }, - }); + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + addGlobalEventProcessor(event => { + if (!getCurrentHub().getIntegration(Modules)) { + return event; + } + return { + ...event, + modules: { + ...event.modules, + ...this._getModules(), }, - ); - - req.on('error', reject); - body.pipe(req); + }; }); - }; -} + } + + /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ + _getModules() { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; + } +} Modules.__initStatic(); -//# sourceMappingURL=http.js.map +//# sourceMappingURL=modules.js.map /***/ }), -/* 1675 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/* 1664 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Context": () => (/* binding */ Context), +/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), +/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), +/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(846); +/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__webpack_require__(1676)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); -} -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map -/***/ }), -/* 1676 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__webpack_require__(62)); -const tls_1 = __importDefault(__webpack_require__(145)); -const url_1 = __importDefault(__webpack_require__(63)); -const assert_1 = __importDefault(__webpack_require__(91)); -const debug_1 = __importDefault(__webpack_require__(1677)); -const agent_base_1 = __webpack_require__(1681); -const parse_proxy_response_1 = __importDefault(__webpack_require__(1687)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports["default"] = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map -/***/ }), -/* 1677 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1678); -} else { - module.exports = __webpack_require__(1680); -} +// TODO: Required until we drop support for Node v8 +const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); +const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); +/** Add node modules / packages to the event */ +class Context { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Context';} -/***/ }), -/* 1678 */ -/***/ ((module, exports, __webpack_require__) => { + /** + * @inheritDoc + */ + __init() {this.name = Context.id;} -/* eslint-env browser */ + /** + * Caches context so it's only evaluated once + */ -/** - * This is the web browser implementation of `debug()`. - */ + constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); + // + } -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor) { + addGlobalEventProcessor(event => this.addContext(event)); + } - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + /** Processes an event and adds context */ + async addContext(event) { + if (this._cachedContext === undefined) { + this._cachedContext = this._getContexts(); + } -/** - * Colors. - */ + const updatedContext = this._updateContext(await this._cachedContext); -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + event.contexts = { + ...event.contexts, + app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, + os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, + device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, + culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, + }; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + return event; + } -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + /** + * Updates the context with dynamic values that can change + */ + _updateContext(contexts) { + // Only update properties if they exist + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { + contexts.app.app_memory = process.memoryUsage().rss; + } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { + contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); + } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + return contexts; + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + /** + * Gets the contexts for the current environment + */ + async _getContexts() { + const contexts = {}; -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + if (this._options.os) { + contexts.os = await getOsContext(); + } - if (!this.useColors) { - return; - } + if (this._options.app) { + contexts.app = getAppContext(); + } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + if (this._options.device) { + contexts.device = getDeviceContext(this._options.device); + } - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + if (this._options.culture) { + const culture = getCultureContext(); - args.splice(lastC, 0, c); -} + if (culture) { + contexts.culture = culture; + } + } -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); + return contexts; + } +}Context.__initStatic(); /** - * Save `namespaces`. + * Returns the operating system context. * - * @param {String} namespaces - * @api private + * Based on the current platform, this uses a different strategy to provide the + * most accurate OS information. Since this might involve spawning subprocesses + * or accessing the file system, this should only be executed lazily and cached. + * + * - On macOS (Darwin), this will execute the `sw_vers` utility. The context + * has a `name`, `version`, `build` and `kernel_version` set. + * - On Linux, this will try to load a distribution release from `/etc` and set + * the `name`, `version` and `kernel_version` fields. + * - On all other platforms, only a `name` and `version` will be returned. Note + * that `version` might actually be the kernel version. */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +async function getOsContext() { + const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); + switch (platformId) { + case 'darwin': + return getDarwinInfo(); + case 'linux': + return getLinuxInfo(); + default: + return { + name: PLATFORM_NAMES[platformId] || platformId, + version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + }; + } } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function getCultureContext() { + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (typeof (process.versions ).icu !== 'string') { + // Node was built without ICU support + return; + } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + // Check that node was built with full Intl support. Its possible it was built without support for non-English + // locales which will make resolvedOptions inaccurate + // + // https://nodejs.org/api/intl.html#detecting-internationalization-support + const january = new Date(9e8); + const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); + if (spanish.format(january) === 'enero') { + const options = Intl.DateTimeFormat().resolvedOptions(); - return r; + return { + locale: options.locale, + timezone: options.timeZone, + }; + } + } catch (err) { + // + } + + return; +} + +function getAppContext() { + const app_memory = process.memoryUsage().rss; + const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); + + return { app_start_time, app_memory }; } /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Gets device information from os */ +function getDeviceContext(deviceOpt) { + const device = {}; -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). + // Hence, we only set boot time, if we get a valid uptime value. + // @see https://github.com/getsentry/sentry-javascript/issues/5856 + const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); + if (typeof uptime === 'number') { + device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); + } -module.exports = __webpack_require__(1679)(exports); + device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); -const {formatters} = module.exports; + if (deviceOpt === true || deviceOpt.memory) { + device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); + device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); + } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (deviceOpt === true || deviceOpt.cpu) { + const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); + if (cpuInfo && cpuInfo.length) { + const firstCpu = cpuInfo[0]; -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } + device.processor_count = cpuInfo.length; + device.cpu_description = firstCpu.model; + device.processor_frequency = firstCpu.speed; + } + } + + return device; +} + +/** Mapping of Node's platform names to actual OS names. */ +const PLATFORM_NAMES = { + aix: 'IBM AIX', + freebsd: 'FreeBSD', + openbsd: 'OpenBSD', + sunos: 'SunOS', + win32: 'Windows', }; +/** Linux version file to check for a distribution. */ -/***/ }), -/* 1679 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** Mapping of linux release files located in /etc to distributions. */ +const LINUX_DISTROS = [ + { name: 'fedora-release', distros: ['Fedora'] }, + { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, + { name: 'redhat_version', distros: ['Red Hat Linux'] }, + { name: 'SuSE-release', distros: ['SUSE Linux'] }, + { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, + { name: 'debian_version', distros: ['Debian'] }, + { name: 'debian_release', distros: ['Debian'] }, + { name: 'arch-release', distros: ['Arch Linux'] }, + { name: 'gentoo-release', distros: ['Gentoo Linux'] }, + { name: 'novell-release', distros: ['SUSE Linux'] }, + { name: 'alpine-release', distros: ['Alpine Linux'] }, +]; + +/** Functions to extract the OS version from Linux release files. */ +const LINUX_VERSIONS + = { + alpine: content => content, + arch: content => matchFirst(/distrib_release=(.*)/, content), + centos: content => matchFirst(/release ([^ ]+)/, content), + debian: content => content, + fedora: content => matchFirst(/release (..)/, content), + mint: content => matchFirst(/distrib_release=(.*)/, content), + red: content => matchFirst(/release ([^ ]+)/, content), + suse: content => matchFirst(/VERSION = (.*)\n/, content), + ubuntu: content => matchFirst(/distrib_release=(.*)/, content), +}; /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Executes a regular expression with one capture group. + * + * @param regex A regular expression to execute. + * @param text Content to execute the RegEx on. + * @returns The captured string if matched; otherwise undefined. */ +function matchFirst(regex, text) { + const match = regex.exec(text); + return match ? match[1] : undefined; +} -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1405); - createDebug.destroy = destroy; +/** Loads the macOS operating system context. */ +async function getDarwinInfo() { + // Default values that will be used in case no operating system information + // can be loaded. The default version is computed via heuristics from the + // kernel version, but the build ID is missing. + const darwinInfo = { + kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + name: 'Mac OS X', + version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, + }; - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); + try { + // We try to load the actual macOS version by executing the `sw_vers` tool. + // This tool should be available on every standard macOS installation. In + // case this fails, we stick with the values computed above. - /** - * The currently active debug mode names, and names to skip. - */ + const output = await new Promise((resolve, reject) => { + (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { + if (error) { + reject(error); + return; + } + resolve(stdout); + }); + }); - createDebug.names = []; - createDebug.skips = []; + darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); + darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); + darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); + } catch (e) { + // ignore + } - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + return darwinInfo; +} - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +/** Returns a distribution identifier to look up version callbacks. */ +function getLinuxDistroId(name) { + return name.split(' ')[0].toLowerCase(); +} - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +/** Loads the Linux operating system context. */ +async function getLinuxInfo() { + // By default, we cannot assume anything about the distribution or Linux + // version. `os.release()` returns the kernel version and we assume a generic + // "Linux" name, which will be replaced down below. + const linuxInfo = { + kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + name: 'Linux', + }; - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + try { + // We start guessing the distribution by listing files in the /etc + // directory. This is were most Linux distributions (except Knoppix) store + // release files with certain distribution-dependent meta data. We search + // for exactly one known file defined in `LINUX_DISTROS` and exit if none + // are found. In case there are more than one file, we just stick with the + // first one. + const etcFiles = await readDirAsync('/etc'); + const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); + if (!distroFile) { + return linuxInfo; + } - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; + // Once that file is known, load its contents. To make searching in those + // files easier, we lowercase the file contents. Since these files are + // usually quite small, this should not allocate too much memory and we only + // hold on to it for a very short amount of time. + const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); + const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + // Some Linux distributions store their release information in the same file + // (e.g. RHEL and Centos). In those cases, we scan the file for an + // identifier, that basically consists of the first word of the linux + // distribution name (e.g. "red" for Red Hat). In case there is no match, we + // just assume the first distribution in our list. + const { distros } = distroFile; + linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; - const self = debug; + // Based on the found distribution, we can now compute the actual version + // number. This is different for every distribution, so several strategies + // are computed in `LINUX_VERSIONS`. + const id = getLinuxDistroId(linuxInfo.name); + linuxInfo.version = LINUX_VERSIONS[id](contents); + } catch (e) { + // ignore + } - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + return linuxInfo; +} - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +//# sourceMappingURL=context.js.map - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/***/ }), +/* 1665 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "RequestData": () => (/* binding */ RequestData) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1669); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } +const DEFAULT_OPTIONS = { + include: { + cookies: true, + data: true, + headers: true, + ip: false, + query_string: true, + url: true, + user: { + id: true, + username: true, + email: true, + }, + }, + transactionNamingScheme: 'methodPath', +}; + +/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` + * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ +class RequestData { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'RequestData';} + + /** + * @inheritDoc + */ + __init() {this.name = RequestData.id;} + + /** + * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but + * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use + * something similar in browser-based SDKs in the future. + */ + + /** + * @inheritDoc + */ + constructor(options = {}) {;RequestData.prototype.__init.call(this); + this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; + this._options = { + ...DEFAULT_OPTIONS, + ...options, + include: { + // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in + // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) + method: true, + ...DEFAULT_OPTIONS.include, + ...options.include, + user: + options.include && typeof options.include.user === 'boolean' + ? options.include.user + : { + ...DEFAULT_OPTIONS.include.user, + // Unclear why TS still thinks `options.include.user` could be a boolean at this point + ...((options.include || {}).user ), + }, + }, + }; + } + + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + // Note: In the long run, most of the logic here should probably move into the request data utility functions. For + // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. + // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once + // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) + const { transactionNamingScheme } = this._options; - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + addGlobalEventProcessor(event => { + const hub = getCurrentHub(); + const self = hub.getIntegration(RequestData); - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + const { sdkProcessingMetadata = {} } = event; + const req = sdkProcessingMetadata.request; - return debug; - } + // If the globally installed instance of this integration isn't associated with the current hub, `self` will be + // undefined + if (!self || !req) { + return event; + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + // The Express request handler takes a similar `include` option to that which can be passed to this integration. + // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this + // integration, so that all of this passing and conversion isn't necessary + const addRequestDataOptions = + sdkProcessingMetadata.requestDataOptionsFromExpressHandler || + sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || + convertReqDataIntegrationOptsToAddReqDataOpts(this._options); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; + const processedEvent = this._addRequestData(event, req, addRequestDataOptions); - createDebug.names = []; - createDebug.skips = []; + // Transaction events already have the right `transaction` value + if (event.type === 'transaction' || transactionNamingScheme === 'handler') { + return processedEvent; + } - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` + // value with a high-quality one + const reqWithTransaction = req ; + const transaction = reqWithTransaction._sentryTransaction; + if (transaction) { + // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to + // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential + // to break things like alert rules.) + const shouldIncludeMethodInTransactionName = + getSDKName(hub) === 'sentry.javascript.nextjs' + ? transaction.name.startsWith('/api') + : transactionNamingScheme !== 'path'; - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { + path: true, + method: shouldIncludeMethodInTransactionName, + customRoute: transaction.name, + }); - namespaces = split[i].replace(/\*/g, '.*?'); + processedEvent.transaction = transactionValue; + } - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + return processedEvent; + }); + } +} RequestData.__initStatic(); - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +/** Convert this integration's options to match what `addRequestDataToEvent` expects */ +/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ +function convertReqDataIntegrationOptsToAddReqDataOpts( + integrationOptions, +) { + const { + transactionNamingScheme, + include: { ip, user, ...requestOptions }, + } = integrationOptions; - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + const requestIncludeKeys = []; + for (const [key, value] of Object.entries(requestOptions)) { + if (value) { + requestIncludeKeys.push(key); + } + } - let i; - let len; + let addReqDataUserOpt; + if (user === undefined) { + addReqDataUserOpt = true; + } else if (typeof user === 'boolean') { + addReqDataUserOpt = user; + } else { + const userIncludeKeys = []; + for (const [key, value] of Object.entries(user)) { + if (value) { + userIncludeKeys.push(key); + } + } + addReqDataUserOpt = userIncludeKeys; + } - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + return { + include: { + ip, + user: addReqDataUserOpt, + request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, + transaction: transactionNamingScheme, + }, + }; +} - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +function getSDKName(hub) { + try { + // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to + // write out a long chain of `a && a.b && a.b.c && ...` + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return hub.getClient().getOptions()._metadata.sdk.name; + } catch (err) { + // In theory we should never get here + return undefined; + } +} - return false; - } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +//# sourceMappingURL=requestdata.js.map - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } +/***/ }), +/* 1666 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - createDebug.enable(createDebug.load()); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), +/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), +/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), +/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1668); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1621); +/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); - return createDebug; -} -module.exports = setup; -/***/ }), -/* 1680 */ -/***/ ((module, exports, __webpack_require__) => { + +const DEFAULT_INCLUDES = { + ip: false, + request: true, + transaction: true, + user: true, +}; +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; /** - * Module dependencies. + * Options deciding what parts of the request to use when enhancing an event */ -const tty = __webpack_require__(1407); -const util = __webpack_require__(64); - /** - * This is the Node.js implementation of `debug()`. + * Sets parameterized route as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +function addRequestDataToTransaction(transaction, req) { + if (!transaction) return; + if (!transaction.metadata.source || transaction.metadata.source === 'url') { + // Attempt to grab a parameterized route off of the request + transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); + } + transaction.setData('url', req.originalUrl || req.url); + if (req.baseUrl) { + transaction.setData('baseUrl', req.baseUrl); + } + transaction.setData('query', extractQueryParams(req)); +} /** - * Colors. + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. + * + * Additionally, this function determines and returns the transaction name source + * + * eg. GET /mountpoint/user/:id + * + * @param req A request object + * @param options What to include in the transaction name (method, path, or a custom route name to be + * used instead of the request's route) + * + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */ +function extractPathForTransaction( + req, + options = {}, +) { + const method = req.method && req.method.toUpperCase(); -exports.colors = [6, 2, 3, 4, 5, 1]; + let path = ''; + let source = 'url'; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1408); + // Check to see if there's a parameterized route we can use (as there is in Express) + if (options.customRoute || req.route) { + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; + source = 'route'; + } - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + // Otherwise, just take the original URL + else if (req.originalUrl || req.url) { + path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); + } + + let name = ''; + if (options.method && method) { + name += method; + } + if (options.method && options.path) { + name += ' '; + } + if (options.path && path) { + name += path; + } + + return [name, source]; +} + +/** JSDoc */ +function extractTransaction(req, type) { + switch (type) { + case 'path': { + return extractPathForTransaction(req, { path: true })[0]; + } + case 'handler': { + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + } + case 'methodPath': + default: { + return extractPathForTransaction(req, { path: true, method: true })[0]; + } + } +} + +/** JSDoc */ +function extractUserData( + user + +, + keys, +) { + const extractedUser = {}; + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + + attributes.forEach(key => { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + + return extractedUser; } /** - * Build up the default `inspectOpts` object from the environment variables. + * Normalize data from the request object * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param req The request object from which to extract data + * @param options.include An optional array of keys to include in the normalized data. Defaults to + * DEFAULT_REQUEST_INCLUDES if not provided. + * @param options.deps Injected, platform-specific dependencies + * + * @returns An object containing normalized request data */ +function extractRequestData( + req, + options -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +, +) { + const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; + const requestData = {}; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } + // headers: + // node, express, koa, nextjs: req.headers + const headers = (req.headers || {}) - obj[prop] = val; - return obj; -}, {}); +; + // method: + // node, express, koa, nextjs: req.method + const method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + const host = req.hostname || req.host || headers.host || '<no host>'; + // protocol: + // node, nextjs: <n/a> + // express, koa: req.protocol + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + const originalUrl = req.originalUrl || req.url || ''; + // absolute url + const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; + include.forEach(key => { + switch (key) { + case 'headers': { + requestData.headers = headers; -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + // Remove the Cookie header in case cookie data should not be included in the event + if (!include.includes('cookies')) { + delete (requestData.headers ).cookie; + } -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); + break; + } + case 'method': { + requestData.method = method; + break; + } + case 'url': { + requestData.url = absoluteUrl; + break; + } + case 'cookies': { + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can + // come off in v8 + req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; + break; + } + case 'query_string': { + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = extractQueryParams(req); + break; + } + case 'data': { + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); + } + break; + } + default: { + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = (req )[key]; + } + } + } + }); + + return requestData; } /** - * Adds ANSI color escape codes if enabled. + * Add data from the given request to the given event * - * @api public + * @param event The event to which the request data will be added + * @param req Request object + * @param options.include Flags to control what data is included + * + * @returns The mutated `Event` object */ +function addRequestDataToEvent( + event, + req, + options, +) { + const include = { + ...DEFAULT_INCLUDES, + ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), + }; -function formatArgs(args) { - const {namespace: name, useColors} = this; + if (include.request) { + const extractedRequestData = Array.isArray(include.request) + ? extractRequestData(req, { include: include.request }) + : extractRequestData(req); - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + event.request = { + ...event.request, + ...extractedRequestData, + }; + } - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } + if (include.user) { + const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; + + if (Object.keys(extractedUser).length) { + event.user = { + ...event.user, + ...extractedUser, + }; + } + } + + // client ip: + // node, nextjs: req.socket.remoteAddress + // express, koa: req.ip + if (include.ip) { + const ip = req.ip || (req.socket && req.socket.remoteAddress); + if (ip) { + event.user = { + ...event.user, + ip_address: ip, + }; + } + } + + if (include.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, include.transaction); + } + + return event; } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; +function extractQueryParams(req) { + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + let originalUrl = req.originalUrl || req.url || ''; + + if (!originalUrl) { + return; + } + + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. + if (originalUrl.startsWith('/')) { + originalUrl = `http://dogs.are.great${originalUrl}`; + } + + return ( + req.query || + (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node + url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || + undefined + ); } + +//# sourceMappingURL=requestdata.js.map + + +/***/ }), +/* 1667 */ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Module exports. + * @public */ -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +exports.parse = parse; +exports.serialize = serialize; /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module variables. + * @private */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} + +var decode = decodeURIComponent; +var encode = encodeURIComponent; /** - * Load `namespaces`. + * RegExp to match field-content in RFC 7230 sec 3.2 * - * @return {String} returns the previously persisted debug modes - * @api private + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF */ -function load() { - return process.env.DEBUG; -} +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** - * Init logic for `debug` instances. + * Parse a cookie header. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public */ -function init(debug) { - debug.inspectOpts = {}; +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + var obj = {} + var opt = options || {}; + var pairs = str.split(';') + var dec = opt.decode || decode; -module.exports = __webpack_require__(1679)(exports); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var index = pair.indexOf('=') -const {formatters} = module.exports; + // skip things that don't look like key=value + if (index < 0) { + continue; + } -/** - * Map %o to `util.inspect()`, all on a single line. - */ + var key = pair.substring(0, index).trim() -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + // only assign once + if (undefined == obj[key]) { + var val = pair.substring(index + 1, pair.length).trim() + + // quoted values + if (val[0] === '"') { + val = val.slice(1, -1) + } + + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public */ -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } -/***/ }), -/* 1681 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } -"use strict"; + var value = enc(val); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __webpack_require__(250); -const debug_1 = __importDefault(__webpack_require__(1682)); -const promisify_1 = __importDefault(__webpack_require__(1686)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); -} -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map -/***/ }), -/* 1682 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + str += '; Domain=' + opt.domain; + } -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1683); -} else { - module.exports = __webpack_require__(1685); -} + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + str += '; Path=' + opt.path; + } -/***/ }), -/* 1683 */ -/***/ ((module, exports, __webpack_require__) => { + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } -/* eslint-env browser */ + str += '; Expires=' + opt.expires.toUTCString(); + } -/** - * This is the web browser implementation of `debug()`. - */ + if (opt.httpOnly) { + str += '; HttpOnly'; + } -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + if (opt.secure) { + str += '; Secure'; + } - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; -/** - * Colors. - */ + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; + return str; +} /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Try decoding a string using a decoding function. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {string} str + * @param {function} decode + * @private */ -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +/***/ }), +/* 1668 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), +/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), +/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) +/* harmony export */ }); /** - * Colorize log arguments if enabled. - * - * @api public + * Parses string form of URL into an object + * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B + * // intentionally using regex and not <a/> href parsing trick because React Native and other + * // environments where DOM might not be available + * @returns parsed URL object */ +function parseUrl(url) -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } + { + if (!url) { + return {}; + } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); + const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + if (!match) { + return {}; + } - args.splice(lastC, 0, c); + // coerce to undefined values to empty string so we don't get 'undefined' + const query = match[6] || ''; + const fragment = match[8] || ''; + return { + host: match[4], + path: match[5], + protocol: match[2], + relative: match[5] + query + fragment, // everything minus origin + }; } /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. + * Strip the query string and fragment off of a given URL or path (if present) * - * @api public + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment */ -exports.log = console.debug || console.log || (() => {}); +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; +} /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Returns number of URL segments of a passed string URL. */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function getNumberOfUrlSegments(url) { + // split at '/' or at '\/' to split regex urls correctly + return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } +//# sourceMappingURL=url.js.map - return r; + +/***/ }), +/* 1669 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), +/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), +/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) +/* harmony export */ }); +/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1624); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1621); +/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); + + + + + +const DEFAULT_INCLUDES = { + ip: false, + request: true, + transaction: true, + user: true, +}; +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; + +/** + * Sets parameterized route as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request + */ +function addRequestDataToTransaction( + transaction, + req, + deps, +) { + if (!transaction) return; + if (!transaction.metadata.source || transaction.metadata.source === 'url') { + // Attempt to grab a parameterized route off of the request + transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); + } + transaction.setData('url', req.originalUrl || req.url); + if (req.baseUrl) { + transaction.setData('baseUrl', req.baseUrl); + } + transaction.setData('query', extractQueryParams(req, deps)); } /** - * Localstorage attempts to return the localstorage. + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * Additionally, this function determines and returns the transaction name source * - * @return {LocalStorage} - * @api private + * eg. GET /mountpoint/user/:id + * + * @param req A request object + * @param options What to include in the transaction name (method, path, or a custom route name to be + * used instead of the request's route) + * + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */ +function extractPathForTransaction( + req, + options = {}, +) { + const method = req.method && req.method.toUpperCase(); -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + let path = ''; + let source = 'url'; + + // Check to see if there's a parameterized route we can use (as there is in Express) + if (options.customRoute || req.route) { + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; + source = 'route'; + } + + // Otherwise, just take the original URL + else if (req.originalUrl || req.url) { + path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); + } + + let name = ''; + if (options.method && method) { + name += method; + } + if (options.method && options.path) { + name += ' '; + } + if (options.path && path) { + name += path; + } + + return [name, source]; } -module.exports = __webpack_require__(1684)(exports); +/** JSDoc */ +function extractTransaction(req, type) { + switch (type) { + case 'path': { + return extractPathForTransaction(req, { path: true })[0]; + } + case 'handler': { + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + } + case 'methodPath': + default: { + return extractPathForTransaction(req, { path: true, method: true })[0]; + } + } +} -const {formatters} = module.exports; +/** JSDoc */ +function extractUserData( + user + +, + keys, +) { + const extractedUser = {}; + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + + attributes.forEach(key => { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + + return extractedUser; +} /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + * Normalize data from the request object, accounting for framework differences. + * + * @param req The request object from which to extract data + * @param options.include An optional array of keys to include in the normalized data. Defaults to + * DEFAULT_REQUEST_INCLUDES if not provided. + * @param options.deps Injected, platform-specific dependencies + * @returns An object containing normalized request data */ +function extractRequestData( + req, + options -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; +, +) { + const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; + const requestData = {}; + // headers: + // node, express, koa, nextjs: req.headers + const headers = (req.headers || {}) -/***/ }), -/* 1684 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +; + // method: + // node, express, koa, nextjs: req.method + const method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + const host = req.hostname || req.host || headers.host || '<no host>'; + // protocol: + // node, nextjs: <n/a> + // express, koa: req.protocol + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + const originalUrl = req.originalUrl || req.url || ''; + // absolute url + const absoluteUrl = `${protocol}://${host}${originalUrl}`; + include.forEach(key => { + switch (key) { + case 'headers': { + requestData.headers = headers; + break; + } + case 'method': { + requestData.method = method; + break; + } + case 'url': { + requestData.url = absoluteUrl; + break; + } + case 'cookies': { + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can + // come off in v8 + req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; + break; + } + case 'query_string': { + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = extractQueryParams(req, deps); + break; + } + case 'data': { + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); + } + break; + } + default: { + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = (req )[key]; + } + } + } + }); + return requestData; +} /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Options deciding what parts of the request to use when enhancing an event */ -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1405); - createDebug.destroy = destroy; +/** + * Add data from the given request to the given event + * + * @param event The event to which the request data will be added + * @param req Request object + * @param options.include Flags to control what data is included + * @param options.deps Injected platform-specific dependencies + * @hidden + */ +function addRequestDataToEvent( + event, + req, + options, +) { + const include = { + ...DEFAULT_INCLUDES, + ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), + }; - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); + if (include.request) { + const extractedRequestData = Array.isArray(include.request) + ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) + : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); - /** - * The currently active debug mode names, and names to skip. - */ + event.request = { + ...event.request, + ...extractedRequestData, + }; + } - createDebug.names = []; - createDebug.skips = []; + if (include.user) { + const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + if (Object.keys(extractedUser).length) { + event.user = { + ...event.user, + ...extractedUser, + }; + } + } - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + // client ip: + // node, nextjs: req.socket.remoteAddress + // express, koa: req.ip + if (include.ip) { + const ip = req.ip || (req.socket && req.socket.remoteAddress); + if (ip) { + event.user = { + ...event.user, + ip_address: ip, + }; + } + } - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (include.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, include.transaction); + } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + return event; +} - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +function extractQueryParams( + req, + deps, +) { + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + let originalUrl = req.originalUrl || req.url || ''; - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + if (!originalUrl) { + return; + } - const self = debug; + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. + if (originalUrl.startsWith('/')) { + originalUrl = `http://dogs.are.great${originalUrl}`; + } - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + return ( + req.query || + (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node + (deps && deps.url && deps.url.parse(originalUrl).query) || + undefined + ); +} - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +//# sourceMappingURL=requestdata.js.map - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/***/ }), +/* 1670 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getModule": () => (/* binding */ getModule) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1671); - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. +/** normalizes Windows paths */ +function normalizePath(path) { + return path + .replace(/^[A-Z]:/, '') // remove Windows-style prefix + .replace(/\\/g, '/'); // replace all `\` instances with `/` +} - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } +/** Gets the module from a filename */ +function getModule(filename) { + if (!filename) { + return; + } - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + const normalizedFilename = normalizePath(filename); - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + // We could use optional chaining here but webpack does like that mixed with require + const base = normalizePath( + `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, + ); - return debug; - } + // It's specifically a module + const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); + let n = path.lastIndexOf('/node_modules/'); + if (n > -1) { + // /node_modules/ is 14 chars + return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; + } + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + n = `${path}/`.lastIndexOf(base, 0); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; + if (n === 0) { + let moduleName = path.substr(base.length).replace(/\//g, '.'); + if (moduleName) { + moduleName += ':'; + } + moduleName += file; + return moduleName; + } + return file; +} - createDebug.names = []; - createDebug.skips = []; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +//# sourceMappingURL=module.js.map - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - namespaces = split[i].replace(/\*/g, '.*?'); +/***/ }), +/* 1671 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "basename": () => (/* binding */ basename), +/* harmony export */ "dirname": () => (/* binding */ dirname), +/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), +/* harmony export */ "join": () => (/* binding */ join), +/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), +/* harmony export */ "relative": () => (/* binding */ relative), +/* harmony export */ "resolve": () => (/* binding */ resolve) +/* harmony export */ }); +// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript +// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +/** JSDoc */ +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + let up = 0; + for (let i = parts.length - 1; i >= 0; i--) { + const last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } - let i; - let len; + return parts; +} - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; +/** JSDoc */ +function splitPath(filename) { + const parts = splitPathRe.exec(filename); + return parts ? parts.slice(1) : []; +} - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +// path.resolve([from ...], to) +// posix version +/** JSDoc */ +function resolve(...args) { + let resolvedPath = ''; + let resolvedAbsolute = false; - return false; - } + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + // Skip empty entries + if (!path) { + continue; + } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charAt(0) === '/'; + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray( + resolvedPath.split('/').filter(p => !!p), + !resolvedAbsolute, + ).join('/'); + + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; +} + +/** JSDoc */ +function trim(arr) { + let start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') { + break; + } + } + + let end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') { + break; + } + } + + if (start > end) { + return []; + } + return arr.slice(start, end - start + 1); +} + +// path.relative(from, to) +// posix version +/** JSDoc */ +function relative(from, to) { + /* eslint-disable no-param-reassign */ + from = resolve(from).substr(1); + to = resolve(to).substr(1); + /* eslint-enable no-param-reassign */ + + const fromParts = trim(from.split('/')); + const toParts = trim(to.split('/')); + + const length = Math.min(fromParts.length, toParts.length); + let samePartsLength = length; + for (let i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + let outputParts = []; + for (let i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } - createDebug.enable(createDebug.load()); + outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return createDebug; + return outputParts.join('/'); } -module.exports = setup; +// path.normalize(path) +// posix version +/** JSDoc */ +function normalizePath(path) { + const isPathAbsolute = isAbsolute(path); + const trailingSlash = path.substr(-1) === '/'; + // Normalize the path + let normalizedPath = normalizeArray( + path.split('/').filter(p => !!p), + !isPathAbsolute, + ).join('/'); -/***/ }), -/* 1685 */ -/***/ ((module, exports, __webpack_require__) => { + if (!normalizedPath && !isPathAbsolute) { + normalizedPath = '.'; + } + if (normalizedPath && trailingSlash) { + normalizedPath += '/'; + } -/** - * Module dependencies. - */ + return (isPathAbsolute ? '/' : '') + normalizedPath; +} -const tty = __webpack_require__(1407); -const util = __webpack_require__(64); +// posix version +/** JSDoc */ +function isAbsolute(path) { + return path.charAt(0) === '/'; +} -/** - * This is the Node.js implementation of `debug()`. - */ +// posix version +/** JSDoc */ +function join(...args) { + return normalizePath(args.join('/')); +} -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +/** JSDoc */ +function dirname(path) { + const result = splitPath(path); + const root = result[0]; + let dir = result[1]; -/** - * Colors. - */ + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } -exports.colors = [6, 2, 3, 4, 5, 1]; + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1408); + return root + dir; +} - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. +/** JSDoc */ +function basename(path, ext) { + let f = splitPath(path)[2]; + if (ext && f.substr(ext.length * -1) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; } -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +//# sourceMappingURL=path.js.map - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; -}, {}); +/***/ }), +/* 1672 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), +/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), +/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1609); -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -function formatArgs(args) { - const {namespace: name, useColors} = this; +/** Options for the InboundFilters integration */ - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; +/** Inbound filters configurable by the user */ +class InboundFilters { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'InboundFilters';} - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + /** + * @inheritDoc + */ + __init() {this.name = InboundFilters.id;} -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} + constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + const eventProcess = (event) => { + const hub = getCurrentHub(); + if (hub) { + const self = hub.getIntegration(InboundFilters); + if (self) { + const client = hub.getClient(); + const clientOptions = client ? client.getOptions() : {}; + const options = _mergeOptions(self._options, clientOptions); + return _shouldDropEvent(event, options) ? null : event; + } + } + return event; + }; -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); + eventProcess.id = this.name; + addGlobalEventProcessor(eventProcess); + } +} InboundFilters.__initStatic(); + +/** JSDoc */ +function _mergeOptions( + internalOptions = {}, + clientOptions = {}, +) { + return { + allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], + denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], + ignoreErrors: [ + ...(internalOptions.ignoreErrors || []), + ...(clientOptions.ignoreErrors || []), + ...DEFAULT_IGNORE_ERRORS, + ], + ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, + }; } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } +/** JSDoc */ +function _shouldDropEvent(event, options) { + if (options.ignoreInternal && _isSentryError(event)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return true; + } + if (_isIgnoredError(event, options.ignoreErrors)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, + ); + return true; + } + if (_isDeniedUrl(event, options.denyUrls)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + if (!_isAllowedUrl(event, options.allowUrls)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + return false; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +function _isIgnoredError(event, ignoreErrors) { + if (!ignoreErrors || !ignoreErrors.length) { + return false; + } -function load() { - return process.env.DEBUG; + return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); } -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +function _isDeniedUrl(event, denyUrls) { + // TODO: Use Glob instead? + if (!denyUrls || !denyUrls.length) { + return false; + } + const url = _getEventFilterUrl(event); + return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); +} -function init(debug) { - debug.inspectOpts = {}; +function _isAllowedUrl(event, allowUrls) { + // TODO: Use Glob instead? + if (!allowUrls || !allowUrls.length) { + return true; + } + const url = _getEventFilterUrl(event); + return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); +} - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } +function _getPossibleEventMessages(event) { + if (event.message) { + return [event.message]; + } + if (event.exception) { + try { + const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; + return [`${value}`, `${type}: ${value}`]; + } catch (oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return []; + } + } + return []; } -module.exports = __webpack_require__(1684)(exports); +function _isSentryError(event) { + try { + // @ts-ignore can't be a sentry error if undefined + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return event.exception.values[0].type === 'SentryError'; + } catch (e) { + // ignore + } + return false; +} -const {formatters} = module.exports; +function _getLastValidUrl(frames = []) { + for (let i = frames.length - 1; i >= 0; i--) { + const frame = frames[i]; -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { + return frame.filename || null; + } + } -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + return null; +} -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ +function _getEventFilterUrl(event) { + try { + let frames; + try { + // @ts-ignore we only care about frames if the whole thing here is defined + frames = event.exception.values[0].stacktrace.frames; + } catch (e) { + // ignore + } + return frames ? _getLastValidUrl(frames) : null; + } catch (oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return null; + } +} -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + +//# sourceMappingURL=inboundfilters.js.map /***/ }), -/* 1686 */ -/***/ ((__unused_webpack_module, exports) => { +/* 1673 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); -Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); + +let originalFunctionToString; + +/** Patch toString calls to return proper name for wrapped functions */ +class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'FunctionToString';} + + /** + * @inheritDoc + */ + __init() {this.name = FunctionToString.id;} + + /** + * @inheritDoc + */ + setupOnce() { + // eslint-disable-next-line @typescript-eslint/unbound-method + originalFunctionToString = Function.prototype.toString; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Function.prototype.toString = function ( ...args) { + const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; + return originalFunctionToString.apply(context, args); }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map + } +} FunctionToString.__initStatic(); -/***/ }), -/* 1687 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; +//# sourceMappingURL=functiontostring.js.map -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__webpack_require__(1677)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); - } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); -} -exports["default"] = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map /***/ }), -/* 1688 */ +/* 1674 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) +/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) /* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); + + + +/** A class object that can instantiate Client objects. */ + /** - * Polyfill for the nullish coalescing operator (`??`). - * - * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the - * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. - * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. * - * @param lhs The value of the expression to the left of the `??` - * @param rhsFn A function returning the value of the expression to the right of the `??` - * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. */ -function _nullishCoalesce(lhs, rhsFn) { - // by checking for loose equality to `null`, we catch both `null` and `undefined` - return lhs != null ? lhs : rhsFn(); -} +function initAndBind( + clientClass, + options, +) { + if (options.debug === true) { + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); + } else { + // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped + // eslint-disable-next-line no-console + console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + } + } + const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); + const scope = hub.getScope(); + if (scope) { + scope.update(options.initialScope); + } -// Sucrase version: -// function _nullishCoalesce(lhs, rhsFn) { -// if (lhs != null) { -// return lhs; -// } else { -// return rhsFn(); -// } -// } + const client = new clientClass(options); + hub.bindClient(client); +} -//# sourceMappingURL=_nullishCoalesce.js.map +//# sourceMappingURL=sdk.js.map /***/ }), -/* 1689 */ +/* 1675 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "close": () => (/* binding */ close), -/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), -/* harmony export */ "flush": () => (/* binding */ flush), -/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), -/* harmony export */ "init": () => (/* binding */ init), -/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), -/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) +/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1711); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1712); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1670); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1713); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1662); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1644); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1665); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1690); -/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1709); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1673); -/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1691); -/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1693); -/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1696); -/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1698); -/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1700); -/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1703); -/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1702); -/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1704); -/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1699); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1674); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +/** + * Recursively read the contents of a directory. + * + * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this + * directory. + * @returns Array holding all relative paths + */ +function deepReadDirSync(targetDir) { + const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); + if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); + } + if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); + } + // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it + // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve + // the difference between `targetDirAbsPath` and `currentDirAbsPath`. + const deepReadCurrentDir = (currentDirAbsPath) => { + return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { + const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); + if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { + return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; + } + return [...absPaths, itemAbsPath]; + }, []); + }; + return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); +} +//# sourceMappingURL=utils.js.map +/***/ }), +/* 1676 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), +/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), +/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), +/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), +/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1616); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1678); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1656); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1669); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1611); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1666); +/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); +/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1677); -/* eslint-disable max-lines */ -const defaultIntegrations = [ - // Common - new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), - new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), - // Native Wrappers - new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), - new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), - // Global Handlers - new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), - new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), - // Event Info - new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), - new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), - new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), - new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), - // Misc - new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), -]; + + +/* eslint-disable @typescript-eslint/no-explicit-any */ /** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link NodeOptions} for documentation on configuration options. + * Express-compatible tracing handler. + * @see Exposed as `Handlers.tracingHandler` */ -function init(options = {}) { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); - const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : [ - ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), - ...autoloadedIntegrations, - ]; +function tracingHandler() - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } + { + return function sentryTracingMiddleware( + req, + res, + next, + ) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; + if ( + !options || + options.instrumenter !== 'sentry' || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' + ) { + return next(); } - } - if (options.release === undefined) { - const detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; + // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a + // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. + if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( + 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + + 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', + ); + return next(); } - } - - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } + // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) + const traceparentData = + req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); + const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); + const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); - if (options.instrumenter === undefined) { - options.instrumenter = 'sentry'; - } + const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); + const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( + { + name, + op: 'http.server', + ...traceparentData, + metadata: { + dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, + // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become + // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the + // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to + // be sure + request: req, + source, + }, + }, + // extra context passed to the tracesSampler + { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, + ); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); - } + // We put the transaction on the scope so users can attach children to it + hub.configureScope(scope => { + scope.setSpan(transaction); + }); - // TODO(v7): Refactor this to reduce the logic above - const clientOptions = { - ...options, - stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), - integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), - transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, - }; + // We also set __sentry_transaction on the response so people can grab the transaction there to add + // spans to it later. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).__sentry_transaction = transaction; - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); + res.once('finish', () => { + // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction + // closes + setImmediate(() => { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); + transaction.setHttpStatus(res.statusCode); + transaction.finish(); + }); + }); - if (options.autoSessionTracking) { - startSessionTracking(); - } + next(); + }; } /** - * This is the getter for lastEventId. + * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the + * `AddRequestDataToEventOptions` interface. * - * @returns The last event id of a captured event. + * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. */ -function lastEventId() { - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); -} +function convertReqHandlerOptsToAddReqDataOpts( + reqHandlerOptions = {}, +) { + let addRequestDataOptions; -/** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function flush(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.flush(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); - return Promise.resolve(false); -} + if ('include' in reqHandlerOptions) { + addRequestDataOptions = { include: reqHandlerOptions.include }; + } else { + // eslint-disable-next-line deprecation/deprecation + const { ip, request, transaction, user } = reqHandlerOptions ; -/** - * Call `close()` on the current client, if there is one. See {@link Client.close}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function close(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.close(timeout); + if (ip || request || transaction || user) { + addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; + } } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return Promise.resolve(false); + + return addRequestDataOptions; } /** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - const clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; +function requestHandler( + options, +) { + // TODO (v8): Get rid of this + const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); + + const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + const client = currentHub.getClient(); + // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the + // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode + if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + client.initSessionFlusher(); + + // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode + const scope = currentHub.getScope(); + if (scope && scope.getSession()) { + scope.setSession(); + } } - return false; + + return function sentryRequestMiddleware( + req, + res, + next, + ) { + if (options && options.flushTimeout && options.flushTimeout > 0) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _end = res.end; + res.end = function (chunk, encoding, cb) { + void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) + .then(() => { + _end.call(this, chunk, encoding, cb); + }) + .then(null, e => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); + _end.call(this, chunk, encoding, cb); + }); + }; + } + const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); + local.add(req); + local.add(res); + + local.run(() => { + const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + + currentHub.configureScope(scope => { + scope.setSDKProcessingMetadata({ + request: req, + // TODO (v8): Stop passing this + requestDataOptionsFromExpressHandler: requestDataOptions, + }); + + const client = currentHub.getClient(); + if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + const scope = currentHub.getScope(); + if (scope) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope.setRequestSession({ status: 'ok' }); + } + } + }); + + res.once('finish', () => { + const client = currentHub.getClient(); + if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + setImmediate(() => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (client && (client )._captureRequestSession) { + // Calling _captureRequestSession to capture request session at the end of the request by incrementing + // the correct SessionAggregates bucket i.e. crashed, errored or exited + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (client )._captureRequestSession(); + } + }); + } + }); + next(); + }); + }; } -/** - * Returns a release dynamically from environment variables. - */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - - // This supports the variable that sentry-webpack-plugin injects - if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { - return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; - } +/** JSDoc */ - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback - ); +/** JSDoc */ +function getStatusCodeFromResponse(error) { + const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); + return statusCode ? parseInt(statusCode , 10) : 500; } -/** Node.js stack parser */ -const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); +/** Returns true if response code is internal server error */ +function defaultShouldHandleError(error) { + const status = getStatusCodeFromResponse(error); + return status >= 500; +} /** - * Enable automatic Session Tracking for the node process. + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` */ -function startSessionTracking() { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', () => { - const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); - const terminalStates = ['exited', 'crashed']; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) hub.endSession(); - }); -} - - -//# sourceMappingURL=sdk.js.map - +function errorHandler(options -/***/ }), -/* 1690 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +) -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), -/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), -/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), -/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), -/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), -/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), -/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), -/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), -/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) -/* harmony export */ }); -/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1691); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1693); -/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1696); -/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1698); -/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1699); -/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1702); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1700); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1703); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1704); + { + return function sentryErrorMiddleware( + error, + _req, + res, + next, + ) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; + if (shouldHandleError(error)) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { + // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, + // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't + // hurt to be sure + _scope.setSDKProcessingMetadata({ request: _req }); + // For some reason we need to set the transaction on the scope again + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const transaction = (res ).__sentry_transaction ; + if (transaction && _scope.getSpan() === undefined) { + _scope.setSpan(transaction); + } + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); + if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the + // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only + // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be + // running in SessionAggregates mode + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; + if (isSessionAggregatesMode) { + const requestSession = _scope.getRequestSession(); + // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a + // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within + // the bounds of a request, and if so the status is updated + if (requestSession && requestSession.status !== undefined) { + requestSession.status = 'crashed'; + } + } + } + const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).sentry = eventId; + next(error); + }); + return; + } + next(error); + }; +} +// TODO (v8 / #5257): Remove this +// eslint-disable-next-line deprecation/deprecation +; -//# sourceMappingURL=index.js.map +//# sourceMappingURL=handlers.js.map /***/ }), -/* 1691 */ +/* 1677 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* binding */ Console) +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), +/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1692); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); - - - - -/** Console module integration */ -class Console {constructor() { Console.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Console';} +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); - /** - * @inheritDoc - */ - __init() {this.name = Console.id;} - /** - * @inheritDoc - */ - setupOnce() { - for (const level of ['debug', 'info', 'warn', 'error', 'log']) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); - } - } -} Console.__initStatic(); +/** + * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. + */ /** - * Wrapper function that'll be used for every console level + * Normalizes data from the request object, accounting for framework differences. + * + * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. + * + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. + * @returns An object containing normalized request data */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); +function extractRequestData(req, keys) { + return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); +} - /* eslint-disable prefer-rest-params */ - return function () { - if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( - { - category: 'console', - level: sentryLevel, - message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), - }, - { - input: [...arguments], - level, - }, - ); - } +/** + * Options deciding what parts of the request to use when enhancing an event + * + * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use + * `AddRequestDataToEventOptions` in `@sentry/utils` instead. + */ - originalConsoleMethod.apply(this, arguments); - }; - /* eslint-enable prefer-rest-params */ - }; +/** + * Enriches passed event with request data. + * + * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. + * + * @param event Will be mutated and enriched with req data + * @param req Request object + * @param options object containing flags to enable functionality + * @hidden + */ +function parseRequest(event, req, options = {}) { + return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); } -//# sourceMappingURL=console.js.map +//# sourceMappingURL=requestDataDeprecated.js.map /***/ }), -/* 1692 */ +/* 1678 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), -/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), -/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) +/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), +/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) /* harmony export */ }); -// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either -// -// a) moving `validSeverityLevels` to `@sentry/types`, -// b) moving the`SeverityLevel` type here, or -// c) importing `validSeverityLevels` from here into `@sentry/types`. -// -// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would -// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the -// type, reminding anyone who changes it to change this list also, will have to do. - -const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; +const TRACEPARENT_REGEXP = new RegExp( + '^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$', // whitespace +); /** - * Converts a string-based level into a member of the deprecated {@link Severity} enum. + * Extract transaction context data from a `sentry-trace` header. * - * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. + * @param traceparent Traceparent string * - * @param level String representation of Severity - * @returns Severity + * @returns Object containing data from the header, or undefined if traceparent string is malformed */ -function severityFromString(level) { - return severityLevelFromString(level) ; -} +function extractTraceparentData(traceparent) { + const matches = traceparent.match(TRACEPARENT_REGEXP); -/** - * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. - * - * @param level String representation of desired `SeverityLevel`. - * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. - */ -function severityLevelFromString(level) { - return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; + if (!traceparent || !matches) { + // empty string or no matches is invalid traceparent data + return undefined; + } + + let parentSampled; + if (matches[3] === '1') { + parentSampled = true; + } else if (matches[3] === '0') { + parentSampled = false; + } + + return { + traceId: matches[1], + parentSampled, + parentSpanId: matches[2], + }; } -//# sourceMappingURL=severity.js.map +//# sourceMappingURL=tracing.js.map /***/ }), -/* 1693 */ +/* 1679 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Http": () => (/* binding */ Http) +/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), +/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1648); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1695); -/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1694); +/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1673); +/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1672); +//# sourceMappingURL=index.js.map +/***/ }), +/* 1680 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); +// @ts-check +const { log } = __webpack_require__(1) /** - * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing - * http requests and attaches trace data when tracing is enabled via its `tracing` option. + * Get daily data up to 36 months & P max + * @param {string} pointId + * @param {string} appLogin + * @param {string} startDate + * @param {string} endDate + * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType + * @param {'EA' | 'PA' | 'PMA'} unit + * @returns {string} */ -class Http { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Http';} - - /** - * @inheritDoc - */ - __init() {this.name = Http.id;} - - /** - * @inheritDoc - */ - constructor(options = {}) {;Http.prototype.__init.call(this); - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; - } - - /** - * @inheritDoc - */ - setupOnce( - _addGlobalEventProcessor, - setupOnceGetCurrentHub, - ) { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - - const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - - // Do not auto-instrument for other instrumenter - if (clientOptions && clientOptions.instrumenter !== 'sentry') { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); - return; - } - - // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions - // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. - const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; +function consultationMesuresDetaillees( + pointId, + appLogin, + startDate, + endDate, + mesureType = 'ENERGIE', + unit = 'EA' +) { + log( + 'info', + `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterMesuresDetaillees> + <demande> + <initiateurLogin>${appLogin}</initiateurLogin> + <pointId>${pointId}</pointId> + <mesuresTypeCode>${mesureType}</mesuresTypeCode> + <grandeurPhysique>${unit}</grandeurPhysique> + <soutirage>true</soutirage> + <injection>false</injection> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <mesuresCorrigees>false</mesuresCorrigees> + <accordClient>true</accordClient> + </demande> + </v2:consulterMesuresDetaillees> + </soapenv:Body> + </soapenv:Envelope> + ` +} - const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); +/** + * Get user max power + * @param {string} pointId + * @param {string} appLogin + * @param {string} startDate + * @param {string} endDate + * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType + * @param {'EA' | 'PA' | 'PMA'} unit + * @returns {string} + */ +function consultationMesuresDetailleesMaxPower( + pointId, + appLogin, + startDate, + endDate, + mesureType = 'PMAX', + unit = 'PMA' +) { + log( + 'info', + `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterMesuresDetaillees> + <demande> + <initiateurLogin>${appLogin}</initiateurLogin> + <pointId>${pointId}</pointId> + <mesuresTypeCode>${mesureType}</mesuresTypeCode> + <grandeurPhysique>${unit}</grandeurPhysique> + <soutirage>true</soutirage> + <injection>false</injection> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <mesuresPas>P1D</mesuresPas> + <mesuresCorrigees>false</mesuresCorrigees> + <accordClient>true</accordClient> + </demande> + </v2:consulterMesuresDetaillees> + </soapenv:Body> + </soapenv:Envelope> + ` +} - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpModule = __webpack_require__(80); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); +/** + * Get user technical data (contract start date) + * @param {string} pointId + * @param {string} appLogin + * @returns {string} + */ +function consulterDonneesTechniquesContractuelles( + pointId, + appLogin, + consent = true +) { + log('info', `Query consulterDonneesTechniquesContractuelles`) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consulterdonneestechniquescontractuelles/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterDonneesTechniquesContractuelles> + <pointId>${pointId}</pointId> + <loginUtilisateur>${appLogin}</loginUtilisateur> + <autorisationClient>${consent}</autorisationClient> + </v2:consulterDonneesTechniquesContractuelles> + </soapenv:Body> + </soapenv:Envelope> + ` +} - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpsModule = __webpack_require__(81); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); - } +/** + * Use rechercherPoint to find user PDL if exist + * @param {string} lastname + * @param {string} postalCode + * @param {string} inseeCode + * @param {string} address + * @param {string} [escalierEtEtageEtAppartement] + * @returns {string} PDL + */ +function rechercherPoint( + appLogin, + lastname, + postalCode, + inseeCode, + address, + escalierEtEtageEtAppartement +) { + log( + 'info', + `Query rechercherPoint - postal code : ${postalCode} / insee code: ${inseeCode}` + ) + if (escalierEtEtageEtAppartement) { + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherPoint> + <criteres> + <adresseInstallation> + <escalierEtEtageEtAppartement>${escalierEtEtageEtAppartement}</escalierEtEtageEtAppartement> + <numeroEtNomVoie>${address}</numeroEtNomVoie> + <codePostal>${postalCode}</codePostal> + <codeInseeCommune>${inseeCode}</codeInseeCommune> + </adresseInstallation> + <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> + <rechercheHorsPerimetre>true</rechercheHorsPerimetre> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherPoint> + </soapenv:Body> + </soapenv:Envelope>` } -}Http.__initStatic(); + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherPoint> + <criteres> + <adresseInstallation> + <numeroEtNomVoie>${address}</numeroEtNomVoie> + <codePostal>${postalCode}</codePostal> + <codeInseeCommune>${inseeCode}</codeInseeCommune> + </adresseInstallation> + <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> + <rechercheHorsPerimetre>true</rechercheHorsPerimetre> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherPoint> + </soapenv:Body> + </soapenv:Envelope>` +} -// for ease of reading below +/** + * Search if user as a service + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @returns {*} + */ +function rechercherServicesSouscritsMesures(appLogin, contractId, pointId) { + log('info', `Query rechercherServicesSouscritsMesures`) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/rechercherservicessouscritsmesures/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherServicesSouscritsMesures> + <criteres> + <pointId>${pointId}</pointId> + <contratId>${contractId}</contratId> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherServicesSouscritsMesures> + </soapenv:Body> + </soapenv:Envelope>` +} /** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans - * - * @returns A function which accepts the exiting handler and returns a wrapped handler + * Activate half hour data collect for user + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @param {string} lastname + * @param {string} startDate + * @param {string} endDate + * @returns {*} */ -function _createWrappedRequestMethodFactory( - breadcrumbsEnabled, - tracingOptions, +function commanderCollectePublicationMesures( + appLogin, + contractId, + pointId, + lastname, + startDate, + endDate ) { - // We're caching results so we don't have to recompute regexp every time we create a request. - const createSpanUrlMap = {}; - const headersUrlMap = {}; + log( + 'info', + `Query commanderCollectePublicationMesures - between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/commandercollectepublicationmesures/v3.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:commanderCollectePublicationMesures> + <demande> + <donneesGenerales> + <objetCode>AME</objetCode> + <pointId>${pointId}</pointId> + <initiateurLogin>${appLogin}</initiateurLogin> + <contratId>${contractId}</contratId> + </donneesGenerales> + <accesMesures> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <declarationAccordClient> + <accord>true</accord> + <personnePhysique> + <nom>${lastname}</nom> + </personnePhysique> + </declarationAccordClient> + <mesuresTypeCode>CDC</mesuresTypeCode> + <soutirage>true</soutirage> + <injection>false</injection> + <mesuresPas>PT30M</mesuresPas> + <mesuresCorrigees>false</mesuresCorrigees> + <transmissionRecurrente>false</transmissionRecurrente> + <periodiciteTransmission>P1D</periodiciteTransmission> + </accesMesures> + </demande> + </v2:commanderCollectePublicationMesures> + </soapenv:Body> + </soapenv:Envelope>` +} - const shouldCreateSpan = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { - return true; - } +/** + * Stop the user consent + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @param {number} serviceSouscritId + * @returns {*} + */ +function commanderArretServiceSouscritMesures( + appLogin, + contractId, + pointId, + serviceSouscritId +) { + log( + 'info', + `Query commanderArretServiceSouscritMesures - serviceSouscritId: ${serviceSouscritId}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/commanderarretservicesouscritmesures/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:commanderArretServiceSouscritMesures> + <demande> + <donneesGenerales> + <objetCode>ASS</objetCode> + <pointId>${pointId}</pointId> + <initiateurLogin>${appLogin}</initiateurLogin> + <contratId>${contractId}</contratId> + </donneesGenerales> + <arretServiceSouscrit> + <serviceSouscritId>${serviceSouscritId}</serviceSouscritId> + </arretServiceSouscrit> + </demande> + </v2:commanderArretServiceSouscritMesures> + </soapenv:Body> + </soapenv:Envelope>` +} - if (createSpanUrlMap[url]) { - return createSpanUrlMap[url]; - } +module.exports = { + consulterDonneesTechniquesContractuelles, + consultationMesuresDetailleesMaxPower, + consultationMesuresDetaillees, + rechercherPoint, + rechercherServicesSouscritsMesures, + commanderCollectePublicationMesures, + commanderArretServiceSouscritMesures, +} - createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); - return createSpanUrlMap[url]; - }; +/***/ }), +/* 1681 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - const shouldAttachTraceData = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { - return true; - } +// @ts-check +const { log, errors } = __webpack_require__(1) +const { default: axios } = __webpack_require__(1682) +const Sentry = __webpack_require__(1600) - if (headersUrlMap[url]) { - return headersUrlMap[url]; - } +/** + * @param {string} pointID + * @param {string} lastname + * @param {string} firstname + * @param {string} address + * @param {string} postalCode + * @param {string} inseeCode + * @param {string} city + * @param {boolean} safetyOnBoarding + * @returns {Promise<Consent>} + */ +async function createBoConsent( + url, + token, + pointID, + lastname, + firstname, + address, + postalCode, + inseeCode, + city, + safetyOnBoarding +) { + log('info', `Query createBoConsent`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } - headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); + try { + const { data } = await axios.post( + `${url}/consent`, + { + pointID, + lastname, + firstname, + address, + postalCode, + inseeCode, + city, + safetyOnBoarding, + }, + headers + ) + return data + } catch (err) { + const errorMessage = 'Error while creating BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'createBoConsent', + }, + extra: { + pointID: pointID, + safetyOnBoarding: safetyOnBoarding, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} - return headersUrlMap[url]; - }; +/** + * @param {string} url + * @param {string} token + * @param {Consent} consent + * @param {string} serviceId + * @returns {Promise<Consent>} + */ +async function updateBoConsent(url, token, consent, serviceId) { + log('info', `Query updateBoConsent`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod( ...args) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const httpModule = this; + let consentId = '' + if (consent.ID) { + consentId = consent.ID.toString() + } + try { + const { data } = await axios.put( + `${url}/consent/${consentId}`, + { + ...consent, + serviceId: parseInt(serviceId), + }, + headers + ) + return data + } catch (err) { + const errorMessage = 'Error while updating BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'updateBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} - const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); - const requestOptions = requestArgs[0]; - const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); +/** + * @param {number} consentId + * @returns {Promise<Consent>} + */ +async function getBoConsent(url, token, consentId) { + log('info', `Query getBoConsent ${consentId}`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } + try { + const { data } = await axios.get(`${url}/consent/${consentId}`, headers) + return data + } catch (err) { + const errorMessage = 'Error while getting BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'getBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } +/** + * Delete BO consent + * @param {string} url + * @param {string} token + * @param {number} consentId + * @returns + */ +async function deleteBoConsent(url, token, consentId) { + log('info', `Query deleteBoConsent ${consentId}`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } + try { + const { data } = await axios.delete(`${url}/consent/${consentId}`, headers) + return data + } catch (err) { + const errorMessage = 'Error while deleting BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'deleteBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} - let requestSpan; - let parentSpan; +module.exports = { + createBoConsent, + updateBoConsent, + getBoConsent, + deleteBoConsent, +} - const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); - if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { - parentSpan = scope.getSpan(); +/***/ }), +/* 1682 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (parentSpan) { - requestSpan = parentSpan.startChild({ - description: `${requestOptions.method || 'GET'} ${requestUrl}`, - op: 'http.client', - }); +module.exports = __webpack_require__(1683); - if (shouldAttachTraceData(requestUrl)) { - const sentryTraceHeader = requestSpan.toTraceparent(); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, - ); +/***/ }), +/* 1683 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - requestOptions.headers = { - ...requestOptions.headers, - 'sentry-trace': sentryTraceHeader, - }; +"use strict"; - if (parentSpan.transaction) { - const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - let newBaggageHeaderField; - if (!requestOptions.headers || !requestOptions.headers.baggage) { - newBaggageHeaderField = sentryBaggageHeader; - } else if (!sentryBaggageHeader) { - newBaggageHeaderField = requestOptions.headers.baggage; - } else if (Array.isArray(requestOptions.headers.baggage)) { - newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; - } else { - // Type-cast explanation: - // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity - // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. - newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; - } +var utils = __webpack_require__(1684); +var bind = __webpack_require__(1685); +var Axios = __webpack_require__(1686); +var mergeConfig = __webpack_require__(1714); +var defaults = __webpack_require__(1691); - requestOptions.headers = { - ...requestOptions.headers, - // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined - ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), - }; - } - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, - ); - } +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); - const transaction = parentSpan.transaction; - if (transaction) { - transaction.metadata.propagations++; - } - } - } + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function ( res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (requestSpan) { - if (res.statusCode) { - requestSpan.setHttpStatus(res.statusCode); - } - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; + // Copy context to instance + utils.extend(instance, context); - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (requestSpan) { - requestSpan.setHttpStatus(500); - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }); - }; + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; + + return instance; } -/** - * Captures Breadcrumb based on provided request/response pair - */ -function addRequestBreadcrumb(event, url, req, res) { - if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { - return; - } +// Create the default instance to be exported +var axios = createInstance(defaults); - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( - { - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url, - }, - type: 'http', - }, - { - event, - request: req, - response: res, - }, - ); -} +// Expose Axios class to allow class inheritance +axios.Axios = Axios; +// Expose Cancel & CancelToken +axios.CanceledError = __webpack_require__(1704); +axios.CancelToken = __webpack_require__(1716); +axios.isCancel = __webpack_require__(1713); +axios.VERSION = (__webpack_require__(1709).version); +axios.toFormData = __webpack_require__(1695); -//# sourceMappingURL=http.js.map +// Expose AxiosError class +axios.AxiosError = __webpack_require__(1693); +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; -/***/ }), -/* 1694 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __webpack_require__(1717); + +// Expose isAxiosError +axios.isAxiosError = __webpack_require__(1718); + +module.exports = axios; + +// Allow use of default import syntax in TypeScript +module.exports["default"] = axios; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), -/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), -/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), -/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), -/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); +/***/ }), +/* 1684 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +"use strict"; +var bind = __webpack_require__(1685); -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +// eslint-disable-next-line func-names +var kindOf = (function(cache) { + // eslint-disable-next-line func-names + return function(thing) { + var str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + }; +})(Object.create(null)); + +function kindOfTest(type) { + type = type.toLowerCase(); + return function isKindOf(thing) { + return kindOf(thing) === type; + }; +} /** - * Checks whether given url points to Sentry server - * @param url url to verify + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false */ -function isSentryRequest(url) { - const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); - return dsn ? url.includes(dsn.host) : false; +function isArray(val) { + return Array.isArray(val); } /** - * Assemble a URL to be used for breadcrumbs and spans. + * Determine if a value is undefined * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false */ -function extractUrl(requestOptions) { - const protocol = requestOptions.protocol || ''; - const hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - const port = - !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; - const path = requestOptions.path ? requestOptions.path : '/'; - - return `${protocol}//${hostname}${port}${path}`; +function isUndefined(val) { + return typeof val === 'undefined'; } /** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object + * Determine if a value is a Buffer * - * @returns The cleaned description + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false */ -function cleanSpanDescription( - description, - requestOptions, - request, -) { - // nothing to clean - if (!description) { - return description; - } +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} - // eslint-disable-next-line prefer-const - let [method, requestUrl] = description.split(' '); +/** + * Determine if a value is an ArrayBuffer + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +var isArrayBuffer = kindOfTest('ArrayBuffer'); - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } - // internal routes can end up starting with a triple slash rather than a single one - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { - requestUrl = requestUrl.slice(2); +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); } - - return `${method} ${requestUrl}`; + return result; } -// the node types are missing a few properties which node's `urlToOptions` function spits out - /** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. + * Determine if a value is a String * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false */ -function urlToOptions(url) { - const options = { - protocol: url.protocol, - hostname: - typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: `${url.pathname || ''}${url.search || ''}`, - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${url.username}:${url.password}`; - } - return options; +function isString(val) { + return typeof val === 'string'; } /** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * Determine if a value is a Number * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false */ -function normalizeRequestArgs( - httpModule, - requestArgs, -) { - let callback, requestOptions; - - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop() ; - } - - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); - } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } else { - requestOptions = requestArgs[0]; - } - - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = { ...requestOptions, ...requestArgs[1] }; - } +function isNumber(val) { + return typeof val === 'number'; +} - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); - } else { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (kindOf(val) !== 'object') { + return false; } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } else { - return [requestOptions]; - } + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; } +/** + * Determine if a value is a Date + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +var isDate = kindOfTest('Date'); -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1695 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/** + * Determine if a value is a File + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFile = kindOfTest('File'); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), -/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), -/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), -/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); +/** + * Determine if a value is a Blob + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +var isBlob = kindOfTest('Blob'); +/** + * Determine if a value is a FileList + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFileList = kindOfTest('FileList'); +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} -const BAGGAGE_HEADER_NAME = 'baggage'; +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} -const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; +/** + * Determine if a value is a FormData + * + * @param {Object} thing The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(thing) { + var pattern = '[object FormData]'; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || + toString.call(thing) === pattern || + (isFunction(thing.toString) && thing.toString() === pattern) + ); +} -const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; +/** + * Determine if a value is a URLSearchParams object + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +var isURLSearchParams = kindOfTest('URLSearchParams'); /** - * Max length of a serialized baggage string + * Trim excess whitespace off the beginning and end of a string * - * https://www.w3.org/TR/baggage/#limits + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace */ -const MAX_BAGGAGE_STRING_LENGTH = 8192; +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); +} /** - * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values - * from it. + * Determine if we're running in a standard browser environment * - * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. - * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' */ -function baggageHeaderToDynamicSamplingContext( - // Very liberal definition of what any incoming header might look like - baggageHeader, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { - return undefined; +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} - // Intermediary object to store baggage key value pairs of incoming baggage headers on. - // It is later used to read Sentry-DSC-values from. - let baggageObject = {}; - - if (Array.isArray(baggageHeader)) { - // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it - baggageObject = baggageHeader.reduce((acc, curr) => { - const currBaggageObject = baggageHeaderToObject(curr); - return { - ...acc, - ...currBaggageObject, - }; - }, {}); - } else { - // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but - // this is how we choose to handle it) - if (!baggageHeader) { - return undefined; - } +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } - baggageObject = baggageHeaderToObject(baggageHeader); + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; } - // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. - const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { - if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { - const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); - acc[nonPrefixedKey] = value; + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); } - return acc; - }, {}); - - // Only return a dynamic sampling context object if there are keys in it. - // A keyless object means there were no sentry values on the header, which means that there is no DSC. - if (Object.keys(dynamicSamplingContext).length > 0) { - return dynamicSamplingContext ; } else { - return undefined; + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } } } /** - * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. * - * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility - * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is - * `undefined` the function will return `undefined`. - * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` - * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties */ -function dynamicSamplingContextToSentryBaggageHeader( - // this also takes undefined for convenience and bundle size in other places - dynamicSamplingContext, -) { - // Prefix all DSC keys with "sentry-" and put them into a new object - const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( - (acc, [dscKey, dscValue]) => { - if (dscValue) { - acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; - } - return acc; - }, - {}, - ); +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } - return objectToBaggageHeader(sentryPrefixedDSC); + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; } /** - * Will parse a baggage header, which is a simple key-value map, into a flat object. + * Extends object a by mutably adding to it the properties of object b. * - * @param baggageHeader The baggage header to parse. - * @returns a flat object containing all the key-value pairs from `baggageHeader`. + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a */ -function baggageHeaderToObject(baggageHeader) { - return baggageHeader - .split(',') - .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) - .reduce((acc, [key, value]) => { - acc[key] = value; - return acc; - }, {}); +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; } /** - * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * - * @param object The object to turn into a baggage header. - * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header - * is not spec compliant. + * @param {string} content with BOM + * @return {string} content value without BOM */ -function objectToBaggageHeader(object) { - if (Object.keys(object).length === 0) { - // An empty baggage header is not spec compliant: We return undefined. - return undefined; +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); } - - return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { - const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; - const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; - if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, - ); - return baggageHeader; - } else { - return newBaggageHeader; - } - }, ''); + return content; } +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + */ -//# sourceMappingURL=baggage.js.map - - -/***/ }), -/* 1696 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); - - - +function inherits(constructor, superConstructor, props, descriptors) { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + props && Object.assign(constructor.prototype, props); +} -/** Global Exception handler */ -class OnUncaughtException { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUncaughtException';} +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function} [filter] + * @returns {Object} + */ - /** - * @inheritDoc - */ - __init() {this.name = OnUncaughtException.id;} +function toFlatObject(sourceObj, destObj, filter) { + var props; + var i; + var prop; + var merged = {}; - /** - * @inheritDoc - */ - __init2() {this.handler = this._makeErrorHandler();} + destObj = destObj || {}; - // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if (!merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = Object.getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - /** - * @inheritDoc - */ - constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); - this._options = { - exitEvenIfOtherHandlersAreRegistered: true, - ...options, - }; - } + return destObj; +} - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('uncaughtException', this.handler); +/* + * determines whether a string ends with the characters of a specified string + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * @returns {boolean} + */ +function endsWith(str, searchString, position) { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; } + position -= searchString.length; + var lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +} - /** - * @hidden - */ - _makeErrorHandler() { - const timeout = 2000; - let caughtFirstError = false; - let caughtSecondError = false; - let calledFatalError = false; - let firstError; - - return (error) => { - let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); - if (this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = this._options.onFatalError; - } else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError ; - } +/** + * Returns new array from array like object + * @param {*} [thing] + * @returns {Array} + */ +function toArray(thing) { + if (!thing) return null; + var i = thing.length; + if (isUndefined(i)) return null; + var arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +} - // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not - // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust - // exit behaviour of the SDK accordingly: - // - If other listeners are attached, do not exit. - // - If the only listener attached is ours, exit. - const userProvidedListenersCount = global.process - .listeners('uncaughtException') - .reduce((acc, listener) => { - if ( - listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself - listener === this.handler // filter the handler we registered ourselves) - ) { - return acc; - } else { - return acc + 1; - } - }, 0); +// eslint-disable-next-line func-names +var isTypedArray = (function(TypedArray) { + // eslint-disable-next-line func-names + return function(thing) { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); - const processWouldExit = userProvidedListenersCount === 0; - const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM, + inherits: inherits, + toFlatObject: toFlatObject, + kindOf: kindOf, + kindOfTest: kindOfTest, + endsWith: endsWith, + toArray: toArray, + isTypedArray: isTypedArray, + isFileList: isFileList +}; - if (!caughtFirstError) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; +/***/ }), +/* 1685 */ +/***/ ((module) => { - if (hub.getIntegration(OnUncaughtException)) { - hub.withScope((scope) => { - scope.setLevel('fatal'); - hub.captureException(error, { - originalException: error, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - }); - } else { - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - } - } else { - if (shouldApplyFatalHandlingLogic) { - if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( - 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', - ); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); - } else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(() => { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - } - } - }; - } -} OnUncaughtException.__initStatic(); +"use strict"; -//# sourceMappingURL=onuncaughtexception.js.map +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; /***/ }), -/* 1697 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1686 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); +var utils = __webpack_require__(1684); +var buildURL = __webpack_require__(1687); +var InterceptorManager = __webpack_require__(1688); +var dispatchRequest = __webpack_require__(1689); +var mergeConfig = __webpack_require__(1714); +var buildFullPath = __webpack_require__(1699); +var validator = __webpack_require__(1715); -const DEFAULT_SHUTDOWN_TIMEOUT = 2000; +var validators = validator.validators; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} /** - * @hidden + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); +Axios.prototype.request = function request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); + config = mergeConfig(this.defaults, config); - if (client === undefined) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; } - const options = client.getOptions(); - const timeout = - (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - client.close(timeout).then( - (result) => { - if (!result) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); - }, - ); -} + var transitional = config.transitional; + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } -//# sourceMappingURL=errorhandling.js.map + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; -/***/ }), -/* 1698 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + var promise; + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); -/** Global Promise Rejection handler */ -class OnUnhandledRejection { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUnhandledRejection';} + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } - /** - * @inheritDoc - */ - __init() {this.name = OnUnhandledRejection.id;} + return promise; + } - /** - * @inheritDoc - */ - constructor( - _options - = { mode: 'warn' }, - ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); } - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - sendUnhandledPromise(reason, promise) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - if (hub.getIntegration(OnUnhandledRejection)) { - hub.withScope((scope) => { - scope.setExtra('unhandledPromiseRejection', true); - hub.captureException(reason, { - originalException: promise, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); - }); - } - this._handleRejection(reason); + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _handleRejection(reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - const rejectionWarning = - 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; + return promise; +}; - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } else if (this._options.mode === 'strict') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - }); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); - } - /* eslint-enable no-console */ +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + var fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url: url, + data: data + })); + }; } -} OnUnhandledRejection.__initStatic(); + Axios.prototype[method] = generateHTTPMethod(); -//# sourceMappingURL=onunhandledrejection.js.map + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +module.exports = Axios; /***/ }), -/* 1699 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1687 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1641); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1652); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1700); +var utils = __webpack_require__(1684); +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; -const DEFAULT_KEY = 'cause'; -const DEFAULT_LIMIT = 5; + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } -/** Adds SDK info to an event. */ -class LinkedErrors { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'LinkedErrors';} + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } - /** - * @inheritDoc - */ - __init() {this.name = LinkedErrors.id;} + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); - /** - * @inheritDoc - */ + serializedParams = parts.join('&'); + } - /** - * @inheritDoc - */ + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } - /** - * @inheritDoc - */ - constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } - /** - * @inheritDoc - */ - setupOnce() { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); - const self = hub.getIntegration(LinkedErrors); - const client = hub.getClient(); - if (client && self && self._handler && typeof self._handler === 'function') { - await self._handler(client.getOptions().stackParser, event, hint); - } - return event; - }); - } + return url; +}; - /** - * @inheritDoc - */ - _handler(stackParser, event, hint) { - if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); - } - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { - void this._walkErrorTree(stackParser, hint.originalException , this._key) - .then((linkedErrors) => { - if (event && event.exception && event.exception.values) { - event.exception.values = [...linkedErrors, ...event.exception.values]; - } - resolve(event); - }) - .then(null, () => { - resolve(event); - }); - }); - } +/***/ }), +/* 1688 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * @inheritDoc - */ - async _walkErrorTree( - stackParser, - error, - key, - stack = [], - ) { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { - return Promise.resolve(stack); - } +"use strict"; - const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); - // If the ContextLines integration is enabled, we add source code context to linked errors - // because we can't guarantee the order that integrations are run. - const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); - if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { - await contextLines.addSourceContextToFrames(exception.stacktrace.frames); - } +var utils = __webpack_require__(1684); - return new Promise((resolve, reject) => { - void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) - .then(resolve) - .then(null, () => { - reject(); - }); - }); +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; } -}LinkedErrors.__initStatic(); +}; +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; -//# sourceMappingURL=linkederrors.js.map +module.exports = InterceptorManager; /***/ }), -/* 1700 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1689 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), -/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1647); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1701); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); - +var utils = __webpack_require__(1684); +var transformData = __webpack_require__(1690); +var isCancel = __webpack_require__(1713); +var defaults = __webpack_require__(1691); +var CanceledError = __webpack_require__(1704); +/** + * Throws a `CanceledError` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } -const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); -const DEFAULT_LINES_OF_CONTEXT = 7; - -// TODO: Replace with promisify when minimum supported node >= v8 -function readTextFileAsync(path) { - return new Promise((resolve, reject) => { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { - if (err) reject(err); - else resolve(data); - }); - }); + if (config.signal && config.signal.aborted) { + throw new CanceledError(); + } } /** - * Resets the file cache. Exists for testing purposes. - * @hidden + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); -/** Add node modules / packages to the event */ -class ContextLines { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'ContextLines';} + // Ensure headers exist + config.headers = config.headers || {}; - /** - * @inheritDoc - */ - __init() {this.name = ContextLines.id;} + // Transform request data + config.data = transformData.call( + config, + config.data, + config.headers, + config.transformRequest + ); - constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); - /** Get's the number of context lines to add */ - get _contextLines() { - return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - } + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addSourceContext(event)); - } + var adapter = config.adapter || defaults.adapter; - /** Processes an event and adds context lines */ - async addSourceContext(event) { - if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { - for (const exception of event.exception.values) { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { - await this.addSourceContextToFrames(exception.stacktrace.frames); - } + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + reason.response.data, + reason.response.headers, + config.transformResponse + ); } } - return event; - } + return Promise.reject(reason); + }); +}; - /** Adds context lines to frames */ - async addSourceContextToFrames(frames) { - const contextLines = this._contextLines; - for (const frame of frames) { - // Only add context if we have a filename and it hasn't already been added - if (frame.filename && frame.context_line === undefined) { - const sourceFile = await _readSourceFile(frame.filename); +/***/ }), +/* 1690 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; - if (sourceFile) { - try { - const lines = sourceFile.split('\n'); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); - } catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - } - } - } -}ContextLines.__initStatic(); + +var utils = __webpack_require__(1684); +var defaults = __webpack_require__(1691); /** - * Reads file contents and caches them in a global LRU cache. + * Transform the data for a request or a response * - * @param filename filepath to read content from. + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data */ -async function _readSourceFile(filename) { - const cachedFile = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cachedFile !== undefined) { - return cachedFile; - } - - let content = null; - try { - content = await readTextFileAsync(filename); - } catch (_) { - // - } +module.exports = function transformData(data, headers, fns) { + var context = this || defaults; + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); - FILE_CONTENT_CACHE.set(filename, content); - return content; -} + return data; +}; -//# sourceMappingURL=contextlines.js.map +/***/ }), +/* 1691 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +"use strict"; -/***/ }), -/* 1701 */ -/***/ (function(module, exports, __webpack_require__) { -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** - * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most - * recently used items while discarding least recently used items when its limit - * is reached. - * - * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/> - * See README.md for details. - * - * Illustration of the design: - * - * entry entry entry entry - * ______ ______ ______ ______ - * | head |.newer => | |.newer => | |.newer => | tail | - * | A | | B | | C | | D | - * |______| <= older.|______| <= older.|______| <= older.|______| - * - * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added - */ -(function(g,f){ - const e = true ? exports : 0; - f(e); - if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } -})(this, function(exports) { +var utils = __webpack_require__(1684); +var normalizeHeaderName = __webpack_require__(1692); +var AxiosError = __webpack_require__(1693); +var transitionalDefaults = __webpack_require__(1694); +var toFormData = __webpack_require__(1695); -const NEWER = Symbol('newer'); -const OLDER = Symbol('older'); +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; -function LRUMap(limit, entries) { - if (typeof limit !== 'number') { - // called as (entries) - entries = limit; - limit = 0; +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; } +} - this.size = 0; - this.limit = limit; - this.oldest = this.newest = undefined; - this._keymap = new Map(); +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __webpack_require__(1696); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __webpack_require__(1706); + } + return adapter; +} - if (entries) { - this.assign(entries); - if (limit < 1) { - this.limit = this.size; +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } } } + + return (encoder || JSON.stringify)(rawValue); } -exports.LRUMap = LRUMap; +var defaults = { -function Entry(key, value) { - this.key = key; - this.value = value; - this[NEWER] = undefined; - this[OLDER] = undefined; -} + transitional: transitionalDefaults, + adapter: getDefaultAdapter(), -LRUMap.prototype._markEntryAsUsed = function(entry) { - if (entry === this.newest) { - // Already the most recenlty used entry, so no need to update the list - return; - } - // HEAD--------------TAIL - // <.older .newer> - // <--- add direction -- - // A B C <D> E - if (entry[NEWER]) { - if (entry === this.oldest) { - this.oldest = entry[NEWER]; - } - entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. - } - if (entry[OLDER]) { - entry[OLDER][NEWER] = entry[NEWER]; // C. --> E - } - entry[NEWER] = undefined; // D --x - entry[OLDER] = this.newest; // D. --> E - if (this.newest) { - this.newest[NEWER] = entry; // E. <-- D - } - this.newest = entry; -}; + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); -LRUMap.prototype.assign = function(entries) { - let entry, limit = this.limit || Number.MAX_VALUE; - this._keymap.clear(); - let it = entries[Symbol.iterator](); - for (let itv = it.next(); !itv.done; itv = it.next()) { - let e = new Entry(itv.value[0], itv.value[1]); - this._keymap.set(e.key, e); - if (!entry) { - this.oldest = e; - } else { - entry[NEWER] = e; - e[OLDER] = entry; + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; } - entry = e; - if (limit-- == 0) { - throw new Error('overflow'); + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); } - } - this.newest = entry; - this.size = this._keymap.size; -}; -LRUMap.prototype.get = function(key) { - // First, find our cache entry - var entry = this._keymap.get(key); - if (!entry) return; // Not cached. Sorry. - // As <key> was found in the cache, register it as being requested recently - this._markEntryAsUsed(entry); - return entry.value; -}; + var isObjectPayload = utils.isObject(data); + var contentType = headers && headers['Content-Type']; -LRUMap.prototype.set = function(key, value) { - var entry = this._keymap.get(key); + var isFileList; - if (entry) { - // update existing - entry.value = value; - this._markEntryAsUsed(entry); - return this; - } + if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { + var _FormData = this.env && this.env.FormData; + return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); + } else if (isObjectPayload || contentType === 'application/json') { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } - // new entry - this._keymap.set(key, (entry = new Entry(key, value))); + return data; + }], - if (this.newest) { - // link previous tail to the new tail (entry) - this.newest[NEWER] = entry; - entry[OLDER] = this.newest; - } else { - // we're first in -- yay - this.oldest = entry; - } + transformResponse: [function transformResponse(data) { + var transitional = this.transitional || defaults.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; - // add new entry to the end of the linked list -- it's now the freshest entry. - this.newest = entry; - ++this.size; - if (this.size > this.limit) { - // we hit the limit -- remove the head - this.shift(); - } + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } - return this; -}; + return data; + }], -LRUMap.prototype.shift = function() { - // todo: handle special case when limit == 1 - var entry = this.oldest; - if (entry) { - if (this.oldest[NEWER]) { - // advance the list - this.oldest = this.oldest[NEWER]; - this.oldest[OLDER] = undefined; - } else { - // the cache is exhausted - this.oldest = undefined; - this.newest = undefined; + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: __webpack_require__(1710) + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' } - // Remove last strong reference to <entry> and remove links from the purged - // entry being returned: - entry[NEWER] = entry[OLDER] = undefined; - this._keymap.delete(entry.key); - --this.size; - return [entry.key, entry.value]; } }; -// ---------------------------------------------------------------------------- -// Following code is optional and can be removed without breaking the core -// functionality. +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); -LRUMap.prototype.find = function(key) { - let e = this._keymap.get(key); - return e ? e.value : undefined; -}; +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); -LRUMap.prototype.has = function(key) { - return this._keymap.has(key); -}; +module.exports = defaults; -LRUMap.prototype['delete'] = function(key) { - var entry = this._keymap.get(key); - if (!entry) return; - this._keymap.delete(entry.key); - if (entry[NEWER] && entry[OLDER]) { - // relink the older entry with the newer entry - entry[OLDER][NEWER] = entry[NEWER]; - entry[NEWER][OLDER] = entry[OLDER]; - } else if (entry[NEWER]) { - // remove the link to us - entry[NEWER][OLDER] = undefined; - // link the newer entry to head - this.oldest = entry[NEWER]; - } else if (entry[OLDER]) { - // remove the link to us - entry[OLDER][NEWER] = undefined; - // link the newer entry to head - this.newest = entry[OLDER]; - } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { - this.oldest = this.newest = undefined; - } - this.size--; - return entry.value; -}; +/***/ }), +/* 1692 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -LRUMap.prototype.clear = function() { - // Not clearing links should be safe, as we don't expose live links to user - this.oldest = this.newest = undefined; - this.size = 0; - this._keymap.clear(); -}; +"use strict"; -function EntryIterator(oldestEntry) { this.entry = oldestEntry; } -EntryIterator.prototype[Symbol.iterator] = function() { return this; } -EntryIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: [ent.key, ent.value] }; - } else { - return { done: true, value: undefined }; - } +var utils = __webpack_require__(1684); + +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); }; -function KeyIterator(oldestEntry) { this.entry = oldestEntry; } -KeyIterator.prototype[Symbol.iterator] = function() { return this; } -KeyIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.key }; - } else { - return { done: true, value: undefined }; - } -}; +/***/ }), +/* 1693 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function ValueIterator(oldestEntry) { this.entry = oldestEntry; } -ValueIterator.prototype[Symbol.iterator] = function() { return this; } -ValueIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.value }; - } else { - return { done: true, value: undefined }; +"use strict"; + + +var utils = __webpack_require__(1684); + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); +} + +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; } -}; +}); +var prototype = AxiosError.prototype; +var descriptors = {}; -LRUMap.prototype.keys = function() { - return new KeyIterator(this.oldest); -}; +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED' +// eslint-disable-next-line func-names +].forEach(function(code) { + descriptors[code] = {value: code}; +}); -LRUMap.prototype.values = function() { - return new ValueIterator(this.oldest); -}; +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, 'isAxiosError', {value: true}); -LRUMap.prototype.entries = function() { - return this; -}; +// eslint-disable-next-line func-names +AxiosError.from = function(error, code, config, request, response, customProps) { + var axiosError = Object.create(prototype); -LRUMap.prototype[Symbol.iterator] = function() { - return new EntryIterator(this.oldest); -}; + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }); -LRUMap.prototype.forEach = function(fun, thisObj) { - if (typeof thisObj !== 'object') { - thisObj = this; - } - let entry = this.oldest; - while (entry) { - fun.call(thisObj, entry.value, entry.key, this); - entry = entry[NEWER]; - } -}; + AxiosError.call(axiosError, error.message, code, config, request, response); -/** Returns a JSON (array) representation */ -LRUMap.prototype.toJSON = function() { - var s = new Array(this.size), i = 0, entry = this.oldest; - while (entry) { - s[i++] = { key: entry.key, value: entry.value }; - entry = entry[NEWER]; - } - return s; -}; + axiosError.name = error.name; -/** Returns a String representation */ -LRUMap.prototype.toString = function() { - var s = '', entry = this.oldest; - while (entry) { - s += String(entry.key)+':'+entry.value; - entry = entry[NEWER]; - if (entry) { - s += ' < '; - } - } - return s; + customProps && Object.assign(axiosError, customProps); + + return axiosError; }; -}); +module.exports = AxiosError; /***/ }), -/* 1702 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { +/* 1694 */ +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Modules": () => (/* binding */ Modules) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +module.exports = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; -let moduleCache; -/** Extract information about paths */ -function getPaths() { - try { - return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; - } catch (e) { - return []; - } -} +/***/ }), +/* 1695 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** Extract information about package.json modules */ -function collectModules() +"use strict"; - { - const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; - const paths = getPaths(); - const infos - = {}; - const seen +var utils = __webpack_require__(1684); - = {}; +/** + * Convert a data object to FormData + * @param {Object} obj + * @param {?Object} [formData] + * @returns {Object} + **/ - paths.forEach(path => { - let dir = path; +function toFormData(obj, formData) { + // eslint-disable-next-line no-param-reassign + formData = formData || new FormData(); - /** Traverse directories upward in the search of package.json file */ - const updir = () => { - const orig = dir; - dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); + var stack = []; - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } + function convertValue(value) { + if (value === null) return ''; - const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); - seen[orig] = true; + if (utils.isDate(value)) { + return value.toISOString(); + } - if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { - return updir(); - } + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } - try { - const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) + return value; + } -; - infos[info.name] = info.version; - } catch (_oO) { - // no-empty + function build(data, parentKey) { + if (utils.isPlainObject(data) || utils.isArray(data)) { + if (stack.indexOf(data) !== -1) { + throw Error('Circular reference detected in ' + parentKey); } - }; - updir(); - }); + stack.push(data); - return infos; + utils.forEach(data, function each(value, key) { + if (utils.isUndefined(value)) return; + var fullKey = parentKey ? parentKey + '.' + key : key; + var arr; + + if (value && !parentKey && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { + // eslint-disable-next-line func-names + arr.forEach(function(el) { + !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); + }); + return; + } + } + + build(value, fullKey); + }); + + stack.pop(); + } else { + formData.append(parentKey, convertValue(data)); + } + } + + build(obj); + + return formData; } -/** Add node modules / packages to the event */ -class Modules {constructor() { Modules.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Modules';} +module.exports = toFormData; - /** - * @inheritDoc - */ - __init() {this.name = Modules.id;} - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - addGlobalEventProcessor(event => { - if (!getCurrentHub().getIntegration(Modules)) { - return event; +/***/ }), +/* 1696 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var utils = __webpack_require__(1684); +var settle = __webpack_require__(1697); +var cookies = __webpack_require__(1698); +var buildURL = __webpack_require__(1687); +var buildFullPath = __webpack_require__(1699); +var parseHeaders = __webpack_require__(1702); +var isURLSameOrigin = __webpack_require__(1703); +var transitionalDefaults = __webpack_require__(1694); +var AxiosError = __webpack_require__(1693); +var CanceledError = __webpack_require__(1704); +var parseProtocol = __webpack_require__(1705); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + var responseType = config.responseType; + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); } - return { - ...event, - modules: { - ...event.modules, - ...this._getModules(), - }, - }; - }); - } - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - _getModules() { - if (!moduleCache) { - moduleCache = collectModules(); + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } } - return moduleCache; - } -} Modules.__initStatic(); - - -//# sourceMappingURL=modules.js.map + if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { + delete requestHeaders['Content-Type']; // Let the browser set it + } -/***/ }), -/* 1703 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + var request = new XMLHttpRequest(); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Context": () => (/* binding */ Context), -/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), -/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), -/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(846); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + // Set the request timeout in MS + request.timeout = config.timeout; + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + // Clean up request + request = null; + } -// TODO: Required until we drop support for Node v8 -const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); -const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } -/** Add node modules / packages to the event */ -class Context { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Context';} + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } - /** - * @inheritDoc - */ - __init() {this.name = Context.id;} + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } - /** - * Caches context so it's only evaluated once - */ + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); - constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); - // - } + // Clean up request + request = null; + }; - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addContext(event)); - } + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); - /** Processes an event and adds context */ - async addContext(event) { - if (this._cachedContext === undefined) { - this._cachedContext = this._getContexts(); - } + // Clean up request + request = null; + }; - const updatedContext = this._updateContext(await this._cachedContext); + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + var transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); - event.contexts = { - ...event.contexts, - app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, - os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, - device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, - culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, + // Clean up request + request = null; }; - return event; - } + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; - /** - * Updates the context with dynamic values that can change - */ - _updateContext(contexts) { - // Only update properties if they exist - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { - contexts.app.app_memory = process.memoryUsage().rss; + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } } - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { - contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); } - return contexts; - } - - /** - * Gets the contexts for the current environment - */ - async _getContexts() { - const contexts = {}; + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } - if (this._options.os) { - contexts.os = await getOsContext(); + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; } - if (this._options.app) { - contexts.app = getAppContext(); + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); } - if (this._options.device) { - contexts.device = getDeviceContext(this._options.device); + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); } - if (this._options.culture) { - const culture = getCultureContext(); + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (!request) { + return; + } + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + request.abort(); + request = null; + }; - if (culture) { - contexts.culture = culture; + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); } } - return contexts; - } -}Context.__initStatic(); + if (!requestData) { + requestData = null; + } -/** - * Returns the operating system context. - * - * Based on the current platform, this uses a different strategy to provide the - * most accurate OS information. Since this might involve spawning subprocesses - * or accessing the file system, this should only be executed lazily and cached. - * - * - On macOS (Darwin), this will execute the `sw_vers` utility. The context - * has a `name`, `version`, `build` and `kernel_version` set. - * - On Linux, this will try to load a distribution release from `/etc` and set - * the `name`, `version` and `kernel_version` fields. - * - On all other platforms, only a `name` and `version` will be returned. Note - * that `version` might actually be the kernel version. - */ -async function getOsContext() { - const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); - switch (platformId) { - case 'darwin': - return getDarwinInfo(); - case 'linux': - return getLinuxInfo(); - default: - return { - name: PLATFORM_NAMES[platformId] || platformId, - version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - }; - } -} + var protocol = parseProtocol(fullPath); -function getCultureContext() { - try { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (typeof (process.versions ).icu !== 'string') { - // Node was built without ICU support + if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); return; } - // Check that node was built with full Intl support. Its possible it was built without support for non-English - // locales which will make resolvedOptions inaccurate - // - // https://nodejs.org/api/intl.html#detecting-internationalization-support - const january = new Date(9e8); - const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); - if (spanish.format(january) === 'enero') { - const options = Intl.DateTimeFormat().resolvedOptions(); - return { - locale: options.locale, - timezone: options.timeZone, - }; - } - } catch (err) { - // - } + // Send the request + request.send(requestData); + }); +}; - return; -} -function getAppContext() { - const app_memory = process.memoryUsage().rss; - const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); +/***/ }), +/* 1697 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return { app_start_time, app_memory }; -} +"use strict"; + + +var AxiosError = __webpack_require__(1693); /** - * Gets device information from os + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. */ -function getDeviceContext(deviceOpt) { - const device = {}; - - // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). - // Hence, we only set boot time, if we get a valid uptime value. - // @see https://github.com/getsentry/sentry-javascript/issues/5856 - const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); - if (typeof uptime === 'number') { - device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); } +}; - device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); - if (deviceOpt === true || deviceOpt.memory) { - device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); - device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } +/***/ }), +/* 1698 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (deviceOpt === true || deviceOpt.cpu) { - const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); - if (cpuInfo && cpuInfo.length) { - const firstCpu = cpuInfo[0]; +"use strict"; - device.processor_count = cpuInfo.length; - device.cpu_description = firstCpu.model; - device.processor_frequency = firstCpu.speed; - } - } - return device; -} +var utils = __webpack_require__(1684); -/** Mapping of Node's platform names to actual OS names. */ -const PLATFORM_NAMES = { - aix: 'IBM AIX', - freebsd: 'FreeBSD', - openbsd: 'OpenBSD', - sunos: 'SunOS', - win32: 'Windows', -}; +module.exports = ( + utils.isStandardBrowserEnv() ? -/** Linux version file to check for a distribution. */ + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); -/** Mapping of linux release files located in /etc to distributions. */ -const LINUX_DISTROS = [ - { name: 'fedora-release', distros: ['Fedora'] }, - { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, - { name: 'redhat_version', distros: ['Red Hat Linux'] }, - { name: 'SuSE-release', distros: ['SUSE Linux'] }, - { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, - { name: 'debian_version', distros: ['Debian'] }, - { name: 'debian_release', distros: ['Debian'] }, - { name: 'arch-release', distros: ['Arch Linux'] }, - { name: 'gentoo-release', distros: ['Gentoo Linux'] }, - { name: 'novell-release', distros: ['SUSE Linux'] }, - { name: 'alpine-release', distros: ['Alpine Linux'] }, -]; + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } -/** Functions to extract the OS version from Linux release files. */ -const LINUX_VERSIONS + if (utils.isString(path)) { + cookie.push('path=' + path); + } - = { - alpine: content => content, - arch: content => matchFirst(/distrib_release=(.*)/, content), - centos: content => matchFirst(/release ([^ ]+)/, content), - debian: content => content, - fedora: content => matchFirst(/release (..)/, content), - mint: content => matchFirst(/distrib_release=(.*)/, content), - red: content => matchFirst(/release ([^ ]+)/, content), - suse: content => matchFirst(/VERSION = (.*)\n/, content), - ubuntu: content => matchFirst(/distrib_release=(.*)/, content), -}; + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } -/** - * Executes a regular expression with one capture group. - * - * @param regex A regular expression to execute. - * @param text Content to execute the RegEx on. - * @returns The captured string if matched; otherwise undefined. - */ -function matchFirst(regex, text) { - const match = regex.exec(text); - return match ? match[1] : undefined; -} + if (secure === true) { + cookie.push('secure'); + } -/** Loads the macOS operating system context. */ -async function getDarwinInfo() { - // Default values that will be used in case no operating system information - // can be loaded. The default version is computed via heuristics from the - // kernel version, but the build ID is missing. - const darwinInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Mac OS X', - version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, - }; + document.cookie = cookie.join('; '); + }, - try { - // We try to load the actual macOS version by executing the `sw_vers` tool. - // This tool should be available on every standard macOS installation. In - // case this fails, we stick with the values computed above. + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, - const output = await new Promise((resolve, reject) => { - (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { - if (error) { - reject(error); - return; + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); } - resolve(stdout); - }); - }); + }; + })() : - darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); - darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); - darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); - } catch (e) { - // ignore + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); + + +/***/ }), +/* 1699 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var isAbsoluteURL = __webpack_require__(1700); +var combineURLs = __webpack_require__(1701); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); } + return requestedURL; +}; - return darwinInfo; -} -/** Returns a distribution identifier to look up version callbacks. */ -function getLinuxDistroId(name) { - return name.split(' ')[0].toLowerCase(); -} +/***/ }), +/* 1700 */ +/***/ ((module) => { -/** Loads the Linux operating system context. */ -async function getLinuxInfo() { - // By default, we cannot assume anything about the distribution or Linux - // version. `os.release()` returns the kernel version and we assume a generic - // "Linux" name, which will be replaced down below. - const linuxInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Linux', - }; +"use strict"; - try { - // We start guessing the distribution by listing files in the /etc - // directory. This is were most Linux distributions (except Knoppix) store - // release files with certain distribution-dependent meta data. We search - // for exactly one known file defined in `LINUX_DISTROS` and exit if none - // are found. In case there are more than one file, we just stick with the - // first one. - const etcFiles = await readDirAsync('/etc'); - const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); - if (!distroFile) { - return linuxInfo; - } - // Once that file is known, load its contents. To make searching in those - // files easier, we lowercase the file contents. Since these files are - // usually quite small, this should not allocate too much memory and we only - // hold on to it for a very short amount of time. - const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); - const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +}; - // Some Linux distributions store their release information in the same file - // (e.g. RHEL and Centos). In those cases, we scan the file for an - // identifier, that basically consists of the first word of the linux - // distribution name (e.g. "red" for Red Hat). In case there is no match, we - // just assume the first distribution in our list. - const { distros } = distroFile; - linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; - // Based on the found distribution, we can now compute the actual version - // number. This is different for every distribution, so several strategies - // are computed in `LINUX_VERSIONS`. - const id = getLinuxDistroId(linuxInfo.name); - linuxInfo.version = LINUX_VERSIONS[id](contents); - } catch (e) { - // ignore - } +/***/ }), +/* 1701 */ +/***/ ((module) => { - return linuxInfo; -} +"use strict"; -//# sourceMappingURL=context.js.map +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; /***/ }), -/* 1704 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1702 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "RequestData": () => (/* binding */ RequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1708); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1705); +var utils = __webpack_require__(1684); -const DEFAULT_OPTIONS = { - include: { - cookies: true, - data: true, - headers: true, - ip: false, - query_string: true, - url: true, - user: { - id: true, - username: true, - email: true, - }, - }, - transactionNamingScheme: 'methodPath', +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; }; -/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` - * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ -class RequestData { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'RequestData';} - /** - * @inheritDoc - */ - __init() {this.name = RequestData.id;} +/***/ }), +/* 1703 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but - * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use - * something similar in browser-based SDKs in the future. - */ +"use strict"; - /** - * @inheritDoc - */ - constructor(options = {}) {;RequestData.prototype.__init.call(this); - this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; - this._options = { - ...DEFAULT_OPTIONS, - ...options, - include: { - // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in - // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) - method: true, - ...DEFAULT_OPTIONS.include, - ...options.include, - user: - options.include && typeof options.include.user === 'boolean' - ? options.include.user - : { - ...DEFAULT_OPTIONS.include.user, - // Unclear why TS still thinks `options.include.user` could be a boolean at this point - ...((options.include || {}).user ), - }, - }, - }; - } - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - // Note: In the long run, most of the logic here should probably move into the request data utility functions. For - // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. - // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once - // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) - const { transactionNamingScheme } = this._options; +var utils = __webpack_require__(1684); - addGlobalEventProcessor(event => { - const hub = getCurrentHub(); - const self = hub.getIntegration(RequestData); +module.exports = ( + utils.isStandardBrowserEnv() ? - const { sdkProcessingMetadata = {} } = event; - const req = sdkProcessingMetadata.request; + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; - // If the globally installed instance of this integration isn't associated with the current hub, `self` will be - // undefined - if (!self || !req) { - return event; - } + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; - // The Express request handler takes a similar `include` option to that which can be passed to this integration. - // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this - // integration, so that all of this passing and conversion isn't necessary - const addRequestDataOptions = - sdkProcessingMetadata.requestDataOptionsFromExpressHandler || - sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || - convertReqDataIntegrationOptsToAddReqDataOpts(this._options); + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } - const processedEvent = this._addRequestData(event, req, addRequestDataOptions); + urlParsingNode.setAttribute('href', href); - // Transaction events already have the right `transaction` value - if (event.type === 'transaction' || transactionNamingScheme === 'handler') { - return processedEvent; + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; } - // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` - // value with a high-quality one - const reqWithTransaction = req ; - const transaction = reqWithTransaction._sentryTransaction; - if (transaction) { - // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to - // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential - // to break things like alert rules.) - const shouldIncludeMethodInTransactionName = - getSDKName(hub) === 'sentry.javascript.nextjs' - ? transaction.name.startsWith('/api') - : transactionNamingScheme !== 'path'; + originURL = resolveURL(window.location.href); - const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { - path: true, - method: shouldIncludeMethodInTransactionName, - customRoute: transaction.name, - }); + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : - processedEvent.transaction = transactionValue; - } + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); - return processedEvent; - }); - } -} RequestData.__initStatic(); -/** Convert this integration's options to match what `addRequestDataToEvent` expects */ -/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ -function convertReqDataIntegrationOptsToAddReqDataOpts( - integrationOptions, -) { - const { - transactionNamingScheme, - include: { ip, user, ...requestOptions }, - } = integrationOptions; +/***/ }), +/* 1704 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - const requestIncludeKeys = []; - for (const [key, value] of Object.entries(requestOptions)) { - if (value) { - requestIncludeKeys.push(key); - } - } +"use strict"; - let addReqDataUserOpt; - if (user === undefined) { - addReqDataUserOpt = true; - } else if (typeof user === 'boolean') { - addReqDataUserOpt = user; - } else { - const userIncludeKeys = []; - for (const [key, value] of Object.entries(user)) { - if (value) { - userIncludeKeys.push(key); - } - } - addReqDataUserOpt = userIncludeKeys; - } - return { - include: { - ip, - user: addReqDataUserOpt, - request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, - transaction: transactionNamingScheme, - }, - }; -} +var AxiosError = __webpack_require__(1693); +var utils = __webpack_require__(1684); -function getSDKName(hub) { - try { - // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to - // write out a long chain of `a && a.b && a.b.c && ...` - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return hub.getClient().getOptions()._metadata.sdk.name; - } catch (err) { - // In theory we should never get here - return undefined; - } +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function CanceledError(message) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); + this.name = 'CanceledError'; } +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); -//# sourceMappingURL=requestdata.js.map +module.exports = CanceledError; /***/ }), /* 1705 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1707); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1660); -/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1706); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); +module.exports = function parseProtocol(url) { + var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +}; +/***/ }), +/* 1706 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; +"use strict"; -/** - * Options deciding what parts of the request to use when enhancing an event - */ + +var utils = __webpack_require__(1684); +var settle = __webpack_require__(1697); +var buildFullPath = __webpack_require__(1699); +var buildURL = __webpack_require__(1687); +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var httpFollow = (__webpack_require__(1707).http); +var httpsFollow = (__webpack_require__(1707).https); +var url = __webpack_require__(63); +var zlib = __webpack_require__(83); +var VERSION = (__webpack_require__(1709).version); +var transitionalDefaults = __webpack_require__(1694); +var AxiosError = __webpack_require__(1693); +var CanceledError = __webpack_require__(1704); + +var isHttps = /https:?/; + +var supportedProtocols = [ 'http:', 'https:', 'file:' ]; /** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location */ -function addRequestDataToTransaction(transaction, req) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; + + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; } - transaction.setData('query', extractQueryParams(req)); + + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); + }; } -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } - let path = ''; - let source = 'url'; + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } + var resolve = function resolve(value) { + done(); + resolvePromise(value); + }; + var rejected = false; + var reject = function reject(value) { + done(); + rejected = true; + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; + var headerNames = {}; + + Object.keys(headers).forEach(function storeLowerName(name) { + headerNames[name.toLowerCase()] = name; + }); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + if ('user-agent' in headerNames) { + // User-Agent is specified; handle case where no UA header is desired + if (!headers[headerNames['user-agent']]) { + delete headers[headerNames['user-agent']]; + } + // Otherwise, use specified value + } else { + // Only set header if it hasn't been set in config + headers['User-Agent'] = 'axios/' + VERSION; + } + + // support for https://www.npmjs.com/package/form-data api + if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + Object.assign(headers, data.getHeaders()); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } + // Add Content-Length header if data exists + if (!headerNames['content-length']) { + headers['Content-Length'] = data.length; + } + } - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } - return [name, source]; -} + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || supportedProtocols[0]; -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; + + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; } - } -} -/** JSDoc */ -function extractUserData( - user + if (auth && headerNames.authorization) { + delete headers[headerNames.authorization]; + } -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; + try { + buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''); + } catch (err) { + var customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + reject(customErr); } - }); - return extractedUser; -} + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; -/** - * Normalize data from the request object - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } -, -) { - const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; - const requestData = {}; + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } - // Remove the Cookie header in case cookie data should not be included in the event - if (!include.includes('cookies')) { - delete (requestData.headers ).cookie; + return parsed.hostname === proxyElement; + }); } - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; + + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } } } } - }); - - return requestData; -} - -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * - * @returns The mutated `Event` object - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request }) - : extractRequestData(req); - - event.request = { - ...event.request, - ...extractedRequestData, - }; - } - if (include.user) { - const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); } - } - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirect = config.beforeRedirect; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; } - } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } - - return event; -} - -function extractQueryParams(req) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; - - if (!originalUrl) { - return; - } - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || - undefined - ); -} + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; -//# sourceMappingURL=requestdata.js.map + // uncompress the response body transparently if required + var stream = res; + // return the last request in case of redirects + var lastRequest = res.req || req; -/***/ }), -/* 1706 */ -/***/ ((__unused_webpack_module, exports) => { -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + } + } + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest + }; -/** - * Module exports. - * @public - */ + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + var totalResponseBytes = 0; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; -exports.parse = parse; -exports.serialize = serialize; + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destoy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + stream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); -/** - * Module variables. - * @private - */ + stream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + stream.destroy(); + reject(new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + )); + }); -var decode = decodeURIComponent; -var encode = encodeURIComponent; + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ + stream.on('end', function handleStreamEnd() { + try { + var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + }); -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + var timeout = parseInt(config.timeout, 10); - var obj = {} - var opt = options || {}; - var pairs = str.split(';') - var dec = opt.decode || decode; + if (isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var index = pair.indexOf('=') + return; + } - // skip things that don't look like key=value - if (index < 0) { - continue; + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + req.abort(); + var transitional = config.transitional || transitionalDefaults; + reject(new AxiosError( + 'timeout of ' + timeout + 'ms exceeded', + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + }); } - var key = pair.substring(0, index).trim() + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (req.aborted) return; - // only assign once - if (undefined == obj[key]) { - var val = pair.substring(index + 1, pair.length).trim() + req.abort(); + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + }; - // quoted values - if (val[0] === '"') { - val = val.slice(1, -1) + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); } + } - obj[key] = tryDecode(val, dec); + + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(AxiosError.from(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); } - } + }); +}; - return obj; -} -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ +/***/ }), +/* 1707 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; +var url = __webpack_require__(63); +var URL = url.URL; +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var Writable = (__webpack_require__(82).Writable); +var assert = __webpack_require__(91); +var debug = __webpack_require__(1708); - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); - var value = enc(val); +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); } - var str = name + '=' + value; + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') - } +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); +}; - str += '; Max-Age=' + Math.floor(maxAge); +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); } - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } - - str += '; Domain=' + opt.domain; + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } - - str += '; Path=' + opt.path; + if (typeof encoding === "function") { + callback = encoding; + encoding = null; } - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); } - - str += '; Expires=' + opt.expires.toUTCString(); + return; } - - if (opt.httpOnly) { - str += '; HttpOnly'; + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); } - - if (opt.secure) { - str += '; Secure'; + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); } +}; - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; } +}; - return str; -} +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } -/***/ }), -/* 1707 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), -/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) -/* harmony export */ }); -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not <a/> href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } - { - if (!url) { - return {}; + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } } - const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } - if (!match) { - return {}; + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); } - // coerce to undefined values to empty string so we don't get 'undefined' - const query = match[6] || ''; - const fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, // everything minus origin - }; -} + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} + return this; +}; -/** - * Returns number of URL segments of a passed string URL. - */ -function getNumberOfUrlSegments(url) { - // split at '/' or at '\/' to split regex urls correctly - return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; -} +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); -//# sourceMappingURL=url.js.map +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } -/***/ }), -/* 1708 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1663); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1660); -/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1707); +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._currentUrl = this._options.path; -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } }; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction( - transaction, - req, - deps, -) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); } - transaction.setData('query', extractQueryParams(req, deps)); -} -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. - let path = ''; - let source = 'url'; + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; + // Clean up + this._requestBodyBuffers = []; + return; } - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } + // The response is a redirect, so abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); - let name = ''; - if (options.method && method) { - name += method; + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; } - if (options.method && options.path) { - name += ' '; + + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); } - if (options.path && path) { - name += path; + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); } - return [name, source]; -} + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = url.parse(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); + + // Determine the URL of the redirection + var redirectUrl; + try { + redirectUrl = url.resolve(currentUrl, location); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + return; } -} -/** JSDoc */ -function extractUserData( - user + // Create the redirected request + debug("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrlParts.protocol !== currentUrlParts.protocol && + redirectUrlParts.protocol !== "https:" || + redirectUrlParts.host !== currentHost && + !isSubdomain(redirectUrlParts.host, currentHost)) { + removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); + } - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; + // Evaluate the beforeRedirect callback + if (typeof beforeRedirect === "function") { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + try { + beforeRedirect(this._options, responseDetails, requestDetails); } - }); - - return extractedUser; -} + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); + } -/** - * Normalize data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + } +}; -, -) { - const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; - const requestData = {}; +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req, deps); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL(urlStr)); } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); } - break; } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); } - }); - return requestData; + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } -/** - * Options deciding what parts of the request to use when enhancing an event - */ +/* istanbul ignore next */ +function noop() { /* empty */ } -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * @param options.deps Injected platform-specific dependencies - * @hidden - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, }; - - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) - : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); - - event.request = { - ...event.request, - ...extractedRequestData, - }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); } + return options; +} - if (include.user) { - const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; - - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; } } + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; +function createErrorType(code, defaultMessage) { + function CustomError(cause) { + Error.captureStackTrace(this, this.constructor); + if (!cause) { + this.message = defaultMessage; + } + else { + this.message = defaultMessage + ": " + cause.message; + this.cause = cause; } } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; +} - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); +function abortRequest(request) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); } - - return event; + request.on("error", noop); + request.abort(); } -function extractQueryParams( - req, - deps, -) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; +function isSubdomain(subdomain, domain) { + const dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} - if (!originalUrl) { - return; - } +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - (deps && deps.url && deps.url.parse(originalUrl).query) || - undefined - ); -} +/***/ }), +/* 1708 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var debug; -//# sourceMappingURL=requestdata.js.map +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __webpack_require__(1402)("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; /***/ }), /* 1709 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getModule": () => (/* binding */ getModule) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1710); +module.exports = { + "version": "0.27.2" +}; +/***/ }), +/* 1710 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** normalizes Windows paths */ -function normalizePath(path) { - return path - .replace(/^[A-Z]:/, '') // remove Windows-style prefix - .replace(/\\/g, '/'); // replace all `\` instances with `/` -} +// eslint-disable-next-line strict +module.exports = __webpack_require__(1711); -/** Gets the module from a filename */ -function getModule(filename) { - if (!filename) { - return; - } - const normalizedFilename = normalizePath(filename); +/***/ }), +/* 1711 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // We could use optional chaining here but webpack does like that mixed with require - const base = normalizePath( - `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, - ); +var CombinedStream = __webpack_require__(147); +var util = __webpack_require__(64); +var path = __webpack_require__(142); +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var parseUrl = (__webpack_require__(63).parse); +var fs = __webpack_require__(149); +var Stream = (__webpack_require__(82).Stream); +var mime = __webpack_require__(139); +var asynckit = __webpack_require__(150); +var populate = __webpack_require__(1712); - // It's specifically a module - const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); +// Public API +module.exports = FormData; - const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); - let n = path.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = `${path}/`.lastIndexOf(base, 0); - if (n === 0) { - let moduleName = path.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; - } - moduleName += file; - return moduleName; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; } - return file; } +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; -//# sourceMappingURL=module.js.map +FormData.prototype.append = function(field, value, options) { + options = options || {}; -/***/ }), -/* 1710 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "basename": () => (/* binding */ basename), -/* harmony export */ "dirname": () => (/* binding */ dirname), -/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), -/* harmony export */ "join": () => (/* binding */ join), -/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), -/* harmony export */ "relative": () => (/* binding */ relative), -/* harmony export */ "resolve": () => (/* binding */ resolve) -/* harmony export */ }); -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js + var append = CombinedStream.prototype.append.bind(this); -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - let up = 0; - for (let i = parts.length - 1; i >= 0; i--) { - const last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; } - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - const parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve(...args) { - let resolvedPath = ''; - let resolvedAbsolute = false; + append(header); + append(value); + append(footer); - for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - const path = i >= 0 ? args[i] : '/'; + // pass along options.knownLength + this._trackLength(header, value, options); +}; - // Skip empty entries - if (!path) { - continue; - } +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charAt(0) === '/'; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray( - resolvedPath.split('/').filter(p => !!p), - !resolvedAbsolute, - ).join('/'); + this._valueLength += valueLength; - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; -/** JSDoc */ -function trim(arr) { - let start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; } - let end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); } +}; - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} +FormData.prototype._lengthRetriever = function(value, callback) { -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ + if (value.hasOwnProperty('fd')) { - const fromParts = trim(from.split('/')); - const toParts = trim(to.split('/')); + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - const length = Math.min(fromParts.length, toParts.length); - let samePartsLength = length; - for (let i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - let outputParts = []; - for (let i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - outputParts = outputParts.concat(toParts.slice(samePartsLength)); + var fileSize; - return outputParts.join('/'); -} + if (err) { + callback(err); + return; + } -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - const isPathAbsolute = isAbsolute(path); - const trailingSlash = path.substr(-1) === '/'; + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - // Normalize the path - let normalizedPath = normalizeArray( - path.split('/').filter(p => !!p), - !isPathAbsolute, - ).join('/'); + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; +}; + +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; } - return (isPathAbsolute ? '/' : '') + normalizedPath; -} + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; -// posix version -/** JSDoc */ -function join(...args) { - return normalizePath(args.join('/')); -} + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } -/** JSDoc */ -function dirname(path) { - const result = splitPath(path); - const root = result[0]; - let dir = result[1]; + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } + // skip nullish headers. + if (header == null) { + continue; + } - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } } - return root + dir; -} + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; -/** JSDoc */ -function basename(path, ext) { - let f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); +FormData.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); } - return f; -} + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } -//# sourceMappingURL=path.js.map + return contentDisposition; +}; +FormData.prototype._getContentType = function(value, options) { -/***/ }), -/* 1711 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // use custom content-type above all + var contentType = options.contentType; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), -/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), -/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1648); + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } -/** Options for the InboundFilters integration */ + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } -/** Inbound filters configurable by the user */ -class InboundFilters { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'InboundFilters';} + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } - /** - * @inheritDoc - */ - __init() {this.name = InboundFilters.id;} + return contentType; +}; - constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - const eventProcess = (event) => { - const hub = getCurrentHub(); - if (hub) { - const self = hub.getIntegration(InboundFilters); - if (self) { - const client = hub.getClient(); - const clientOptions = client ? client.getOptions() : {}; - const options = _mergeOptions(self._options, clientOptions); - return _shouldDropEvent(event, options) ? null : event; - } - } - return event; - }; + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - eventProcess.id = this.name; - addGlobalEventProcessor(eventProcess); - } -} InboundFilters.__initStatic(); + next(footer); + }.bind(this); +}; -/** JSDoc */ -function _mergeOptions( - internalOptions = {}, - clientOptions = {}, -) { - return { - allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], - denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], - ignoreErrors: [ - ...(internalOptions.ignoreErrors || []), - ...(clientOptions.ignoreErrors || []), - ...DEFAULT_IGNORE_ERRORS, - ], - ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, - }; -} +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; -/** JSDoc */ -function _shouldDropEvent(event, options) { - if (options.ignoreInternal && _isSentryError(event)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return true; - } - if (_isIgnoredError(event, options.ignoreErrors)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, - ); - return true; - } - if (_isDeniedUrl(event, options.denyUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - if (!_isAllowedUrl(event, options.allowUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; - } - return false; -} +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; -function _isIgnoredError(event, ignoreErrors) { - if (!ignoreErrors || !ignoreErrors.length) { - return false; + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } } - return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); -} + return formHeaders; +}; -function _isDeniedUrl(event, denyUrls) { - // TODO: Use Glob instead? - if (!denyUrls || !denyUrls.length) { - return false; - } - const url = _getEventFilterUrl(event); - return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); -} +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; -function _isAllowedUrl(event, allowUrls) { - // TODO: Use Glob instead? - if (!allowUrls || !allowUrls.length) { - return true; +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - const url = _getEventFilterUrl(event); - return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); -} -function _getPossibleEventMessages(event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; - return [`${value}`, `${type}: ${value}`]; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return []; - } - } - return []; -} + return this._boundary; +}; -function _isSentryError(event) { - try { - // @ts-ignore can't be a sentry error if undefined - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return event.exception.values[0].type === 'SentryError'; - } catch (e) { - // ignore - } - return false; -} +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); -function _getLastValidUrl(frames = []) { - for (let i = frames.length - 1; i >= 0; i--) { - const frame = frames[i]; + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { - if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { - return frame.filename || null; + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } } } - return null; -} + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; -function _getEventFilterUrl(event) { - try { - let frames; - try { - // @ts-ignore we only care about frames if the whole thing here is defined - frames = event.exception.values[0].stacktrace.frames; - } catch (e) { - // ignore - } - return frames ? _getLastValidUrl(frames) : null; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return null; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); } -} - -//# sourceMappingURL=inboundfilters.js.map + this._boundary = boundary; +}; +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; -/***/ }), -/* 1712 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + return knownLength; +}; -let originalFunctionToString; +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -/** Patch toString calls to return proper name for wrapped functions */ -class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'FunctionToString';} + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - /** - * @inheritDoc - */ - __init() {this.name = FunctionToString.id;} + return hasKnownLength; +}; - /** - * @inheritDoc - */ - setupOnce() { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function ( ...args) { - const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; - return originalFunctionToString.apply(context, args); - }; + if (this._streams.length) { + knownLength += this._lastBoundary().length; } -} FunctionToString.__initStatic(); + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } -//# sourceMappingURL=functiontostring.js.map + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); -/***/ }), -/* 1713 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + cb(null, knownLength); + }); +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); -/** A class object that can instantiate Client objects. */ + // use custom params + } else { -/** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. - * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. - */ -function initAndBind( - clientClass, - options, -) { - if (options.debug === true) { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); - } else { - // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped - // eslint-disable-next-line no-console - console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; } } - const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const scope = hub.getScope(); - if (scope) { - scope.update(options.initialScope); - } - const client = new clientClass(options); - hub.bindClient(client); -} + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -//# sourceMappingURL=sdk.js.map + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } + // add content length + if (length) { + request.setHeader('Content-Length', length); + } -/***/ }), -/* 1714 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + this.pipe(request); + if (cb) { + var onResponse; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + return cb.call(this, error, responce); + }; + onResponse = callback.bind(this, null); -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); - if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); - } + return request; +}; - if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); } +}; - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - const deepReadCurrentDir = (currentDirAbsPath) => { - return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { - const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); +FormData.prototype.toString = function () { + return '[object FormData]'; +}; - if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { - return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; - } - return [...absPaths, itemAbsPath]; - }, []); - }; +/***/ }), +/* 1712 */ +/***/ ((module) => { - return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); -} +// populates missing values +module.exports = function(dst, src) { + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); -//# sourceMappingURL=utils.js.map + return dst; +}; /***/ }), -/* 1715 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1713 */ +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), -/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), -/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), -/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), -/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1655); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1717); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1695); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1708); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1650); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1705); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1689); -/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1716); - +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; +/***/ }), +/* 1714 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ +var utils = __webpack_require__(1684); /** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 */ -function tracingHandler() +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; - { - return function sentryTracingMiddleware( - req, - res, - next, - ) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } - if ( - !options || - options.instrumenter !== 'sentry' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' - ) { - return next(); + // eslint-disable-next-line consistent-return + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); } + } - // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a - // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. - if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( - 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + - 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', - ); - return next(); + // eslint-disable-next-line consistent-return + function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); } + } - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - const traceparentData = - req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); - const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); - const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); + // eslint-disable-next-line consistent-return + function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); + } + } - const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); - const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( - { - name, - op: 'http.server', - ...traceparentData, - metadata: { - dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, - // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become - // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the - // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to - // be sure - request: req, - source, - }, - }, - // extra context passed to the tracesSampler - { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, - ); + // eslint-disable-next-line consistent-return + function mergeDirectKeys(prop) { + if (prop in config2) { + return getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + return getMergedValue(undefined, config1[prop]); + } + } - // We put the transaction on the scope so users can attach children to it - hub.configureScope(scope => { - scope.setSpan(transaction); - }); + var mergeMap = { + 'url': valueFromConfig2, + 'method': valueFromConfig2, + 'data': valueFromConfig2, + 'baseURL': defaultToConfig2, + 'transformRequest': defaultToConfig2, + 'transformResponse': defaultToConfig2, + 'paramsSerializer': defaultToConfig2, + 'timeout': defaultToConfig2, + 'timeoutMessage': defaultToConfig2, + 'withCredentials': defaultToConfig2, + 'adapter': defaultToConfig2, + 'responseType': defaultToConfig2, + 'xsrfCookieName': defaultToConfig2, + 'xsrfHeaderName': defaultToConfig2, + 'onUploadProgress': defaultToConfig2, + 'onDownloadProgress': defaultToConfig2, + 'decompress': defaultToConfig2, + 'maxContentLength': defaultToConfig2, + 'maxBodyLength': defaultToConfig2, + 'beforeRedirect': defaultToConfig2, + 'transport': defaultToConfig2, + 'httpAgent': defaultToConfig2, + 'httpsAgent': defaultToConfig2, + 'cancelToken': defaultToConfig2, + 'socketPath': defaultToConfig2, + 'responseEncoding': defaultToConfig2, + 'validateStatus': mergeDirectKeys + }; - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).__sentry_transaction = transaction; + utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { + var merge = mergeMap[prop] || mergeDeepProperties; + var configValue = merge(prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); - res.once('finish', () => { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(() => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); + return config; +}; - next(); + +/***/ }), +/* 1715 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var VERSION = (__webpack_require__(1709).version); +var AxiosError = __webpack_require__(1693); + +var validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; -} +}); + +var deprecatedWarnings = {}; /** - * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the - * `AddRequestDataToEventOptions` interface. - * - * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. + * Transitional option validator + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * @returns {function} */ -function convertReqHandlerOptsToAddReqDataOpts( - reqHandlerOptions = {}, -) { - let addRequestDataOptions; +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } - if ('include' in reqHandlerOptions) { - addRequestDataOptions = { include: reqHandlerOptions.include }; - } else { - // eslint-disable-next-line deprecation/deprecation - const { ip, request, transaction, user } = reqHandlerOptions ; + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } - if (ip || request || transaction || user) { - addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); } - } - return addRequestDataOptions; -} + return validator ? validator(value, opt, opts) : true; + }; +}; /** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown */ -function requestHandler( - options, -) { - // TODO (v8): Get rid of this - const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); - - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - client.initSessionFlusher(); - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - const scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); } - - return function sentryRequestMiddleware( - req, - res, - next, - ) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const _end = res.end; - res.end = function (chunk, encoding, cb) { - void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) - .then(() => { - _end.call(this, chunk, encoding, cb); - }) - .then(null, e => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); - _end.call(this, chunk, encoding, cb); - }); - }; + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; } - const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); - local.add(req); - local.add(res); - - local.run(() => { - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} - currentHub.configureScope(scope => { - scope.setSDKProcessingMetadata({ - request: req, - // TODO (v8): Stop passing this - requestDataOptionsFromExpressHandler: requestDataOptions, - }); +module.exports = { + assertOptions: assertOptions, + validators: validators +}; - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - const scope = currentHub.getScope(); - if (scope) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: 'ok' }); - } - } - }); - res.once('finish', () => { - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - setImmediate(() => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && (client )._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (client )._captureRequestSession(); - } - }); - } - }); - next(); - }); - }; -} +/***/ }), +/* 1716 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** JSDoc */ +"use strict"; -/** JSDoc */ -function getStatusCodeFromResponse(error) { - const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode , 10) : 500; -} -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - const status = getStatusCodeFromResponse(error); - return status >= 500; -} +var CanceledError = __webpack_require__(1704); /** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. */ -function errorHandler(options - -) +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } - { - return function sentryErrorMiddleware( - error, - _req, - res, - next, - ) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; + var resolvePromise; - if (shouldHandleError(error)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { - // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, - // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't - // hurt to be sure - _scope.setSDKProcessingMetadata({ request: _req }); + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const transaction = (res ).__sentry_transaction ; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } + var token = this; - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - const requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) { - requestSession.status = 'crashed'; - } - } - } + // eslint-disable-next-line func-names + this.promise.then(function(cancel) { + if (!token._listeners) return; - const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).sentry = eventId; - next(error); - }); + var i; + var l = token._listeners.length; - return; + for (i = 0; i < l; i++) { + token._listeners[i](cancel); } + token._listeners = null; + }); - next(error); - }; -} - -// TODO (v8 / #5257): Remove this -// eslint-disable-next-line deprecation/deprecation -; - - -//# sourceMappingURL=handlers.js.map + // eslint-disable-next-line func-names + this.promise.then = function(onfulfilled) { + var _resolve; + // eslint-disable-next-line func-names + var promise = new Promise(function(resolve) { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; -/***/ }), -/* 1716 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + return promise; + }; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), -/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) -/* harmony export */ }); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1705); + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + token.reason = new CanceledError(message); + resolvePromise(token.reason); + }); +} /** - * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. + * Throws a `CanceledError` if cancellation has been requested. */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; /** - * Normalizes data from the request object, accounting for framework differences. - * - * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. - * @returns An object containing normalized request data + * Subscribe to the cancel signal */ -function extractRequestData(req, keys) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); -} + +CancelToken.prototype.subscribe = function subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } +}; /** - * Options deciding what parts of the request to use when enhancing an event - * - * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use - * `AddRequestDataToEventOptions` in `@sentry/utils` instead. + * Unsubscribe from the cancel signal */ +CancelToken.prototype.unsubscribe = function unsubscribe(listener) { + if (!this._listeners) { + return; + } + var index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } +}; + /** - * Enriches passed event with request data. - * - * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. */ -function parseRequest(event, req, options = {}) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); -} - +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; -//# sourceMappingURL=requestDataDeprecated.js.map +module.exports = CancelToken; /***/ }), /* 1717 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) -/* harmony export */ }); -const TRACEPARENT_REGEXP = new RegExp( - '^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$', // whitespace -); + /** - * Extract transaction context data from a `sentry-trace` header. + * Syntactic sugar for invoking a function and expanding an array for arguments. * - * @param traceparent Traceparent string + * Common use case would be to use `Function.prototype.apply`. * - * @returns Object containing data from the header, or undefined if traceparent string is malformed + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} */ -function extractTraceparentData(traceparent) { - const matches = traceparent.match(TRACEPARENT_REGEXP); - - if (!traceparent || !matches) { - // empty string or no matches is invalid traceparent data - return undefined; - } - - let parentSampled; - if (matches[3] === '1') { - parentSampled = true; - } else if (matches[3] === '0') { - parentSampled = false; - } - - return { - traceId: matches[1], - parentSampled, - parentSpanId: matches[2], +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); }; -} - - -//# sourceMappingURL=tracing.js.map +}; /***/ }), /* 1718 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), -/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) -/* harmony export */ }); -/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1712); -/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1711); -//# sourceMappingURL=index.js.map +var utils = __webpack_require__(1684); + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +}; /***/ }), @@ -246976,9 +247044,9 @@ module.exports = { const { log, errors } = __webpack_require__(1) const soapRequest = __webpack_require__(1375) const { parseTags, parseValue, parseServiceId } = __webpack_require__(1599) -const { commanderCollectePublicationMesures } = __webpack_require__(1600) +const { commanderCollectePublicationMesures } = __webpack_require__(1680) const xml2js = __webpack_require__(1557) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) /** * @param {string} url @@ -247018,10 +247086,19 @@ async function activateContract( endDate ), }).catch(err => { - log('error', 'commanderCollectePublicationMesures') - log('error', err) - Sentry.captureException('commanderCollectePublicationMesures', err) - throw errors.CAPTCHA_RESOLUTION_FAILED + const errorMessage = `Error while activating contract : ${err}` + log('debug', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'activateContract', + }, + extra: { + pointId: pointId, + dates: [startDate, endDate], + }, + }) + + throw new Error(errors.CAPTCHA_RESOLUTION_FAILED) }) const parsedReply = await xml2js.parseStringPromise(response.body, { @@ -247045,7 +247122,7 @@ async function activateContract( // TODO: handle SGT4B8: Il existe déjà plusieurs demandes en cours sur le point ? // TODO: handle SGT4H9: La demande ne porte pas sur un point équipé d'un compteur communicant ouvert aux services niveau 2. // TODO: handle SGT589: La demande ne peut pas aboutir car le compteur n'est actuellement pas téléopérable. - throw errors.CAPTCHA_RESOLUTION_FAILED + throw new Error(errors.CAPTCHA_RESOLUTION_FAILED) } } @@ -247065,8 +247142,8 @@ const { parseContractStartDate, } = __webpack_require__(1599) const xml2js = __webpack_require__(1557) -const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1600) -const Sentry = __webpack_require__(1639) +const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1680) +const Sentry = __webpack_require__(1600) /** * Get user contract start date @@ -247090,8 +247167,15 @@ async function getContractStartDate(url, apiAuthKey, userLogin, pointId) { }).catch(err => { const errorMessage = 'Error while fetching contract start date : ' + err log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { + section: 'getContractStartDate', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errors.VENDOR_DOWN) }) const result = await xml2js.parseStringPromise(response.body, { @@ -247109,7 +247193,7 @@ async function getContractStartDate(url, apiAuthKey, userLogin, pointId) { 'error', `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` ) - throw errors.NOT_EXISTING_DIRECTORY + throw new Error(errors.NOT_EXISTING_DIRECTORY) } } @@ -247124,9 +247208,9 @@ module.exports = { getContractStartDate } const { log, errors } = __webpack_require__(1) const soapRequest = __webpack_require__(1375) const { parseTags, parseValue } = __webpack_require__(1599) -const { commanderArretServiceSouscritMesures } = __webpack_require__(1600) +const { commanderArretServiceSouscritMesures } = __webpack_require__(1680) const xml2js = __webpack_require__(1557) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) /** * @param {string} url @@ -247160,10 +247244,19 @@ async function terminateContract( serviceId ), }).catch(err => { - log('error', 'commanderArretServiceSouscritMesures') - log('error', err) - Sentry.captureException('commanderArretServiceSouscritMesures', err) - throw errors.VENDOR_DOWN + const errorMessage = 'Error while terminating contract : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'terminateContract', + }, + extra: { + contractId: contractId, + pointId: pointId, + serviceId: serviceId, + }, + }) + throw new Error(errors.VENDOR_DOWN) }) const parsedReply = await xml2js.parseStringPromise(response.body, { @@ -247186,8 +247279,15 @@ async function terminateContract( 'Error while parsing user contract termination: ' + error log('error', errorMessage) log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { + section: 'terminateContract', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errors.VENDOR_DOWN) } } @@ -247207,10 +247307,10 @@ const { parseContracts, checkContractExists, } = __webpack_require__(1599) -const { rechercherServicesSouscritsMesures } = __webpack_require__(1600) +const { rechercherServicesSouscritsMesures } = __webpack_require__(1680) const xml2js = __webpack_require__(1557) const { contractState } = __webpack_require__(1724) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) /** * @param {string} url @@ -247231,10 +247331,18 @@ async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) { headers: sgeHeaders, xml: rechercherServicesSouscritsMesures(appLogin, contractId, pointId), }).catch(err => { - log('error', 'rechercherServicesSouscritsMesures') - log('error', err) - Sentry.captureException('rechercherServicesSouscritsMesures', err) - throw errors.CAPTCHA_RESOLUTION_FAILED + const errorMessage = 'Error while verifying contract : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'verifyContract', + }, + extra: { + contractId: contractId, + pointId: pointId, + }, + }) + throw new Error(errors.CAPTCHA_RESOLUTION_FAILED) }) const parsedReply = await xml2js.parseStringPromise(response.body, { @@ -247266,7 +247374,11 @@ async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) { } catch (error) { const errorMessage = 'Error while parsing user contract: ' + error log('error', errorMessage) - Sentry.captureException(errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'verifyContract', + }, + }) if (parsedReply.Envelope.Body.Fault) { log( 'error', @@ -247277,7 +247389,7 @@ async function verifyContract(url, apiAuthKey, appLogin, contractId, pointId) { 'error', 'if an error is thrown here, it probably means that the contract has already been open today and that enedis cannot open a second one. Wait until tomorow to try again' ) - throw errors.CAPTCHA_RESOLUTION_FAILED + throw new Error(errors.CAPTCHA_RESOLUTION_FAILED) } } @@ -247310,9 +247422,9 @@ module.exports = { contractState } const { log, errors } = __webpack_require__(1) const soapRequest = __webpack_require__(1375) const { parseUserPdl, parseTags, parseValue } = __webpack_require__(1599) -const { rechercherPoint } = __webpack_require__(1600) +const { rechercherPoint } = __webpack_require__(1680) const xml2js = __webpack_require__(1557) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) /** * @param {string} url @@ -247352,10 +247464,19 @@ async function findUserPdl( escalierEtEtageEtAppartement ), }).catch(err => { - log('error', 'rechercherPointResponse') - log('error', err) - Sentry.captureException('rechercherPointResponse', err) - throw errors.VENDOR_DOWN + const errorMessage = 'Error while finding user pdl : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'findUserPdl', + }, + extra: { + address: address, + postalCode: postalCode, + escalierEtEtageEtAppartement: escalierEtEtageEtAppartement, + }, + }) + throw new Error(errors.VENDOR_DOWN) }) const parsedReply = await xml2js.parseStringPromise(response.body, { @@ -247395,7 +247516,7 @@ const { removeDots, removeAddressNumber, } = __webpack_require__(1599) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) const { sanitizeLastname } = __webpack_require__(1729) /** @@ -247415,8 +247536,8 @@ async function verifyUserIdentity( isAlternateStart = false, inseeCode = '' ) { - // If first start get InseeCode log('debug', 'verifyUserIdentity') + // If first start get InseeCode if (!isAlternateStart) { inseeCode = await getInseeCode(fields.postalCode, fields.city) } @@ -247511,7 +247632,9 @@ async function verifyUserIdentity( } if (!pdl) { - Sentry.captureException('Second chance failed, no pdl found') + Sentry.captureException('Second chance failed, no pdl found', { + tags: { section: 'verifyUserIdentity' }, + }) } } @@ -247519,11 +247642,15 @@ async function verifyUserIdentity( log('error', 'PointId does not match') if (isAlternateStart) { - Sentry.captureException('PointId does not match: Alternate start') - throw errors.TERMS_VERSION_MISMATCH + Sentry.captureException('PointId does not match: Alternate start', { + tags: { section: 'verifyUserIdentity' }, + }) + throw new Error(errors.TERMS_VERSION_MISMATCH) } else { - Sentry.captureException('PointId does not match') - throw errors.LOGIN_FAILED + Sentry.captureException('PointId does not match', { + tags: { section: 'verifyUserIdentity' }, + }) + throw new Error(errors.LOGIN_FAILED) } } @@ -247547,8 +247674,8 @@ module.exports = { verifyUserIdentity } /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // @ts-check -const Sentry = __webpack_require__(1639) -const { default: axios } = __webpack_require__(1602) +const Sentry = __webpack_require__(1600) +const { default: axios } = __webpack_require__(1682) const { log, errors } = __webpack_require__(1) const API_URL = 'https://apicarto.ign.fr/api/codes-postaux/communes' @@ -247594,7 +247721,7 @@ async function getInseeCode(postalCode, city) { log('error', error.message) const errorMessage = `Query getInseeCode failed for postalCode ${postalCode} / ${city}` Sentry.captureException(errorMessage) - throw errors.USER_ACTION_NEEDED + throw new Error(errors.USER_ACTION_NEEDED) } } @@ -247651,8 +247778,8 @@ const { parseUserAddress, } = __webpack_require__(1599) const xml2js = __webpack_require__(1557) -const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1600) -const Sentry = __webpack_require__(1639) +const { consulterDonneesTechniquesContractuelles } = __webpack_require__(1680) +const Sentry = __webpack_require__(1600) /** * Get user contract start date @@ -247676,8 +247803,15 @@ async function findUserAddress(url, apiAuthKey, userLogin, pointId) { }).catch(err => { const errorMessage = 'Error while fetching user : ' + err log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { + section: 'findUserAddress', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errors.VENDOR_DOWN) }) const result = await xml2js.parseStringPromise(response.body, { @@ -247695,8 +247829,12 @@ async function findUserAddress(url, apiAuthKey, userLogin, pointId) { 'error', `Enedis issue ${result.Envelope.Body.Fault.detail.erreur.resultat.$.code}: ${result.Envelope.Body.Fault.faultstring}` ) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { + section: 'findUserAddress', + }, + }) + throw new Error(errors.VENDOR_DOWN) } } @@ -247863,8 +248001,8 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1734); /* harmony import */ var _browser_browsertracing_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1750); /* harmony import */ var _browser_request_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1753); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1717); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1707); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1678); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1668); @@ -247903,10 +248041,10 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "addExtensionMethods": () => (/* binding */ addExtensionMethods), /* harmony export */ "startIdleTransaction": () => (/* binding */ startIdleTransaction) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1645); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1606); /* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1738); /* harmony import */ var _idletransaction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1737); /* harmony import */ var _transaction_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1735); @@ -248225,9 +248363,9 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "msToSec": () => (/* binding */ msToSec), /* harmony export */ "secToMs": () => (/* binding */ secToMs) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1717); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1707); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1678); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1668); @@ -248280,11 +248418,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Transaction": () => (/* binding */ Transaction) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1688); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1650); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); /* harmony import */ var _span_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1736); @@ -248576,11 +248714,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "SpanRecorder": () => (/* binding */ SpanRecorder), /* harmony export */ "spanStatusfromHttpCode": () => (/* binding */ spanStatusfromHttpCode) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1688); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); @@ -248976,8 +249114,8 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "IdleTransaction": () => (/* binding */ IdleTransaction), /* harmony export */ "IdleTransactionSpanRecorder": () => (/* binding */ IdleTransactionSpanRecorder) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); /* harmony import */ var _span_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1736); /* harmony import */ var _transaction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1735); @@ -249293,7 +249431,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "registerErrorInstrumentation": () => (/* binding */ registerErrorInstrumentation) /* harmony export */ }); /* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1739); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1734); @@ -249331,12 +249469,12 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "addInstrumentationHandler": () => (/* binding */ addInstrumentationHandler) /* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1662); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); +/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); +/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1623); /* harmony import */ var _supports_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1740); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); @@ -249930,8 +250068,8 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "supportsReferrerPolicy": () => (/* binding */ supportsReferrerPolicy), /* harmony export */ "supportsReportingObserver": () => (/* binding */ supportsReportingObserver) /* harmony export */ }); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); +/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); @@ -250160,11 +250298,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Express": () => (/* binding */ Express) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1707); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1708); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1668); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1669); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1743); @@ -250515,7 +250653,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "shouldDisableAutoInstrumentation": () => (/* binding */ shouldDisableAutoInstrumentation) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1663); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1624); /** @@ -250544,11 +250682,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Postgres": () => (/* binding */ Postgres) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1645); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1743); @@ -250652,10 +250790,10 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Mysql": () => (/* binding */ Mysql) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1645); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1743); @@ -250735,11 +250873,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Mongo": () => (/* binding */ Mongo) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1645); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1743); @@ -250966,9 +251104,9 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Prisma": () => (/* binding */ Prisma) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1743); @@ -251062,11 +251200,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "GraphQL": () => (/* binding */ GraphQL) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1645); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1743); @@ -251146,12 +251284,12 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "Apollo": () => (/* binding */ Apollo) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1645); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1606); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1610); /* harmony import */ var _utils_node_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1743); @@ -251281,11 +251419,11 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "BrowserTracing": () => (/* binding */ BrowserTracing), /* harmony export */ "getMetaContent": () => (/* binding */ getMetaContent) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1717); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1695); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1651); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1678); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1656); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1612); /* harmony import */ var _hubextensions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1733); /* harmony import */ var _idletransaction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1737); /* harmony import */ var _backgroundtab_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1767); @@ -251491,7 +251629,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "instrumentRoutingWithDefaults": () => (/* binding */ instrumentRoutingWithDefaults) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); /* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1739); /* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1752); @@ -251567,7 +251705,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "WINDOW": () => (/* binding */ WINDOW) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); const WINDOW = _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; @@ -251591,9 +251729,9 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "xhrCallback": () => (/* binding */ xhrCallback) /* harmony export */ }); /* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1739); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1648); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1695); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1656); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1610); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1734); @@ -251872,10 +252010,10 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ "startTrackingLongTasks": () => (/* binding */ startTrackingLongTasks), /* harmony export */ "startTrackingWebVitals": () => (/* binding */ startTrackingWebVitals) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1688); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1651); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1612); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1734); /* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1752); /* harmony import */ var _web_vitals_getCLS_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1756); @@ -253065,7 +253203,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "registerBackgroundTabDetection": () => (/* binding */ registerBackgroundTabDetection) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1734); /* harmony import */ var _types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1752); diff --git a/onDeleteAccount.js b/onDeleteAccount.js index 71e230d..b241af4 100644 --- a/onDeleteAccount.js +++ b/onDeleteAccount.js @@ -228317,6 +228317,7 @@ module.exports = require("timers"); // @ts-check const { log } = __webpack_require__(1) const moment = __webpack_require__(1417) +const Sentry = __webpack_require__(1600) /** * Return User PDL @@ -228526,7 +228527,16 @@ function parsePointId(pointId) { } else if (strPointId.length === 13) { return `0${strPointId}` } else { - throw new Error(`PointId ${pointId} is malformed`) + const errorMessage = 'PointId is malformed' + Sentry.captureException(errorMessage, { + tags: { + section: 'parsePointId', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errorMessage) } } @@ -228551,17631 +228561,17660 @@ module.exports = { /***/ }), /* 1600 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), +/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), +/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), +/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), +/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), +/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), +/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), +/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), +/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), +/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), +/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), +/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), +/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), +/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), +/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), +/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), +/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), +/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), +/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), +/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), +/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), +/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), +/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), +/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), +/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), +/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), +/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), +/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), +/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), +/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), +/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), +/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), +/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), +/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), +/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), +/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1679); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1615); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1616); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1617); +/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1626); +/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1634); +/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1650); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1666); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1675); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); +/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1676); +/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1651); +/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1635); + + + + + + + + + + + + + +; +; + +; +; + +const INTEGRATIONS = { + ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, + ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, +}; + +// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like +// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. +const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); +if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; +} + + +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 1601 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), +/* harmony export */ "Hub": () => (/* binding */ Hub), +/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), +/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), +/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), +/* harmony export */ "makeMain": () => (/* binding */ makeMain), +/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1605); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1606); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1602); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1603); + -// @ts-check -const { log } = __webpack_require__(1) + + +const NIL_EVENT_ID = '00000000000000000000000000000000'; /** - * Get daily data up to 36 months & P max - * @param {string} pointId - * @param {string} appLogin - * @param {string} startDate - * @param {string} endDate - * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType - * @param {'EA' | 'PA' | 'PMA'} unit - * @returns {string} + * API compatibility version of this hub. + * + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * + * @hidden */ -function consultationMesuresDetaillees( - pointId, - appLogin, - startDate, - endDate, - mesureType = 'ENERGIE', - unit = 'EA' -) { - log( - 'info', - `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterMesuresDetaillees> - <demande> - <initiateurLogin>${appLogin}</initiateurLogin> - <pointId>${pointId}</pointId> - <mesuresTypeCode>${mesureType}</mesuresTypeCode> - <grandeurPhysique>${unit}</grandeurPhysique> - <soutirage>true</soutirage> - <injection>false</injection> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <mesuresCorrigees>false</mesuresCorrigees> - <accordClient>true</accordClient> - </demande> - </v2:consulterMesuresDetaillees> - </soapenv:Body> - </soapenv:Envelope> - ` -} +const API_VERSION = 4; /** - * Get user max power - * @param {string} pointId - * @param {string} appLogin - * @param {string} startDate - * @param {string} endDate - * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType - * @param {'EA' | 'PA' | 'PMA'} unit - * @returns {string} + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. */ -function consultationMesuresDetailleesMaxPower( - pointId, - appLogin, - startDate, - endDate, - mesureType = 'PMAX', - unit = 'PMA' -) { - log( - 'info', - `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterMesuresDetaillees> - <demande> - <initiateurLogin>${appLogin}</initiateurLogin> - <pointId>${pointId}</pointId> - <mesuresTypeCode>${mesureType}</mesuresTypeCode> - <grandeurPhysique>${unit}</grandeurPhysique> - <soutirage>true</soutirage> - <injection>false</injection> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <mesuresPas>P1D</mesuresPas> - <mesuresCorrigees>false</mesuresCorrigees> - <accordClient>true</accordClient> - </demande> - </v2:consulterMesuresDetaillees> - </soapenv:Body> - </soapenv:Envelope> - ` -} +const DEFAULT_BREADCRUMBS = 100; /** - * Get user technical data (contract start date) - * @param {string} pointId - * @param {string} appLogin - * @returns {string} + * A layer in the process stack. + * @hidden */ -function consulterDonneesTechniquesContractuelles( - pointId, - appLogin, - consent = true -) { - log('info', `Query consulterDonneesTechniquesContractuelles`) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/consulterdonneestechniquescontractuelles/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:consulterDonneesTechniquesContractuelles> - <pointId>${pointId}</pointId> - <loginUtilisateur>${appLogin}</loginUtilisateur> - <autorisationClient>${consent}</autorisationClient> - </v2:consulterDonneesTechniquesContractuelles> - </soapenv:Body> - </soapenv:Envelope> - ` -} /** - * Use rechercherPoint to find user PDL if exist - * @param {string} lastname - * @param {string} postalCode - * @param {string} inseeCode - * @param {string} address - * @param {string} [escalierEtEtageEtAppartement] - * @returns {string} PDL + * @inheritDoc */ -function rechercherPoint( - appLogin, - lastname, - postalCode, - inseeCode, - address, - escalierEtEtageEtAppartement -) { - log( - 'info', - `Query rechercherPoint - postal code : ${postalCode} / insee code: ${inseeCode}` - ) - if (escalierEtEtageEtAppartement) { - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherPoint> - <criteres> - <adresseInstallation> - <escalierEtEtageEtAppartement>${escalierEtEtageEtAppartement}</escalierEtEtageEtAppartement> - <numeroEtNomVoie>${address}</numeroEtNomVoie> - <codePostal>${postalCode}</codePostal> - <codeInseeCommune>${inseeCode}</codeInseeCommune> - </adresseInstallation> - <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> - <rechercheHorsPerimetre>true</rechercheHorsPerimetre> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherPoint> - </soapenv:Body> - </soapenv:Envelope>` - } - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherPoint> - <criteres> - <adresseInstallation> - <numeroEtNomVoie>${address}</numeroEtNomVoie> - <codePostal>${postalCode}</codePostal> - <codeInseeCommune>${inseeCode}</codeInseeCommune> - </adresseInstallation> - <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> - <rechercheHorsPerimetre>true</rechercheHorsPerimetre> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherPoint> - </soapenv:Body> - </soapenv:Envelope>` -} - -/** - * Search if user as a service - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @returns {*} - */ -function rechercherServicesSouscritsMesures(appLogin, contractId, pointId) { - log('info', `Query rechercherServicesSouscritsMesures`) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/rechercherservicessouscritsmesures/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:rechercherServicesSouscritsMesures> - <criteres> - <pointId>${pointId}</pointId> - <contratId>${contractId}</contratId> - </criteres> - <loginUtilisateur>${appLogin}</loginUtilisateur> - </v2:rechercherServicesSouscritsMesures> - </soapenv:Body> - </soapenv:Envelope>` -} - -/** - * Activate half hour data collect for user - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @param {string} lastname - * @param {string} startDate - * @param {string} endDate - * @returns {*} - */ -function commanderCollectePublicationMesures( - appLogin, - contractId, - pointId, - lastname, - startDate, - endDate -) { - log( - 'info', - `Query commanderCollectePublicationMesures - between ${startDate} and ${endDate}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/commandercollectepublicationmesures/v3.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:commanderCollectePublicationMesures> - <demande> - <donneesGenerales> - <objetCode>AME</objetCode> - <pointId>${pointId}</pointId> - <initiateurLogin>${appLogin}</initiateurLogin> - <contratId>${contractId}</contratId> - </donneesGenerales> - <accesMesures> - <dateDebut>${startDate}</dateDebut> - <dateFin>${endDate}</dateFin> - <declarationAccordClient> - <accord>true</accord> - <personnePhysique> - <nom>${lastname}</nom> - </personnePhysique> - </declarationAccordClient> - <mesuresTypeCode>CDC</mesuresTypeCode> - <soutirage>true</soutirage> - <injection>false</injection> - <mesuresPas>PT30M</mesuresPas> - <mesuresCorrigees>false</mesuresCorrigees> - <transmissionRecurrente>false</transmissionRecurrente> - <periodiciteTransmission>P1D</periodiciteTransmission> - </accesMesures> - </demande> - </v2:commanderCollectePublicationMesures> - </soapenv:Body> - </soapenv:Envelope>` -} - -/** - * Stop the user consent - * @param {string} appLogin - * @param {string} contractId - * @param {string} pointId - * @param {number} serviceSouscritId - * @returns {*} - */ -function commanderArretServiceSouscritMesures( - appLogin, - contractId, - pointId, - serviceSouscritId -) { - log( - 'info', - `Query commanderArretServiceSouscritMesures - serviceSouscritId: ${serviceSouscritId}` - ) - return `<?xml version='1.0' encoding='utf-8'?> - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" - xmlns:v2="http://www.enedis.fr/sge/b2b/commanderarretservicesouscritmesures/v1.0" - xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> - <soapenv:Header/> - <soapenv:Body> - <v2:commanderArretServiceSouscritMesures> - <demande> - <donneesGenerales> - <objetCode>ASS</objetCode> - <pointId>${pointId}</pointId> - <initiateurLogin>${appLogin}</initiateurLogin> - <contratId>${contractId}</contratId> - </donneesGenerales> - <arretServiceSouscrit> - <serviceSouscritId>${serviceSouscritId}</serviceSouscritId> - </arretServiceSouscrit> - </demande> - </v2:commanderArretServiceSouscritMesures> - </soapenv:Body> - </soapenv:Envelope>` -} - -module.exports = { - consulterDonneesTechniquesContractuelles, - consultationMesuresDetailleesMaxPower, - consultationMesuresDetaillees, - rechercherPoint, - rechercherServicesSouscritsMesures, - commanderCollectePublicationMesures, - commanderArretServiceSouscritMesures, -} - - -/***/ }), -/* 1601 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// @ts-check -const { log, errors } = __webpack_require__(1) -const { default: axios } = __webpack_require__(1602) -const Sentry = __webpack_require__(1639) - -/** - * @param {string} pointID - * @param {string} lastname - * @param {string} firstname - * @param {string} address - * @param {string} postalCode - * @param {string} inseeCode - * @param {string} city - * @param {boolean} safetyOnBoarding - * @returns {Promise<Consent>} - */ -async function createBoConsent( - url, - token, - pointID, - lastname, - firstname, - address, - postalCode, - inseeCode, - city, - safetyOnBoarding -) { - log('info', `Query createBoConsent`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, - } - - try { - const { data } = await axios.post( - `${url}/consent`, - { - pointID, - lastname, - firstname, - address, - postalCode, - inseeCode, - city, - safetyOnBoarding, - }, - headers - ) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE - } -} - -/** - * @param {string} url - * @param {string} token - * @param {Consent} consent - * @param {string} serviceId - * @returns {Promise<Consent>} - */ -async function updateBoConsent(url, token, consent, serviceId) { - log('info', `Query updateBoConsent`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, - } - - try { - let consentId = '' - if (consent.ID) { - consentId = consent.ID.toString() - } - const { data } = await axios.put( - `${url}/consent/${consentId}`, - { - ...consent, - serviceId: parseInt(serviceId), - }, - headers - ) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE - } -} - -/** - * @param {number} boId - * @returns {Promise<Consent>} - */ -async function getBoConsent(url, token, boId) { - log('info', `Query getBoConsent ${boId}`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, - } - try { - const { data } = await axios.get(`${url}/consent/${boId}`, headers) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE - } -} - -/** - * Delete BO consent - * @param {string} url - * @param {string} token - * @param {number} boId - * @returns - */ -async function deleteBoConsent(url, token, boId) { - log('info', `Query deleteBoConsent ${boId}`) - const headers = { - headers: { - Authorization: `Bearer ${token}`, - }, - } - try { - const { data } = await axios.delete(`${url}/consent/${boId}`, headers) - return data - } catch (e) { - const errorMessage = `BO replied with ${e}` - log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.MAINTENANCE - } -} - -module.exports = { - createBoConsent, - updateBoConsent, - getBoConsent, - deleteBoConsent, -} - - -/***/ }), -/* 1602 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = __webpack_require__(1603); - -/***/ }), -/* 1603 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(1604); -var bind = __webpack_require__(1605); -var Axios = __webpack_require__(1606); -var mergeConfig = __webpack_require__(1634); -var defaults = __webpack_require__(1611); - -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * @return {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - var context = new Axios(defaultConfig); - var instance = bind(Axios.prototype.request, context); - - // Copy axios.prototype to instance - utils.extend(instance, Axios.prototype, context); - - // Copy context to instance - utils.extend(instance, context); - - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - - return instance; -} - -// Create the default instance to be exported -var axios = createInstance(defaults); - -// Expose Axios class to allow class inheritance -axios.Axios = Axios; - -// Expose Cancel & CancelToken -axios.CanceledError = __webpack_require__(1624); -axios.CancelToken = __webpack_require__(1636); -axios.isCancel = __webpack_require__(1633); -axios.VERSION = (__webpack_require__(1629).version); -axios.toFormData = __webpack_require__(1615); - -// Expose AxiosError class -axios.AxiosError = __webpack_require__(1613); - -// alias for CanceledError for backward compatibility -axios.Cancel = axios.CanceledError; - -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = __webpack_require__(1637); - -// Expose isAxiosError -axios.isAxiosError = __webpack_require__(1638); - -module.exports = axios; - -// Allow use of default import syntax in TypeScript -module.exports["default"] = axios; - - -/***/ }), -/* 1604 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var bind = __webpack_require__(1605); - -// utils is a library of generic helper functions non-specific to axios - -var toString = Object.prototype.toString; - -// eslint-disable-next-line func-names -var kindOf = (function(cache) { - // eslint-disable-next-line func-names - return function(thing) { - var str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); - }; -})(Object.create(null)); - -function kindOfTest(type) { - type = type.toLowerCase(); - return function isKindOf(thing) { - return kindOf(thing) === type; - }; -} - -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Array, otherwise false - */ -function isArray(val) { - return Array.isArray(val); -} - -/** - * Determine if a value is undefined - * - * @param {Object} val The value to test - * @returns {boolean} True if the value is undefined, otherwise false - */ -function isUndefined(val) { - return typeof val === 'undefined'; -} - -/** - * Determine if a value is a Buffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); -} - -/** - * Determine if a value is an ArrayBuffer - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -var isArrayBuffer = kindOfTest('ArrayBuffer'); - - -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - var result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); - } - return result; -} - -/** - * Determine if a value is a String - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a String, otherwise false - */ -function isString(val) { - return typeof val === 'string'; -} - -/** - * Determine if a value is a Number - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Number, otherwise false - */ -function isNumber(val) { - return typeof val === 'number'; -} - -/** - * Determine if a value is an Object - * - * @param {Object} val The value to test - * @returns {boolean} True if value is an Object, otherwise false - */ -function isObject(val) { - return val !== null && typeof val === 'object'; -} - -/** - * Determine if a value is a plain Object - * - * @param {Object} val The value to test - * @return {boolean} True if value is a plain Object, otherwise false - */ -function isPlainObject(val) { - if (kindOf(val) !== 'object') { - return false; - } - - var prototype = Object.getPrototypeOf(val); - return prototype === null || prototype === Object.prototype; -} - -/** - * Determine if a value is a Date - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a Date, otherwise false - */ -var isDate = kindOfTest('Date'); - -/** - * Determine if a value is a File - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -var isFile = kindOfTest('File'); - -/** - * Determine if a value is a Blob - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a Blob, otherwise false - */ -var isBlob = kindOfTest('Blob'); - -/** - * Determine if a value is a FileList - * - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a File, otherwise false - */ -var isFileList = kindOfTest('FileList'); - -/** - * Determine if a value is a Function - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -function isFunction(val) { - return toString.call(val) === '[object Function]'; -} - -/** - * Determine if a value is a Stream - * - * @param {Object} val The value to test - * @returns {boolean} True if value is a Stream, otherwise false - */ -function isStream(val) { - return isObject(val) && isFunction(val.pipe); -} - -/** - * Determine if a value is a FormData - * - * @param {Object} thing The value to test - * @returns {boolean} True if value is an FormData, otherwise false - */ -function isFormData(thing) { - var pattern = '[object FormData]'; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || - toString.call(thing) === pattern || - (isFunction(thing.toString) && thing.toString() === pattern) - ); -} - -/** - * Determine if a value is a URLSearchParams object - * @function - * @param {Object} val The value to test - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -var isURLSearchParams = kindOfTest('URLSearchParams'); - -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * @returns {String} The String freed of excess whitespace - */ -function trim(str) { - return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); -} - -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - */ -function isStandardBrowserEnv() { - if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || - navigator.product === 'NativeScript' || - navigator.product === 'NS')) { - return false; - } - return ( - typeof window !== 'undefined' && - typeof document !== 'undefined' - ); -} - -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - */ -function forEach(obj, fn) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - - if (isArray(obj)) { - // Iterate over array values - for (var i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Iterate over object keys - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - fn.call(null, obj[key], key, obj); - } - } - } -} - -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - var result = {}; - function assignValue(val, key) { - if (isPlainObject(result[key]) && isPlainObject(val)) { - result[key] = merge(result[key], val); - } else if (isPlainObject(val)) { - result[key] = merge({}, val); - } else if (isArray(val)) { - result[key] = val.slice(); - } else { - result[key] = val; - } - } - - for (var i = 0, l = arguments.length; i < l; i++) { - forEach(arguments[i], assignValue); - } - return result; -} - -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * @return {Object} The resulting value of object a - */ -function extend(a, b, thisArg) { - forEach(b, function assignValue(val, key) { - if (thisArg && typeof val === 'function') { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }); - return a; -} - -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * @return {string} content value without BOM - */ -function stripBOM(content) { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} - -/** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - */ - -function inherits(constructor, superConstructor, props, descriptors) { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - props && Object.assign(constructor.prototype, props); -} - -/** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function} [filter] - * @returns {Object} - */ - -function toFlatObject(sourceObj, destObj, filter) { - var props; - var i; - var prop; - var merged = {}; - - destObj = destObj || {}; - - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if (!merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = Object.getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - - return destObj; -} - -/* - * determines whether a string ends with the characters of a specified string - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * @returns {boolean} - */ -function endsWith(str, searchString, position) { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - var lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -} +class Hub { + /** Is a {@link Layer}[] containing the client and scope */ + __init() {this._stack = [{}];} + /** Contains the last event id of a captured event. */ -/** - * Returns new array from array like object - * @param {*} [thing] - * @returns {Array} - */ -function toArray(thing) { - if (!thing) return null; - var i = thing.length; - if (isUndefined(i)) return null; - var arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; + /** + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. + */ + constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); + this.getStackTop().scope = scope; + if (client) { + this.bindClient(client); + } } - return arr; -} - -// eslint-disable-next-line func-names -var isTypedArray = (function(TypedArray) { - // eslint-disable-next-line func-names - return function(thing) { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); - -module.exports = { - isArray: isArray, - isArrayBuffer: isArrayBuffer, - isBuffer: isBuffer, - isFormData: isFormData, - isArrayBufferView: isArrayBufferView, - isString: isString, - isNumber: isNumber, - isObject: isObject, - isPlainObject: isPlainObject, - isUndefined: isUndefined, - isDate: isDate, - isFile: isFile, - isBlob: isBlob, - isFunction: isFunction, - isStream: isStream, - isURLSearchParams: isURLSearchParams, - isStandardBrowserEnv: isStandardBrowserEnv, - forEach: forEach, - merge: merge, - extend: extend, - trim: trim, - stripBOM: stripBOM, - inherits: inherits, - toFlatObject: toFlatObject, - kindOf: kindOf, - kindOfTest: kindOfTest, - endsWith: endsWith, - toArray: toArray, - isTypedArray: isTypedArray, - isFileList: isFileList -}; - - -/***/ }), -/* 1605 */ -/***/ ((module) => { - -"use strict"; + /** + * @inheritDoc + */ + isOlderThan(version) { + return this._version < version; + } -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + /** + * @inheritDoc + */ + bindClient(client) { + const top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); } - return fn.apply(thisArg, args); - }; -}; - - -/***/ }), -/* 1606 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + } -"use strict"; + /** + * @inheritDoc + */ + pushScope() { + // We want to clone the content of prev scope + const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); + this.getStack().push({ + client: this.getClient(), + scope, + }); + return scope; + } + /** + * @inheritDoc + */ + popScope() { + if (this.getStack().length <= 1) return false; + return !!this.getStack().pop(); + } -var utils = __webpack_require__(1604); -var buildURL = __webpack_require__(1607); -var InterceptorManager = __webpack_require__(1608); -var dispatchRequest = __webpack_require__(1609); -var mergeConfig = __webpack_require__(1634); -var buildFullPath = __webpack_require__(1619); -var validator = __webpack_require__(1635); + /** + * @inheritDoc + */ + withScope(callback) { + const scope = this.pushScope(); + try { + callback(scope); + } finally { + this.popScope(); + } + } -var validators = validator.validators; -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - */ -function Axios(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; -} + /** + * @inheritDoc + */ + getClient() { + return this.getStackTop().client ; + } -/** - * Dispatch a request - * - * @param {Object} config The config specific for this request (merged with this.defaults) - */ -Axios.prototype.request = function request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; + /** Returns the scope of the top stack. */ + getScope() { + return this.getStackTop().scope; } - config = mergeConfig(this.defaults, config); + /** Returns the scope stack for domains or the process. */ + getStack() { + return this._stack; + } - // Set config.method - if (config.method) { - config.method = config.method.toLowerCase(); - } else if (this.defaults.method) { - config.method = this.defaults.method.toLowerCase(); - } else { - config.method = 'get'; + /** Returns the topmost scope layer in the order domain > local > process. */ + getStackTop() { + return this._stack[this._stack.length - 1]; } - var transitional = config.transitional; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint) { + const syntheticException = new Error('Sentry syntheticException'); + this._lastEventId = + this._withClient((client, scope) => { + return client.captureException( + exception, + { + originalException: exception, + syntheticException, + ...hint, + }, + scope, + ); + }) || NIL_EVENT_ID; + return this._lastEventId; + } - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); + /** + * @inheritDoc + */ + captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level, + hint, + ) { + const syntheticException = new Error(message); + this._lastEventId = + this._withClient((client, scope) => { + return client.captureMessage( + message, + level, + { + originalException: message, + syntheticException, + ...hint, + }, + scope, + ); + }) || NIL_EVENT_ID; + return this._lastEventId; } - // filter out skipped interceptors - var requestInterceptorChain = []; - var synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; + /** + * @inheritDoc + */ + captureEvent(event, hint) { + const clientId = + this._withClient((client, scope) => { + return client.captureEvent(event, { ...hint }, scope); + }) || NIL_EVENT_ID; + + if (event.type !== 'transaction') { + this._lastEventId = clientId; } - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); + return clientId; + } - var responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); + /** + * @inheritDoc + */ + lastEventId() { + return this._lastEventId; + } - var promise; + /** + * @inheritDoc + */ + addBreadcrumb(breadcrumb, hint) { + const { scope, client } = this.getStackTop(); - if (!synchronousRequestInterceptors) { - var chain = [dispatchRequest, undefined]; + if (!scope || !client) return; - Array.prototype.unshift.apply(chain, requestInterceptorChain); - chain = chain.concat(responseInterceptorChain); + // eslint-disable-next-line @typescript-eslint/unbound-method + const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = + (client.getOptions && client.getOptions()) || {}; - promise = Promise.resolve(config); - while (chain.length) { - promise = promise.then(chain.shift(), chain.shift()); - } + if (maxBreadcrumbs <= 0) return; - return promise; - } + const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); + const mergedBreadcrumb = { timestamp, ...breadcrumb }; + const finalBreadcrumb = beforeBreadcrumb + ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) + : mergedBreadcrumb; + if (finalBreadcrumb === null) return; - var newConfig = config; - while (requestInterceptorChain.length) { - var onFulfilled = requestInterceptorChain.shift(); - var onRejected = requestInterceptorChain.shift(); - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected(error); - break; - } + scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); } - try { - promise = dispatchRequest(newConfig); - } catch (error) { - return Promise.reject(error); + /** + * @inheritDoc + */ + setUser(user) { + const scope = this.getScope(); + if (scope) scope.setUser(user); } - while (responseInterceptorChain.length) { - promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + /** + * @inheritDoc + */ + setTags(tags) { + const scope = this.getScope(); + if (scope) scope.setTags(tags); } - return promise; -}; - -Axios.prototype.getUri = function getUri(config) { - config = mergeConfig(this.defaults, config); - var fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); -}; - -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method: method, - url: url, - data: (config || {}).data - })); - }; -}); + /** + * @inheritDoc + */ + setExtras(extras) { + const scope = this.getScope(); + if (scope) scope.setExtras(extras); + } -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ + /** + * @inheritDoc + */ + setTag(key, value) { + const scope = this.getScope(); + if (scope) scope.setTag(key, value); + } - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method: method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url: url, - data: data - })); - }; + /** + * @inheritDoc + */ + setExtra(key, extra) { + const scope = this.getScope(); + if (scope) scope.setExtra(key, extra); } - Axios.prototype[method] = generateHTTPMethod(); + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setContext(name, context) { + const scope = this.getScope(); + if (scope) scope.setContext(name, context); + } - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); -}); + /** + * @inheritDoc + */ + configureScope(callback) { + const { scope, client } = this.getStackTop(); + if (scope && client) { + callback(scope); + } + } -module.exports = Axios; + /** + * @inheritDoc + */ + run(callback) { + const oldHub = makeMain(this); + try { + callback(this); + } finally { + makeMain(oldHub); + } + } + /** + * @inheritDoc + */ + getIntegration(integration) { + const client = this.getClient(); + if (!client) return null; + try { + return client.getIntegration(integration); + } catch (_oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); + return null; + } + } -/***/ }), -/* 1607 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + startTransaction(context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); + } -"use strict"; + /** + * @inheritDoc + */ + traceHeaders() { + return this._callExtensionMethod('traceHeaders'); + } + /** + * @inheritDoc + */ + captureSession(endSession = false) { + // both send the update and pull the session from the scope + if (endSession) { + return this.endSession(); + } -var utils = __webpack_require__(1604); + // only send the update + this._sendSessionUpdate(); + } -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} + /** + * @inheritDoc + */ + endSession() { + const layer = this.getStackTop(); + const scope = layer && layer.scope; + const session = scope && scope.getSession(); + if (session) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); + } + this._sendSessionUpdate(); -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; + // the session is over; take it off of the scope + if (scope) { + scope.setSession(); + } } - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; - - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } + /** + * @inheritDoc + */ + startSession(context) { + const { scope, client } = this.getStackTop(); + const { release, environment } = (client && client.getOptions()) || {}; - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } + // Will fetch userAgent if called from browser sdk + const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); + const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ + release, + environment, + ...(scope && { user: scope.getUser() }), + ...(userAgent && { userAgent }), + ...context, }); - serializedParams = parts.join('&'); - } + if (scope) { + // End existing session if there's one + const currentSession = scope.getSession && scope.getSession(); + if (currentSession && currentSession.status === 'ok') { + (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); + } + this.endSession(); - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); + // Afterwards we set the new session on the scope + scope.setSession(session); } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + return session; } - return url; -}; - - -/***/ }), -/* 1608 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * Returns if default PII should be sent to Sentry and propagated in ourgoing requests + * when Tracing is used. + */ + shouldSendDefaultPii() { + const client = this.getClient(); + const options = client && client.getOptions(); + return Boolean(options && options.sendDefaultPii); + } -"use strict"; + /** + * Sends the current Session on the scope + */ + _sendSessionUpdate() { + const { scope, client } = this.getStackTop(); + if (!scope) return; + const session = scope.getSession(); + if (session) { + if (client && client.captureSession) { + client.captureSession(session); + } + } + } -var utils = __webpack_require__(1604); + /** + * Internal helper function to call a method on the top client if it exists. + * + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. + */ + _withClient(callback) { + const { scope, client } = this.getStackTop(); + return client && callback(client, scope); + } -function InterceptorManager() { - this.handlers = []; + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _callExtensionMethod(method, ...args) { + const carrier = getMainCarrier(); + const sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); + } + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); + } } /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` + * Returns the global shim registry. * - * @return {Number} An ID used to remove interceptor later - */ -InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled: fulfilled, - rejected: rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; -}; + * FIXME: This function is problematic, because despite always returning a valid Carrier, + * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check + * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. + **/ +function getMainCarrier() { + _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; +} /** - * Remove an interceptor from the stack + * Replaces the current main hub with the passed one on the global object * - * @param {Number} id The ID that was returned by `use` + * @returns The old replaced hub */ -InterceptorManager.prototype.eject = function eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; - } -}; +function makeMain(hub) { + const registry = getMainCarrier(); + const oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; +} /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. + * Returns the default hub instance. * - * @param {Function} fn The function to call for each interceptor + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. */ -InterceptorManager.prototype.forEach = function forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); -}; - -module.exports = InterceptorManager; - - -/***/ }), -/* 1609 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var utils = __webpack_require__(1604); -var transformData = __webpack_require__(1610); -var isCancel = __webpack_require__(1633); -var defaults = __webpack_require__(1611); -var CanceledError = __webpack_require__(1624); +function getCurrentHub() { + // Get main carrier (global for every environment) + const registry = getMainCarrier(); -/** - * Throws a `CanceledError` if cancellation has been requested. - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); + // If there's no hub, or its an old API, assign a new one + if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { + setHubOnCarrier(registry, new Hub()); } - if (config.signal && config.signal.aborted) { - throw new CanceledError(); + // Prefer domains over global if they are there (applicable only to Node environment) + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { + return getHubFromActiveDomain(registry); } + // Return hub that lives on a global object + return getHubFromCarrier(registry); } /** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * @returns {Promise} The Promise to be fulfilled + * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist + * @returns discovered hub */ -module.exports = function dispatchRequest(config) { - throwIfCancellationRequested(config); - - // Ensure headers exist - config.headers = config.headers || {}; - - // Transform request data - config.data = transformData.call( - config, - config.data, - config.headers, - config.transformRequest - ); - - // Flatten headers - config.headers = utils.merge( - config.headers.common || {}, - config.headers[config.method] || {}, - config.headers - ); - - utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - function cleanHeaderConfig(method) { - delete config.headers[method]; - } - ); - - var adapter = config.adapter || defaults.adapter; - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - response.data, - response.headers, - config.transformResponse - ); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - reason.response.data, - reason.response.headers, - config.transformResponse - ); - } - } - - return Promise.reject(reason); - }); -}; +function getHubFromActiveDomain(registry) { + try { + const sentry = getMainCarrier().__SENTRY__; + const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; + // If there's no active domain, just return global hub + if (!activeDomain) { + return getHubFromCarrier(registry); + } -/***/ }), -/* 1610 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // If there's no hub on current domain, or it's an old API, assign a new one + if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { + const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); + setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(registryHubTopStack.scope))); + } -"use strict"; + // Return hub that lives on a domain + return getHubFromCarrier(activeDomain); + } catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); + } +} +/** + * This will tell whether a carrier has a hub on it or not + * @param carrier object + */ +function hasHubOnCarrier(carrier) { + return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); +} -var utils = __webpack_require__(1604); -var defaults = __webpack_require__(1611); +/** + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden + */ +function getHubFromCarrier(carrier) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); +} /** - * Transform the data for a request or a response - * - * @param {Object|String} data The data to be transformed - * @param {Array} headers The headers for the request or response - * @param {Array|Function} fns A single function or Array of functions - * @returns {*} The resulting transformed data + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + * @returns A boolean indicating success or failure */ -module.exports = function transformData(data, headers, fns) { - var context = this || defaults; - /*eslint no-param-reassign:0*/ - utils.forEach(fns, function transform(fn) { - data = fn.call(context, data, headers); - }); +function setHubOnCarrier(carrier, hub) { + if (!carrier) return false; + const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); + __SENTRY__.hub = hub; + return true; +} - return data; -}; + +//# sourceMappingURL=hub.js.map /***/ }), -/* 1611 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1602 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Scope": () => (/* binding */ Scope), +/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1605); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1603); -var utils = __webpack_require__(1604); -var normalizeHeaderName = __webpack_require__(1612); -var AxiosError = __webpack_require__(1613); -var transitionalDefaults = __webpack_require__(1614); -var toFormData = __webpack_require__(1615); -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' -}; +/** + * Default value for maximum number of breadcrumbs added to an event. + */ +const DEFAULT_MAX_BREADCRUMBS = 100; -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} +/** + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. + */ +class Scope { + /** Flag if notifying is happening. */ -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __webpack_require__(1616); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __webpack_require__(1626); - } - return adapter; -} + /** Callback for client to receive scope changes. */ -function stringifySafely(rawValue, parser, encoder) { - if (utils.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } + /** Callback list that will be called after {@link applyToEvent}. */ - return (encoder || JSON.stringify)(rawValue); -} + /** Array of breadcrumbs. */ -var defaults = { + /** User */ - transitional: transitionalDefaults, + /** Tags */ - adapter: getDefaultAdapter(), + /** Extra */ - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); + /** Contexts */ - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } + /** Attachments */ - var isObjectPayload = utils.isObject(data); - var contentType = headers && headers['Content-Type']; + /** + * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get + * sent to Sentry + */ - var isFileList; + /** Fingerprint */ - if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { - var _FormData = this.env && this.env.FormData; - return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); - } else if (isObjectPayload || contentType === 'application/json') { - setContentTypeIfUnset(headers, 'application/json'); - return stringifySafely(data); - } + /** Severity */ + // eslint-disable-next-line deprecation/deprecation - return data; - }], + /** Transaction Name */ - transformResponse: [function transformResponse(data) { - var transitional = this.transitional || defaults.transitional; - var silentJSONParsing = transitional && transitional.silentJSONParsing; - var forcedJSONParsing = transitional && transitional.forcedJSONParsing; - var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; + /** Span */ - if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } - } + /** Session */ - return data; - }], + /** Request Mode Session Status */ - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, + // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', + constructor() { + this._notifyingListeners = false; + this._scopeListeners = []; + this._eventProcessors = []; + this._breadcrumbs = []; + this._attachments = []; + this._user = {}; + this._tags = {}; + this._extra = {}; + this._contexts = {}; + this._sdkProcessingMetadata = {}; + } - maxContentLength: -1, - maxBodyLength: -1, + /** + * Inherit values from the parent scope. + * @param scope to clone. + */ + static clone(scope) { + const newScope = new Scope(); + if (scope) { + newScope._breadcrumbs = [...scope._breadcrumbs]; + newScope._tags = { ...scope._tags }; + newScope._extra = { ...scope._extra }; + newScope._contexts = { ...scope._contexts }; + newScope._user = scope._user; + newScope._level = scope._level; + newScope._span = scope._span; + newScope._session = scope._session; + newScope._transactionName = scope._transactionName; + newScope._fingerprint = scope._fingerprint; + newScope._eventProcessors = [...scope._eventProcessors]; + newScope._requestSession = scope._requestSession; + newScope._attachments = [...scope._attachments]; + newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; + } + return newScope; + } - env: { - FormData: __webpack_require__(1630) - }, + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + addScopeListener(callback) { + this._scopeListeners.push(callback); + } - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, + /** + * @inheritDoc + */ + addEventProcessor(callback) { + this._eventProcessors.push(callback); + return this; + } - headers: { - common: { - 'Accept': 'application/json, text/plain, */*' + /** + * @inheritDoc + */ + setUser(user) { + this._user = user || {}; + if (this._session) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); } + this._notifyScopeListeners(); + return this; } -}; -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); + /** + * @inheritDoc + */ + getUser() { + return this._user; + } -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); + /** + * @inheritDoc + */ + getRequestSession() { + return this._requestSession; + } -module.exports = defaults; + /** + * @inheritDoc + */ + setRequestSession(requestSession) { + this._requestSession = requestSession; + return this; + } + /** + * @inheritDoc + */ + setTags(tags) { + this._tags = { + ...this._tags, + ...tags, + }; + this._notifyScopeListeners(); + return this; + } -/***/ }), -/* 1612 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + setTag(key, value) { + this._tags = { ...this._tags, [key]: value }; + this._notifyScopeListeners(); + return this; + } -"use strict"; + /** + * @inheritDoc + */ + setExtras(extras) { + this._extra = { + ...this._extra, + ...extras, + }; + this._notifyScopeListeners(); + return this; + } + /** + * @inheritDoc + */ + setExtra(key, extra) { + this._extra = { ...this._extra, [key]: extra }; + this._notifyScopeListeners(); + return this; + } -var utils = __webpack_require__(1604); + /** + * @inheritDoc + */ + setFingerprint(fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + } -module.exports = function normalizeHeaderName(headers, normalizedName) { - utils.forEach(headers, function processHeader(value, name) { - if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { - headers[normalizedName] = value; - delete headers[name]; - } - }); -}; + /** + * @inheritDoc + */ + setLevel( + // eslint-disable-next-line deprecation/deprecation + level, + ) { + this._level = level; + this._notifyScopeListeners(); + return this; + } + /** + * @inheritDoc + */ + setTransactionName(name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + } -/***/ }), -/* 1613 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + /** + * @inheritDoc + */ + setContext(key, context) { + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; + } else { + this._contexts[key] = context; + } -"use strict"; + this._notifyScopeListeners(); + return this; + } + /** + * @inheritDoc + */ + setSpan(span) { + this._span = span; + this._notifyScopeListeners(); + return this; + } -var utils = __webpack_require__(1604); + /** + * @inheritDoc + */ + getSpan() { + return this._span; + } -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -function AxiosError(message, code, config, request, response) { - Error.call(this); - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); -} + /** + * @inheritDoc + */ + getTransaction() { + // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will + // have a pointer to the currently-active transaction. + const span = this.getSpan(); + return span && span.transaction; + } -utils.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: this.config, - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; + /** + * @inheritDoc + */ + setSession(session) { + if (!session) { + delete this._session; + } else { + this._session = session; + } + this._notifyScopeListeners(); + return this; } -}); -var prototype = AxiosError.prototype; -var descriptors = {}; + /** + * @inheritDoc + */ + getSession() { + return this._session; + } -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED' -// eslint-disable-next-line func-names -].forEach(function(code) { - descriptors[code] = {value: code}; -}); + /** + * @inheritDoc + */ + update(captureContext) { + if (!captureContext) { + return this; + } -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype, 'isAxiosError', {value: true}); + if (typeof captureContext === 'function') { + const updatedScope = (captureContext )(this); + return updatedScope instanceof Scope ? updatedScope : this; + } -// eslint-disable-next-line func-names -AxiosError.from = function(error, code, config, request, response, customProps) { - var axiosError = Object.create(prototype); + if (captureContext instanceof Scope) { + this._tags = { ...this._tags, ...captureContext._tags }; + this._extra = { ...this._extra, ...captureContext._extra }; + this._contexts = { ...this._contexts, ...captureContext._contexts }; + if (captureContext._user && Object.keys(captureContext._user).length) { + this._user = captureContext._user; + } + if (captureContext._level) { + this._level = captureContext._level; + } + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; + } + if (captureContext._requestSession) { + this._requestSession = captureContext._requestSession; + } + } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { + // eslint-disable-next-line no-param-reassign + captureContext = captureContext ; + this._tags = { ...this._tags, ...captureContext.tags }; + this._extra = { ...this._extra, ...captureContext.extra }; + this._contexts = { ...this._contexts, ...captureContext.contexts }; + if (captureContext.user) { + this._user = captureContext.user; + } + if (captureContext.level) { + this._level = captureContext.level; + } + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; + } + if (captureContext.requestSession) { + this._requestSession = captureContext.requestSession; + } + } - utils.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }); + return this; + } - AxiosError.call(axiosError, error.message, code, config, request, response); + /** + * @inheritDoc + */ + clear() { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._requestSession = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + this._attachments = []; + return this; + } - axiosError.name = error.name; + /** + * @inheritDoc + */ + addBreadcrumb(breadcrumb, maxBreadcrumbs) { + const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; - customProps && Object.assign(axiosError, customProps); + // No data has been changed, so don't notify scope listeners + if (maxCrumbs <= 0) { + return this; + } - return axiosError; -}; + const mergedBreadcrumb = { + timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), + ...breadcrumb, + }; + this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); + this._notifyScopeListeners(); -module.exports = AxiosError; + return this; + } + /** + * @inheritDoc + */ + clearBreadcrumbs() { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + } -/***/ }), -/* 1614 */ -/***/ ((module) => { + /** + * @inheritDoc + */ + addAttachment(attachment) { + this._attachments.push(attachment); + return this; + } -"use strict"; + /** + * @inheritDoc + */ + getAttachments() { + return this._attachments; + } + /** + * @inheritDoc + */ + clearAttachments() { + this._attachments = []; + return this; + } -module.exports = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}; + /** + * Applies data from the scope to the event and runs all event processors on it. + * + * @param event Event + * @param hint Object containing additional information about the original exception, for use by the event processors. + * @hidden + */ + applyToEvent(event, hint = {}) { + if (this._extra && Object.keys(this._extra).length) { + event.extra = { ...this._extra, ...event.extra }; + } + if (this._tags && Object.keys(this._tags).length) { + event.tags = { ...this._tags, ...event.tags }; + } + if (this._user && Object.keys(this._user).length) { + event.user = { ...this._user, ...event.user }; + } + if (this._contexts && Object.keys(this._contexts).length) { + event.contexts = { ...this._contexts, ...event.contexts }; + } + if (this._level) { + event.level = this._level; + } + if (this._transactionName) { + event.transaction = this._transactionName; + } + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relies on that. + if (this._span) { + event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; + const transactionName = this._span.transaction && this._span.transaction.name; + if (transactionName) { + event.tags = { transaction: transactionName, ...event.tags }; + } + } -/***/ }), -/* 1615 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this._applyFingerprint(event); -"use strict"; + event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; + event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; + event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; -var utils = __webpack_require__(1604); + return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); + } -/** - * Convert a data object to FormData - * @param {Object} obj - * @param {?Object} [formData] - * @returns {Object} - **/ + /** + * Add data which will be accessible during event processing but won't get sent to Sentry + */ + setSDKProcessingMetadata(newData) { + this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; -function toFormData(obj, formData) { - // eslint-disable-next-line no-param-reassign - formData = formData || new FormData(); + return this; + } - var stack = []; + /** + * This will be called after {@link applyToEvent} is finished. + */ + _notifyEventProcessors( + processors, + event, + hint, + index = 0, + ) { + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { + const processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } else { + const result = processor({ ...event }, hint) ; - function convertValue(value) { - if (value === null) return ''; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + processor.id && + result === null && + _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); - if (utils.isDate(value)) { - return value.toISOString(); - } + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { + void result + .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) + .then(null, reject); + } else { + void this._notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } + }); + } - if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { - return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + /** + * This will be called on every set call. + */ + _notifyScopeListeners() { + // We need this check for this._notifyingListeners to be able to work on scope during updates + // If this check is not here we'll produce endless recursion when something is done with the scope + // during the callback. + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach(callback => { + callback(this); + }); + this._notifyingListeners = false; } - - return value; } - function build(data, parentKey) { - if (utils.isPlainObject(data) || utils.isArray(data)) { - if (stack.indexOf(data) !== -1) { - throw Error('Circular reference detected in ' + parentKey); - } - - stack.push(data); - - utils.forEach(data, function each(value, key) { - if (utils.isUndefined(value)) return; - var fullKey = parentKey ? parentKey + '.' + key : key; - var arr; - - if (value && !parentKey && typeof value === 'object') { - if (utils.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { - // eslint-disable-next-line func-names - arr.forEach(function(el) { - !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); - }); - return; - } - } + /** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ + _applyFingerprint(event) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(event.fingerprint) : []; - build(value, fullKey); - }); + // If we have something on the scope, then merge it with event + if (this._fingerprint) { + event.fingerprint = event.fingerprint.concat(this._fingerprint); + } - stack.pop(); - } else { - formData.append(parentKey, convertValue(data)); + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; } } +} - build(obj); +/** + * Returns the global event processors. + */ +function getGlobalEventProcessors() { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); +} - return formData; +/** + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add + */ +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); } -module.exports = toFormData; + +//# sourceMappingURL=scope.js.map /***/ }), -/* 1616 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1603 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "closeSession": () => (/* binding */ closeSession), +/* harmony export */ "makeSession": () => (/* binding */ makeSession), +/* harmony export */ "updateSession": () => (/* binding */ updateSession) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); -var utils = __webpack_require__(1604); -var settle = __webpack_require__(1617); -var cookies = __webpack_require__(1618); -var buildURL = __webpack_require__(1607); -var buildFullPath = __webpack_require__(1619); -var parseHeaders = __webpack_require__(1622); -var isURLSameOrigin = __webpack_require__(1623); -var transitionalDefaults = __webpack_require__(1614); -var AxiosError = __webpack_require__(1613); -var CanceledError = __webpack_require__(1624); -var parseProtocol = __webpack_require__(1625); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - var responseType = config.responseType; - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } +/** + * Creates a new `Session` object by setting certain default parameters. If optional @param context + * is passed, the passed properties are applied to the session object. + * + * @param context (optional) additional properties to be applied to the returned session object + * + * @returns a new `Session` object + */ +function makeSession(context) { + // Both timestamp and started are in seconds since the UNIX epoch. + const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } + const session = { + sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), + init: true, + timestamp: startingTime, + started: startingTime, + duration: 0, + status: 'ok', + errors: 0, + ignoreDuration: false, + toJSON: () => sessionToJSON(session), + }; - if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { - delete requestHeaders['Content-Type']; // Let the browser set it - } + if (context) { + updateSession(session, context); + } - var request = new XMLHttpRequest(); + return session; +} - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); +/** + * Updates a session object with the properties passed in the context. + * + * Note that this function mutates the passed object and returns void. + * (Had to do this instead of returning a new and updated session because closing and sending a session + * makes an update to the session after it was passed to the sending logic. + * @see BaseClient.captureSession ) + * + * @param session the `Session` to update + * @param context the `SessionContext` holding the properties that should be updated in @param session + */ +// eslint-disable-next-line complexity +function updateSession(session, context = {}) { + if (context.user) { + if (!session.ipAddress && context.user.ip_address) { + session.ipAddress = context.user.ip_address; } - var fullPath = buildFullPath(config.baseURL, config.url); - - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - - // Clean up request - request = null; + if (!session.did && !context.did) { + session.did = context.user.id || context.user.email || context.user.username; } + } - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } + session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } + if (context.ignoreDuration) { + session.ignoreDuration = context.ignoreDuration; + } + if (context.sid) { + // Good enough uuid validation. — Kamil + session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); + } + if (context.init !== undefined) { + session.init = context.init; + } + if (!session.did && context.did) { + session.did = `${context.did}`; + } + if (typeof context.started === 'number') { + session.started = context.started; + } + if (session.ignoreDuration) { + session.duration = undefined; + } else if (typeof context.duration === 'number') { + session.duration = context.duration; + } else { + const duration = session.timestamp - session.started; + session.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + session.release = context.release; + } + if (context.environment) { + session.environment = context.environment; + } + if (!session.ipAddress && context.ipAddress) { + session.ipAddress = context.ipAddress; + } + if (!session.userAgent && context.userAgent) { + session.userAgent = context.userAgent; + } + if (typeof context.errors === 'number') { + session.errors = context.errors; + } + if (context.status) { + session.status = context.status; + } +} - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); +/** + * Closes a session by setting its status and updating the session object with it. + * Internally calls `updateSession` to update the passed session object. + * + * Note that this function mutates the passed session (@see updateSession for explanation). + * + * @param session the `Session` object to be closed + * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, + * this function will keep the previously set status, unless it was `'ok'` in which case + * it is changed to `'exited'`. + */ +function closeSession(session, status) { + let context = {}; + if (status) { + context = { status }; + } else if (session.status === 'ok') { + context = { status: 'exited' }; + } - // Clean up request - request = null; - }; + updateSession(session, context); +} - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); +/** + * Serializes a passed session object to a JSON object with a slightly different structure. + * This is necessary because the Sentry backend requires a slightly different schema of a session + * than the one the JS SDKs use internally. + * + * @param session the session to be converted + * + * @returns a JSON object of the passed session + */ +function sessionToJSON(session) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ + sid: `${session.sid}`, + init: session.init, + // Make sure that sec is converted to ms for date constructor + started: new Date(session.started * 1000).toISOString(), + timestamp: new Date(session.timestamp * 1000).toISOString(), + status: session.status, + errors: session.errors, + did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, + duration: session.duration, + attrs: { + release: session.release, + environment: session.environment, + ip_address: session.ipAddress, + user_agent: session.userAgent, + }, + }); +} - // Clean up request - request = null; - }; - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - var transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request)); +//# sourceMappingURL=session.js.map - // Clean up request - request = null; - }; - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; +/***/ }), +/* 1604 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; - } - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), +/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), +/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), +/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), +/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), +/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) +/* harmony export */ }); +/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1606); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); +/* module decorator */ module = __webpack_require__.hmd(module); - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } - }); - } - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; - } - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; - } +// eslint-disable-next-line deprecation/deprecation +const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } +/** + * An object that can return the current timestamp in seconds since the UNIX epoch. + */ - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); - } +/** + * A TimestampSource implementation for environments that do not support the Performance Web API natively. + * + * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier + * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It + * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + */ +const dateTimestampSource = { + nowSeconds: () => Date.now() / 1000, +}; - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (!request) { - return; - } - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); - request.abort(); - request = null; - }; +/** + * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} + * for accessing a high-resolution monotonic clock. + */ - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } +/** + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. + * + * Wrapping the native API works around differences in behavior from different browsers. + */ +function getBrowserPerformance() { + const { performance } = WINDOW; + if (!performance || !performance.now) { + return undefined; + } - if (!requestData) { - requestData = null; - } + // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). + // + // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + + // performance.now() gives a date arbitrarily in the past. + // + // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is + // undefined. + // + // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to + // interact with data coming out of performance entries. + // + // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that + // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes + // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have + // observed skews that can be as long as days, weeks or months. + // + // See https://github.com/getsentry/sentry-javascript/issues/2590. + // + // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload + // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation + // transactions of long-lived web pages. + const timeOrigin = Date.now() - performance.now(); - var protocol = parseProtocol(fullPath); + return { + now: () => performance.now(), + timeOrigin, + }; +} - if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; - } +/** + * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't + * implement the API. + */ +function getNodePerformance() { + try { + const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; + return perfHooks.performance; + } catch (_) { + return undefined; + } +} +/** + * The Performance API implementation for the current platform, if available. + */ +const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); - // Send the request - request.send(requestData); - }); -}; +const timestampSource = + platformPerformance === undefined + ? dateTimestampSource + : { + nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, + }; +/** + * Returns a timestamp in seconds since the UNIX epoch using the Date API. + */ +const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/***/ }), -/* 1617 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the + * availability of the Performance API. + * + * See `usingPerformanceAPI` to test whether the Performance API is used. + * + * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is + * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The + * skew can grow to arbitrary amounts like days, weeks or months. + * See https://github.com/getsentry/sentry-javascript/issues/2590. + */ +const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -"use strict"; +// Re-exported with an old name for backwards-compatibility. +const timestampWithMs = timestampInSeconds; +/** + * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. + */ +const usingPerformanceAPI = platformPerformance !== undefined; -var AxiosError = __webpack_require__(1613); +/** + * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. + */ +let _browserPerformanceTimeOriginMode; /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. */ -module.exports = function settle(resolve, reject, response) { - var validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); +const browserPerformanceTimeOrigin = (() => { + // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or + // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin + // data as reliable if they are within a reasonable threshold of the current time. + + const { performance } = WINDOW; + if (!performance || !performance.now) { + _browserPerformanceTimeOriginMode = 'none'; + return undefined; } -}; + const threshold = 3600 * 1000; + const performanceNow = performance.now(); + const dateNow = Date.now(); + + // if timeOrigin isn't available set delta to threshold so it isn't used + const timeOriginDelta = performance.timeOrigin + ? Math.abs(performance.timeOrigin + performanceNow - dateNow) + : threshold; + const timeOriginIsReliable = timeOriginDelta < threshold; + + // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin + // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. + // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always + // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the + // Date API. + // eslint-disable-next-line deprecation/deprecation + const navigationStart = performance.timing && performance.timing.navigationStart; + const hasNavigationStart = typeof navigationStart === 'number'; + // if navigationStart isn't available set delta to threshold so it isn't used + const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + const navigationStartIsReliable = navigationStartDelta < threshold; -/***/ }), -/* 1618 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (timeOriginIsReliable || navigationStartIsReliable) { + // Use the more reliable time origin + if (timeOriginDelta <= navigationStartDelta) { + _browserPerformanceTimeOriginMode = 'timeOrigin'; + return performance.timeOrigin; + } else { + _browserPerformanceTimeOriginMode = 'navigationStart'; + return navigationStart; + } + } -"use strict"; + // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. + _browserPerformanceTimeOriginMode = 'dateNow'; + return dateNow; +})(); -var utils = __webpack_require__(1604); +//# sourceMappingURL=time.js.map -module.exports = ( - utils.isStandardBrowserEnv() ? - // Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - var cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); +/***/ }), +/* 1605 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), +/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), +/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) +/* harmony export */ }); +/** Internal global with common properties and Sentry extensions */ - if (utils.isString(path)) { - cookie.push('path=' + path); - } +// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification +// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js +// core-js has the following licence: +// +// Copyright (c) 2014-2022 Denis Pushkarev +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } +/** Returns 'obj' if it's the global object, otherwise returns undefined */ +function isGlobalObj(obj) { + return obj && obj.Math == Math ? obj : undefined; +} - if (secure === true) { - cookie.push('secure'); - } +/** Get's the global object for the current JavaScript runtime */ +const GLOBAL_OBJ = + (typeof globalThis == 'object' && isGlobalObj(globalThis)) || + // eslint-disable-next-line no-restricted-globals + (typeof window == 'object' && isGlobalObj(window)) || + (typeof self == 'object' && isGlobalObj(self)) || + (typeof global == 'object' && isGlobalObj(global)) || + (function () { + return this; + })() || + {}; - document.cookie = cookie.join('; '); - }, +/** + * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 + */ +function getGlobalObject() { + return GLOBAL_OBJ ; +} - read: function read(name) { - var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, +/** + * Returns a global singleton contained in the global `__SENTRY__` object. + * + * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory + * function and added to the `__SENTRY__` object. + * + * @param name name of the global singleton on __SENTRY__ + * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` + * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value + * @returns the singleton + */ +function getGlobalSingleton(name, creator, obj) { + const gbl = (obj || GLOBAL_OBJ) ; + const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); + const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); + return singleton; +} - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : - // Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })() -); +//# sourceMappingURL=worldwide.js.map /***/ }), -/* 1619 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1606 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), +/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), +/* harmony export */ "loadModule": () => (/* binding */ loadModule) +/* harmony export */ }); +/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1607); +/* module decorator */ module = __webpack_require__.hmd(module); -var isAbsoluteURL = __webpack_require__(1620); -var combineURLs = __webpack_require__(1621); +/** + * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, + * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. + */ /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. + * Checks whether we're in the Node.js or Browser environment * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * @returns {string} The combined full path + * @returns Answer to given question */ -module.exports = function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -}; - - -/***/ }), -/* 1620 */ -/***/ ((module) => { - -"use strict"; +function isNodeEnv() { + // explicitly check for browser bundles as those can be optimized statically + // by terser/rollup. + return ( + !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && + Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' + ); +} +/** + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} /** - * Determines whether the specified URL is absolute + * Helper for dynamically loading module that should work with linked dependencies. + * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` + * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during + * build time. `require.resolve` is also not available in any other way, so we cannot create, + * a fake helper like we do with `dynamicRequire`. * - * @param {string} url The URL to test - * @returns {boolean} True if the specified URL is absolute, otherwise false + * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. + * That is to mimic the behavior of `require.resolve` exactly. + * + * @param moduleName module name to require + * @returns possibly required module */ -module.exports = function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -}; +function loadModule(moduleName) { + let mod; + + try { + mod = dynamicRequire(module, moduleName); + } catch (e) { + // no-empty + } + + try { + const { cwd } = dynamicRequire(module, 'process'); + mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; + } catch (e) { + // no-empty + } + + return mod; +} + + +//# sourceMappingURL=node.js.map /***/ }), -/* 1621 */ -/***/ ((module) => { +/* 1607 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) +/* harmony export */ }); +/* + * This module exists for optimizations in the build process through rollup and terser. We define some global + * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these + * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will + * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to + * `logger` and preventing node-related code from appearing in browser bundles. + * + * Attention: + * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by + * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) + * having issues tree-shaking these constants across package boundaries. + * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want + * users to be able to shake away expressions that it guards. + */ /** - * Creates a new URL by combining the specified URLs + * Figures out if we're building a browser bundle. * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * @returns {string} The combined URL + * @returns true if this is a browser bundle build. */ -module.exports = function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -}; +function isBrowserBundle() { + return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; +} + + +//# sourceMappingURL=env.js.map /***/ }), -/* 1622 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1608 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), +/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), +/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), +/* harmony export */ "arrayify": () => (/* binding */ arrayify), +/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), +/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), +/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), +/* harmony export */ "uuid4": () => (/* binding */ uuid4) +/* harmony export */ }); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); +/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1609); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -var utils = __webpack_require__(1604); -// Headers whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -var ignoreDuplicateOf = [ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]; /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` + * UUID4 generator * - * @param {String} headers Headers needing to be parsed - * @returns {Object} Headers parsed into an object + * @returns string Generated UUID4. */ -module.exports = function parseHeaders(headers) { - var parsed = {}; - var key; - var val; - var i; - - if (!headers) { return parsed; } - - utils.forEach(headers.split('\n'), function parser(line) { - i = line.indexOf(':'); - key = utils.trim(line.substr(0, i)).toLowerCase(); - val = utils.trim(line.substr(i + 1)); - - if (key) { - if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { - return; - } - if (key === 'set-cookie') { - parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; - } - } - }); - - return parsed; -}; - - -/***/ }), -/* 1623 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function uuid4() { + const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; + const crypto = gbl.crypto || gbl.msCrypto; -"use strict"; + if (crypto && crypto.randomUUID) { + return crypto.randomUUID().replace(/-/g, ''); + } + const getRandomByte = + crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; -var utils = __webpack_require__(1604); + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 + // Concatenating the following numbers as strings results in '10000000100040008000100000000000' + return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => + // eslint-disable-next-line no-bitwise + ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), + ); +} -module.exports = ( - utils.isStandardBrowserEnv() ? +function getFirstException(event) { + return event.exception && event.exception.values ? event.exception.values[0] : undefined; +} - // Standard browser envs have full support of the APIs needed to test - // whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - var msie = /(msie|trident)/i.test(navigator.userAgent); - var urlParsingNode = document.createElement('a'); - var originURL; +/** + * Extracts either message or type+value from an event that can be used for user-facing logs + * @returns event's description + */ +function getEventDescription(event) { + const { message, event_id: eventId } = event; + if (message) { + return message; + } - /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - var href = url; + const firstException = getFirstException(event); + if (firstException) { + if (firstException.type && firstException.value) { + return `${firstException.type}: ${firstException.value}`; + } + return firstException.type || firstException.value || eventId || '<unknown>'; + } + return eventId || '<unknown>'; +} - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } +/** + * Adds exception values, type and value to an synthetic Exception. + * @param event The event to modify. + * @param value Value of the exception. + * @param type Type of the exception. + * @hidden + */ +function addExceptionTypeValue(event, value, type) { + const exception = (event.exception = event.exception || {}); + const values = (exception.values = exception.values || []); + const firstException = (values[0] = values[0] || {}); + if (!firstException.value) { + firstException.value = value || ''; + } + if (!firstException.type) { + firstException.type = type || 'Error'; + } +} - urlParsingNode.setAttribute('href', href); +/** + * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. + * + * @param event The event to modify. + * @param newMechanism Mechanism data to add to the event. + * @hidden + */ +function addExceptionMechanism(event, newMechanism) { + const firstException = getFirstException(event); + if (!firstException) { + return; + } - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; - } + const defaultMechanism = { type: 'generic', handled: true }; + const currentMechanism = firstException.mechanism; + firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; - originURL = resolveURL(window.location.href); + if (newMechanism && 'data' in newMechanism) { + const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; + firstException.mechanism.data = mergedData; + } +} - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : +// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +const SEMVER_REGEXP = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })() -); +/** + * Represents Semantic Versioning object + */ +/** + * Parses input into a SemVer interface + * @param input string representation of a semver version + */ +function parseSemver(input) { + const match = input.match(SEMVER_REGEXP) || []; + const major = parseInt(match[1], 10); + const minor = parseInt(match[2], 10); + const patch = parseInt(match[3], 10); + return { + buildmetadata: match[5], + major: isNaN(major) ? undefined : major, + minor: isNaN(minor) ? undefined : minor, + patch: isNaN(patch) ? undefined : patch, + prerelease: match[4], + }; +} -/***/ }), -/* 1624 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * This function adds context (pre/post/line) lines to the provided frame + * + * @param lines string[] containing all lines + * @param frame StackFrame that will be mutated + * @param linesOfContext number of context lines we want to add pre/post + */ +function addContextToFrame(lines, frame, linesOfContext = 5) { + const lineno = frame.lineno || 0; + const maxLines = lines.length; + const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); -"use strict"; + frame.pre_context = lines + .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) + .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); + frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); -var AxiosError = __webpack_require__(1613); -var utils = __webpack_require__(1604); + frame.post_context = lines + .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) + .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); +} /** - * A `CanceledError` is an object that is thrown when an operation is canceled. + * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object + * in question), and marks it captured if not. * - * @class - * @param {string=} message The message. + * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and + * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so + * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because + * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not + * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This + * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we + * see it. + * + * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on + * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent + * object wrapper forms so that this check will always work. However, because we need to flag the exact object which + * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification + * must be done before the exception captured. + * + * @param A thrown exception to check or flag as having been seen + * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) */ -function CanceledError(message) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); - this.name = 'CanceledError'; -} - -utils.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); - -module.exports = CanceledError; +function checkOrSetAlreadyCaught(exception) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (exception && (exception ).__sentry_captured__) { + return true; + } + try { + // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the + // `ExtraErrorData` integration + (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); + } catch (err) { + // `exception` is a primitive, so we can't mark it seen + } -/***/ }), -/* 1625 */ -/***/ ((module) => { + return false; +} -"use strict"; +/** + * Checks whether the given input is already an array, and if it isn't, wraps it in one. + * + * @param maybeArray Input to turn into an array, if necessary + * @returns The input, if already an array, or an array with the input as the only element, if not + */ +function arrayify(maybeArray) { + return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; +} -module.exports = function parseProtocol(url) { - var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; -}; +//# sourceMappingURL=misc.js.map /***/ }), -/* 1626 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1609 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), +/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), +/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), +/* harmony export */ "snipLine": () => (/* binding */ snipLine), +/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), +/* harmony export */ "truncate": () => (/* binding */ truncate) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); -var utils = __webpack_require__(1604); -var settle = __webpack_require__(1617); -var buildFullPath = __webpack_require__(1619); -var buildURL = __webpack_require__(1607); -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var httpFollow = (__webpack_require__(1627).http); -var httpsFollow = (__webpack_require__(1627).https); -var url = __webpack_require__(63); -var zlib = __webpack_require__(83); -var VERSION = (__webpack_require__(1629).version); -var transitionalDefaults = __webpack_require__(1614); -var AxiosError = __webpack_require__(1613); -var CanceledError = __webpack_require__(1624); - -var isHttps = /https:?/; - -var supportedProtocols = [ 'http:', 'https:', 'file:' ]; - /** + * Truncates given string to the maximum characters count * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} proxy - * @param {string} location + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string (0 = unlimited) + * @returns string Encoded */ -function setProxy(options, proxy, location) { - options.hostname = proxy.host; - options.host = proxy.host; - options.port = proxy.port; - options.path = location; - - // Basic proxy authorization - if (proxy.auth) { - var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; +function truncate(str, max = 0) { + if (typeof str !== 'string' || max === 0) { + return str; } - - // If a proxy is used, any redirects must also pass through the proxy - options.beforeRedirect = function beforeRedirect(redirection) { - redirection.headers.host = redirection.host; - setProxy(redirection, proxy, redirection.href); - }; + return str.length <= max ? str : `${str.substr(0, max)}...`; } -/*eslint consistent-return:0*/ -module.exports = function httpAdapter(config) { - return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { - var onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } - } - var resolve = function resolve(value) { - done(); - resolvePromise(value); - }; - var rejected = false; - var reject = function reject(value) { - done(); - rejected = true; - rejectPromise(value); - }; - var data = config.data; - var headers = config.headers; - var headerNames = {}; - - Object.keys(headers).forEach(function storeLowerName(name) { - headerNames[name.toLowerCase()] = name; - }); - - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - if ('user-agent' in headerNames) { - // User-Agent is specified; handle case where no UA header is desired - if (!headers[headerNames['user-agent']]) { - delete headers[headerNames['user-agent']]; - } - // Otherwise, use specified value - } else { - // Only set header if it hasn't been set in config - headers['User-Agent'] = 'axios/' + VERSION; - } - - // support for https://www.npmjs.com/package/form-data api - if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { - Object.assign(headers, data.getHeaders()); - } else if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new AxiosError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - AxiosError.ERR_BAD_REQUEST, - config - )); - } - - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new AxiosError( - 'Request body larger than maxBodyLength limit', - AxiosError.ERR_BAD_REQUEST, - config - )); - } - - // Add Content-Length header if data exists - if (!headerNames['content-length']) { - headers['Content-Length'] = data.length; - } - } - - // HTTP basic authentication - var auth = undefined; - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - auth = username + ':' + password; - } +/** + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 + * + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded + */ +function snipLine(line, colno) { + let newLine = line; + const lineLength = newLine.length; + if (lineLength <= 150) { + return newLine; + } + if (colno > lineLength) { + // eslint-disable-next-line no-param-reassign + colno = lineLength; + } - // Parse url - var fullPath = buildFullPath(config.baseURL, config.url); - var parsed = url.parse(fullPath); - var protocol = parsed.protocol || supportedProtocols[0]; + let start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError( - 'Unsupported protocol ' + protocol, - AxiosError.ERR_BAD_REQUEST, - config - )); - } + let end = Math.min(start + 140, lineLength); + if (end > lineLength - 5) { + end = lineLength; + } + if (end === lineLength) { + start = Math.max(end - 140, 0); + } - if (!auth && parsed.auth) { - var urlAuth = parsed.auth.split(':'); - var urlUsername = urlAuth[0] || ''; - var urlPassword = urlAuth[1] || ''; - auth = urlUsername + ':' + urlPassword; - } + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = `'{snip} ${newLine}`; + } + if (end < lineLength) { + newLine += ' {snip}'; + } - if (auth && headerNames.authorization) { - delete headers[headerNames.authorization]; - } + return newLine; +} - var isHttpsRequest = isHttps.test(protocol); - var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; +/** + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; + } + const output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < input.length; i++) { + const value = input[i]; try { - buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''); - } catch (err) { - var customErr = new Error(err.message); - customErr.config = config; - customErr.url = config.url; - customErr.exists = true; - reject(customErr); - } - - var options = { - path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), - method: config.method.toUpperCase(), - headers: headers, - agent: agent, - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth: auth - }; - - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; + output.push(String(value)); + } catch (e) { + output.push('[value cannot be serialized]'); } + } - var proxy = config.proxy; - if (!proxy && proxy !== false) { - var proxyEnv = protocol.slice(0, -1) + '_proxy'; - var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; - if (proxyUrl) { - var parsedProxyUrl = url.parse(proxyUrl); - var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; - var shouldProxy = true; - - if (noProxyEnv) { - var noProxy = noProxyEnv.split(',').map(function trim(s) { - return s.trim(); - }); - - shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { - if (!proxyElement) { - return false; - } - if (proxyElement === '*') { - return true; - } - if (proxyElement[0] === '.' && - parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { - return true; - } + return output.join(delimiter); +} - return parsed.hostname === proxyElement; - }); - } +/** + * Checks if the given value matches a regex or string + * + * @param value The string to test + * @param pattern Either a regex or a string against which `value` will be matched + * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match + * `pattern` if it contains `pattern`. Only applies to string-type patterns. + */ +function isMatchingPattern( + value, + pattern, + requireExactStringMatch = false, +) { + if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { + return false; + } - if (shouldProxy) { - proxy = { - host: parsedProxyUrl.hostname, - port: parsedProxyUrl.port, - protocol: parsedProxyUrl.protocol - }; + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { + return pattern.test(value); + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { + return requireExactStringMatch ? value === pattern : value.includes(pattern); + } - if (parsedProxyUrl.auth) { - var proxyUrlAuth = parsedProxyUrl.auth.split(':'); - proxy.auth = { - username: proxyUrlAuth[0], - password: proxyUrlAuth[1] - }; - } - } - } - } + return false; +} - if (proxy) { - options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); - setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } +/** + * Test the given string against an array of strings and regexes. By default, string matching is done on a + * substring-inclusion basis rather than a strict equality basis + * + * @param testString The string to test + * @param patterns The patterns against which to test the string + * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to + * count. If false, `testString` will match a string pattern if it contains that pattern. + * @returns + */ +function stringMatchesSomePattern( + testString, + patterns = [], + requireExactStringMatch = false, +) { + return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); +} - var transport; - var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsProxy ? https : http; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirect = config.beforeRedirect; - } - transport = isHttpsProxy ? httpsFollow : httpFollow; - } +/** + * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to + * `new RegExp()`. + * + * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime + * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node + * 12+). + * + * @param regexString The string to escape + * @returns An version of the string with all special regex characters escaped + */ +function escapeStringForRegex(regexString) { + // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems + // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. + return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +} - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; - } +//# sourceMappingURL=string.js.map - // Create the request - var req = transport.request(options, function handleResponse(res) { - if (req.aborted) return; - // uncompress the response body transparently if required - var stream = res; +/***/ }), +/* 1610 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // return the last request in case of redirects - var lastRequest = res.req || req; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), +/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), +/* harmony export */ "isElement": () => (/* binding */ isElement), +/* harmony export */ "isError": () => (/* binding */ isError), +/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), +/* harmony export */ "isEvent": () => (/* binding */ isEvent), +/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), +/* harmony export */ "isNaN": () => (/* binding */ isNaN), +/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), +/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), +/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), +/* harmony export */ "isString": () => (/* binding */ isString), +/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), +/* harmony export */ "isThenable": () => (/* binding */ isThenable) +/* harmony export */ }); +// eslint-disable-next-line @typescript-eslint/unbound-method +const objectToString = Object.prototype.toString; +/** + * Checks whether given value's type is one of a few Error or Error-like + * {@link isError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isError(wat) { + switch (objectToString.call(wat)) { + case '[object Error]': + case '[object Exception]': + case '[object DOMException]': + return true; + default: + return isInstanceOf(wat, Error); + } +} +/** + * Checks whether given value is an instance of the given built-in class. + * + * @param wat The value to be checked + * @param className + * @returns A boolean representing the result. + */ +function isBuiltin(wat, className) { + return objectToString.call(wat) === `[object ${className}]`; +} - // if no content, is HEAD request or decompress disabled we should not decompress - if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { - switch (res.headers['content-encoding']) { - /*eslint default-case:0*/ - case 'gzip': - case 'compress': - case 'deflate': - // add the unzipper to the body stream processing pipeline - stream = stream.pipe(zlib.createUnzip()); +/** + * Checks whether given value's type is ErrorEvent + * {@link isErrorEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isErrorEvent(wat) { + return isBuiltin(wat, 'ErrorEvent'); +} - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - } - } +/** + * Checks whether given value's type is DOMError + * {@link isDOMError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMError(wat) { + return isBuiltin(wat, 'DOMError'); +} - var response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: res.headers, - config: config, - request: lastRequest - }; +/** + * Checks whether given value's type is DOMException + * {@link isDOMException}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isDOMException(wat) { + return isBuiltin(wat, 'DOMException'); +} - if (config.responseType === 'stream') { - response.data = stream; - settle(resolve, reject, response); - } else { - var responseBuffer = []; - var totalResponseBytes = 0; - stream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; +/** + * Checks whether given value's type is a string + * {@link isString}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isString(wat) { + return isBuiltin(wat, 'String'); +} - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - // stream.destoy() emit aborted event before calling reject() on Node.js v16 - rejected = true; - stream.destroy(); - reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); - } - }); +/** + * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) + * {@link isPrimitive}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isPrimitive(wat) { + return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +} - stream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } - stream.destroy(); - reject(new AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, - config, - lastRequest - )); - }); +/** + * Checks whether given value's type is an object literal + * {@link isPlainObject}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isPlainObject(wat) { + return isBuiltin(wat, 'Object'); +} - stream.on('error', function handleStreamError(err) { - if (req.aborted) return; - reject(AxiosError.from(err, null, config, lastRequest)); - }); +/** + * Checks whether given value's type is an Event instance + * {@link isEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isEvent(wat) { + return typeof Event !== 'undefined' && isInstanceOf(wat, Event); +} - stream.on('end', function handleStreamEnd() { - try { - var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (config.responseType !== 'arraybuffer') { - responseData = responseData.toString(config.responseEncoding); - if (!config.responseEncoding || config.responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - reject(AxiosError.from(err, null, config, response.request, response)); - } - settle(resolve, reject, response); - }); - } - }); +/** + * Checks whether given value's type is an Element instance + * {@link isElement}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isElement(wat) { + return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +} - // Handle errors - req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(AxiosError.from(err, null, config, req)); - }); +/** + * Checks whether given value's type is an regexp + * {@link isRegExp}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isRegExp(wat) { + return isBuiltin(wat, 'RegExp'); +} - // set tcp keep alive to prevent drop connection by peer - req.on('socket', function handleRequestSocket(socket) { - // default interval of sending ack packet is 1 minute - socket.setKeepAlive(true, 1000 * 60); - }); +/** + * Checks whether given value has a then function. + * @param wat A value to be checked. + */ +function isThenable(wat) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return Boolean(wat && wat.then && typeof wat.then === 'function'); +} - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - var timeout = parseInt(config.timeout, 10); +/** + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +} - if (isNaN(timeout)) { - reject(new AxiosError( - 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); +/** + * Checks whether given value is NaN + * {@link isNaN}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isNaN(wat) { + return typeof wat === 'number' && wat !== wat; +} - return; - } +/** + * Checks whether given value's type is an instance of provided constructor. + * {@link isInstanceOf}. + * + * @param wat A value to be checked. + * @param base A constructor to be used in a check. + * @returns A boolean representing the result. + */ +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } catch (_e) { + return false; + } +} - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devoring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - req.abort(); - var transitional = config.transitional || transitionalDefaults; - reject(new AxiosError( - 'timeout of ' + timeout + 'ms exceeded', - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - req - )); - }); - } - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = function(cancel) { - if (req.aborted) return; +//# sourceMappingURL=is.js.map - req.abort(); - reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); - }; - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } - } +/***/ }), +/* 1611 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), +/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), +/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), +/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), +/* harmony export */ "fill": () => (/* binding */ fill), +/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), +/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), +/* harmony export */ "objectify": () => (/* binding */ objectify), +/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) +/* harmony export */ }); +/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1612); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1609); - // Send the request - if (utils.isStream(data)) { - data.on('error', function handleStreamError(err) { - reject(AxiosError.from(err, config, null, req)); - }).pipe(req); - } else { - req.end(data); - } - }); -}; -/***/ }), -/* 1627 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Replace a method in an object with a wrapped version of itself. + * + * @param source An object that contains a method to be wrapped. + * @param name The name of the method to be wrapped. + * @param replacementFactory A higher-order function that takes the original version of the given method and returns a + * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to + * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other + * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. + * @returns void + */ +function fill(source, name, replacementFactory) { + if (!(name in source)) { + return; + } -var url = __webpack_require__(63); -var URL = url.URL; -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var Writable = (__webpack_require__(82).Writable); -var assert = __webpack_require__(91); -var debug = __webpack_require__(1628); + const original = source[name] ; + const wrapped = replacementFactory(original) ; -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + try { + markFunctionWrapped(wrapped, original); + } catch (_Oo) { + // This can throw if multiple fill happens on a global object like XMLHttpRequest + // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 + } + } -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); + source[name] = wrapped; +} -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; +/** + * Defines a non-enumerable property on the given object. + * + * @param obj The object on which to set the property + * @param name The name of the property to be set + * @param value The value to which to set the property + */ +function addNonEnumerableProperty(obj, name, value) { + Object.defineProperty(obj, name, { + // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it + value: value, + writable: true, + configurable: true, + }); +} - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } +/** + * Remembers the original function on the wrapped function and + * patches up the prototype. + * + * @param wrapped the wrapper function + * @param original the original function that gets wrapped + */ +function markFunctionWrapped(wrapped, original) { + const proto = original.prototype || {}; + wrapped.prototype = original.prototype = proto; + addNonEnumerableProperty(wrapped, '__sentry_original__', original); +} - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; +/** + * This extracts the original function if available. See + * `markFunctionWrapped` for more information. + * + * @param func the function to unwrap + * @returns the unwrapped version of the function if available. + */ +function getOriginalFunction(func) { + return func.__sentry_original__; +} - // Perform the first request - this._performRequest(); +/** + * Encodes given object into url-friendly format + * + * @param object An object that contains serializable values + * @returns string Encoded + */ +function urlEncode(object) { + return Object.keys(object) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) + .join('&'); } -RedirectableRequest.prototype = Object.create(Writable.prototype); -RedirectableRequest.prototype.abort = function () { - abortRequest(this._currentRequest); - this.emit("abort"); -}; +/** + * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their + * non-enumerable properties attached. + * + * @param value Initial source that we have to transform in order for it to be usable by the serializer + * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor + * an Error. + */ +function convertToPlainObject( + value, +) -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } + { + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { + return { + message: value.message, + name: value.name, + stack: value.stack, + ...getOwnProperties(value), + }; + } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { + const newObj - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } + = { + type: value.type, + target: serializeEventTarget(value.target), + currentTarget: serializeEventTarget(value.currentTarget), + ...getOwnProperties(value), + }; - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); + if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { + newObj.detail = value.detail; } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; + return newObj; + } else { + return value; } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; +} - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); +/** Creates a string representation of the target of an `Event` object */ +function serializeEventTarget(target) { + try { + return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); + } catch (_oO) { + return '<unknown>'; } +} - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); +/** Filters out all but an object's own properties */ +function getOwnProperties(obj) { + if (typeof obj === 'object' && obj !== null) { + const extractedProps = {}; + for (const property in obj) { + if (Object.prototype.hasOwnProperty.call(obj, property)) { + extractedProps[property] = (obj )[property]; + } } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); + return extractedProps; + } else { + return {}; } +} - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } +/** + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` + */ +function extractExceptionKeysForMessage(exception, maxLength = 40) { + const keys = Object.keys(convertToPlainObject(exception)); + keys.sort(); - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } + if (!keys.length) { + return '[object has no keys]'; } - // Attach callback if passed - if (callback) { - this.on("timeout", callback); + if (keys[0].length >= maxLength) { + return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); } - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); + for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { + const serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; + } + if (includedKeys === keys.length) { + return serialized; + } + return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); } - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); + return ''; +} - return this; -}; +/** + * Given any object, return a new object having removed all fields whose value was `undefined`. + * Works recursively on objects and arrays. + * + * Attention: This function keeps circular references in the returned object. + */ +function dropUndefinedKeys(inputValue) { + // This map keeps track of what already visited nodes map to. + // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular + // references as the input object. + const memoizationMap = new Map(); -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); + // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API + return _dropUndefinedKeys(inputValue, memoizationMap); +} -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); +function _dropUndefinedKeys(inputValue, memoizationMap) { + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { + // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; + } -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } + const returnValue = {}; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; + for (const key of Object.keys(inputValue)) { + if (typeof inputValue[key] !== 'undefined') { + returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); + } } - delete options.host; + + return returnValue ; } - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); + if (Array.isArray(inputValue)) { + // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal ; } - } -}; + const returnValue = []; + // Store the mapping of this value in case we visit it again, in case of circular data + memoizationMap.set(inputValue, returnValue); -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } + inputValue.forEach((item) => { + returnValue.push(_dropUndefinedKeys(item, memoizationMap)); + }); - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; + return returnValue ; } - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } + return inputValue; +} - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._currentUrl = this._options.path; +/** + * Ensure that something is an object. + * + * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper + * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. + * + * @param wat The subject of the objectification + * @returns A version of `wat` which can safely be used with `Object` class methods + */ +function objectify(wat) { + let objectified; + switch (true) { + case wat === undefined || wat === null: + objectified = new String(wat); + break; - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; + // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason + // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as + // an object in order to wrap it. + case typeof wat === 'symbol' || typeof wat === 'bigint': + objectified = Object(wat); + break; + + // this will catch the remaining primitives: `String`, `Number`, and `Boolean` + case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + objectified = new (wat ).constructor(wat); + break; -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); + // by process of elimination, at this point we know that `wat` must already be an object + default: + objectified = wat; + break; } + return objectified; +} - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); +//# sourceMappingURL=object.js.map - // Clean up - this._requestBodyBuffers = []; - return; - } - // The response is a redirect, so abort the current request - abortRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); +/***/ }), +/* 1612 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), +/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), +/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); +// eslint-disable-next-line deprecation/deprecation +const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = url.parse(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); +/** + * Given a child DOM element, returns a query-selector statement describing that + * and its ancestors + * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] + * @returns generated DOM path + */ +function htmlTreeAsString(elem, keyAttrs) { - // Determine the URL of the redirection - var redirectUrl; + // try/catch both: + // - accessing event.target (see getsentry/raven-js#838, #768) + // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly + // - can throw an exception in some circumstances. try { - redirectUrl = url.resolve(currentUrl, location); - } - catch (cause) { - this.emit("error", new RedirectionError(cause)); - return; + let currentElem = elem ; + const MAX_TRAVERSE_HEIGHT = 5; + const MAX_OUTPUT_LEN = 80; + const out = []; + let height = 0; + let len = 0; + const separator = ' > '; + const sepLength = separator.length; + let nextStr; + + while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem, keyAttrs); + // bail out if + // - nextStr is the 'html' element + // - the length of the string that would be created exceeds MAX_OUTPUT_LEN + // (ignore this limit if we are on the first iteration) + if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { + break; + } + + out.push(nextStr); + + len += nextStr.length; + currentElem = currentElem.parentNode; + } + + return out.reverse().join(separator); + } catch (_oO) { + return '<unknown>'; } +} - // Create the redirected request - debug("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); +/** + * Returns a simple, query-selector representation of a DOM element + * e.g. [HTMLElement] => input#foo.btn[name=baz] + * @returns generated DOM path + */ +function _htmlElementAsString(el, keyAttrs) { + const elem = el - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrlParts.protocol !== currentUrlParts.protocol && - redirectUrlParts.protocol !== "https:" || - redirectUrlParts.host !== currentHost && - !isSubdomain(redirectUrlParts.host, currentHost)) { - removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); +; + + const out = []; + let className; + let classes; + let key; + let attr; + let i; + + if (!elem || !elem.tagName) { + return ''; } - // Evaluate the beforeRedirect callback - if (typeof beforeRedirect === "function") { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - try { - beforeRedirect(this._options, responseDetails, requestDetails); + out.push(elem.tagName.toLowerCase()); + + // Pairs of attribute keys defined in `serializeAttribute` and their values on element. + const keyAttrPairs = + keyAttrs && keyAttrs.length + ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) + : null; + + if (keyAttrPairs && keyAttrPairs.length) { + keyAttrPairs.forEach(keyAttrPair => { + out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); + }); + } else { + if (elem.id) { + out.push(`#${elem.id}`); } - catch (err) { - this.emit("error", err); - return; + + // eslint-disable-next-line prefer-const + className = elem.className; + if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { + classes = className.split(/\s+/); + for (i = 0; i < classes.length; i++) { + out.push(`.${classes[i]}`); + } + } + } + const allowedAttrs = ['type', 'name', 'title', 'alt']; + for (i = 0; i < allowedAttrs.length; i++) { + key = allowedAttrs[i]; + attr = elem.getAttribute(key); + if (attr) { + out.push(`[${key}="${attr}"]`); } - this._sanitizeOptions(this._options); } + return out.join(''); +} - // Perform the redirected request +/** + * A safe form of location.href + */ +function getLocationHref() { try { - this._performRequest(); + return WINDOW.document.location.href; + } catch (oO) { + return ''; } - catch (cause) { - this.emit("error", new RedirectionError(cause)); +} + +/** + * Gets a DOM element by using document.querySelector. + * + * This wrapper will first check for the existance of the function before + * actually calling it so that we don't have to take care of this check, + * every time we want to access the DOM. + * + * Reason: DOM/querySelector is not available in all environments. + * + * We have to cast to any because utils can be consumed by a variety of environments, + * and we don't want to break TS users. If you know what element will be selected by + * `document.querySelector`, specify it as part of the generic call. For example, + * `const element = getDomElement<Element>('selector');` + * + * @param selector the selector string passed on to document.querySelector + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getDomElement(selector) { + if (WINDOW.document && WINDOW.document.querySelector) { + return WINDOW.document.querySelector(selector) ; } -}; + return null; +} -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); +//# sourceMappingURL=browser.js.map - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url.parse(urlStr); - } - } - else if (URL && (input instanceof URL)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; +/***/ }), +/* 1613 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), +/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), +/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); +/* eslint-disable @typescript-eslint/explicit-function-return-type */ + +/** SyncPromise internal states */ +var States; (function (States) { + /** Pending */ + const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; + /** Resolved / OK */ + const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; + /** Rejected / Error */ + const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; +})(States || (States = {})); + +// Overloads so we can call resolvedSyncPromise without arguments and generic argument + +/** + * Creates a resolved sync promise. + * + * @param value the value to resolve the promise with + * @returns the resolved sync promise + */ +function resolvedSyncPromise(value) { + return new SyncPromise(resolve => { + resolve(value); }); - return exports; } -/* istanbul ignore next */ -function noop() { /* empty */ } - -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; +/** + * Creates a rejected sync promise. + * + * @param value the value to reject the promise with + * @returns the rejected sync promise + */ +function rejectedSyncPromise(reason) { + return new SyncPromise((_, reject) => { + reject(reason); + }); } -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; +/** + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally + */ +class SyncPromise { + __init() {this._state = States.PENDING;} + __init2() {this._handlers = [];} + + constructor( + executor, + ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); + try { + executor(this._resolve, this._reject); + } catch (e) { + this._reject(e); } } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} -function createErrorType(code, defaultMessage) { - function CustomError(cause) { - Error.captureStackTrace(this, this.constructor); - if (!cause) { - this.message = defaultMessage; - } - else { - this.message = defaultMessage + ": " + cause.message; - this.cause = cause; - } + /** JSDoc */ + then( + onfulfilled, + onrejected, + ) { + return new SyncPromise((resolve, reject) => { + this._handlers.push([ + false, + result => { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result ); + } else { + try { + resolve(onfulfilled(result)); + } catch (e) { + reject(e); + } + } + }, + reason => { + if (!onrejected) { + reject(reason); + } else { + try { + resolve(onrejected(reason)); + } catch (e) { + reject(e); + } + } + }, + ]); + this._executeHandlers(); + }); } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} -function abortRequest(request) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); + /** JSDoc */ + catch( + onrejected, + ) { + return this.then(val => val, onrejected); } - request.on("error", noop); - request.abort(); -} -function isSubdomain(subdomain, domain) { - const dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} + /** JSDoc */ + finally(onfinally) { + return new SyncPromise((resolve, reject) => { + let val; + let isRejected; + + return this.then( + value => { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, + reason => { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }, + ).then(() => { + if (isRejected) { + reject(val); + return; + } + + resolve(val ); + }); + }); + } + + /** JSDoc */ + __init3() {this._resolve = (value) => { + this._setResult(States.RESOLVED, value); + };} + + /** JSDoc */ + __init4() {this._reject = (reason) => { + this._setResult(States.REJECTED, reason); + };} -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; + /** JSDoc */ + __init5() {this._setResult = (state, value) => { + if (this._state !== States.PENDING) { + return; + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { + void (value ).then(this._resolve, this._reject); + return; + } -/***/ }), -/* 1628 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this._state = state; + this._value = value; -var debug; + this._executeHandlers(); + };} -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __webpack_require__(1402)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; + /** JSDoc */ + __init6() {this._executeHandlers = () => { + if (this._state === States.PENDING) { + return; } - } - debug.apply(null, arguments); -}; + const cachedHandlers = this._handlers.slice(); + this._handlers = []; -/***/ }), -/* 1629 */ -/***/ ((module) => { + cachedHandlers.forEach(handler => { + if (handler[0]) { + return; + } -module.exports = { - "version": "0.27.2" -}; + if (this._state === States.RESOLVED) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler[1](this._value ); + } -/***/ }), -/* 1630 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (this._state === States.REJECTED) { + handler[2](this._value); + } + + handler[0] = true; + }); + };} +} -// eslint-disable-next-line strict -module.exports = __webpack_require__(1631); + +//# sourceMappingURL=syncpromise.js.map /***/ }), -/* 1631 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1614 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -var CombinedStream = __webpack_require__(147); -var util = __webpack_require__(64); -var path = __webpack_require__(142); -var http = __webpack_require__(80); -var https = __webpack_require__(81); -var parseUrl = (__webpack_require__(63).parse); -var fs = __webpack_require__(149); -var Stream = (__webpack_require__(82).Stream); -var mime = __webpack_require__(139); -var asynckit = __webpack_require__(150); -var populate = __webpack_require__(1632); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), +/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), +/* harmony export */ "logger": () => (/* binding */ logger) +/* harmony export */ }); +/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1605); -// Public API -module.exports = FormData; -// make it a Stream -util.inherits(FormData, CombinedStream); +/** Prefix for logging strings */ +const PREFIX = 'Sentry Logger '; + +const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. + * Temporarily disable sentry console instrumentations. * - * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * @param callback The function to run against the original `console` messages + * @returns The results of the callback */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); +function consoleSandbox(callback) { + if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { + return callback(); } - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; + const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; + const wrappedLevels = {}; - CombinedStream.call(this); + // Restore all wrapped console methods + CONSOLE_LEVELS.forEach(level => { + // TODO(v7): Remove this check as it's only needed for Node 6 + const originalWrappedFunc = + originalConsole[level] && (originalConsole[level] ).__sentry_original__; + if (level in originalConsole && originalWrappedFunc) { + wrappedLevels[level] = originalConsole[level] ; + originalConsole[level] = originalWrappedFunc ; + } + }); - options = options || {}; - for (var option in options) { - this[option] = options[option]; + try { + return callback(); + } finally { + // Revert restoration to wrapped state + Object.keys(wrappedLevels).forEach(level => { + originalConsole[level] = wrappedLevels[level ]; + }); } } -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; +function makeLogger() { + let enabled = false; + const logger = { + enable: () => { + enabled = true; + }, + disable: () => { + enabled = false; + }, + }; -FormData.prototype.append = function(field, value, options) { + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + CONSOLE_LEVELS.forEach(name => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + logger[name] = (...args) => { + if (enabled) { + consoleSandbox(() => { + _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); + }); + } + }; + }); + } else { + CONSOLE_LEVELS.forEach(name => { + logger[name] = () => undefined; + }); + } - options = options || {}; + return logger ; +} - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } +// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used +let logger; +if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); +} else { + logger = makeLogger(); +} - var append = CombinedStream.prototype.append.bind(this); - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } +//# sourceMappingURL=logger.js.map - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); +/***/ }), +/* 1615 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - append(header); - append(value); - append(footer); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) +/* harmony export */ }); +const SDK_VERSION = '7.23.0'; - // pass along options.knownLength - this._trackLength(header, value, options); -}; -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; +//# sourceMappingURL=version.js.map - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - this._valueLength += valueLength; +/***/ }), +/* 1616 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), +/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), +/* harmony export */ "captureException": () => (/* binding */ captureException), +/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), +/* harmony export */ "configureScope": () => (/* binding */ configureScope), +/* harmony export */ "setContext": () => (/* binding */ setContext), +/* harmony export */ "setExtra": () => (/* binding */ setExtra), +/* harmony export */ "setExtras": () => (/* binding */ setExtras), +/* harmony export */ "setTag": () => (/* binding */ setTag), +/* harmony export */ "setTags": () => (/* binding */ setTags), +/* harmony export */ "setUser": () => (/* binding */ setUser), +/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), +/* harmony export */ "withScope": () => (/* binding */ withScope) +/* harmony export */ }); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; +// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, +// where HUB_FUNCTION is some method on the Hub class. +// +// This is done to make sure the top level SDK methods stay in sync with the hub methods. +// Although every method here has an explicit return type, some of them (that map to void returns) do not +// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. + +/** + * Captures an exception event and sends it to Sentry. + * + * @param exception An exception-like object. + * @param captureContext Additional scope data to apply to exception event. + * @returns The generated eventId. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types +function captureException(exception, captureContext) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); +} -FormData.prototype._lengthRetriever = function(value, callback) { +/** + * Captures a message event and sends it to Sentry. + * + * @param message The message to send to Sentry. + * @param Severity Define the level of the message. + * @returns The generated eventId. + */ +function captureMessage( + message, + // eslint-disable-next-line deprecation/deprecation + captureContext, +) { + // This is necessary to provide explicit scopes upgrade, without changing the original + // arity of the `captureMessage(message, level)` method. + const level = typeof captureContext === 'string' ? captureContext : undefined; + const context = typeof captureContext !== 'string' ? { captureContext } : undefined; + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); +} - if (value.hasOwnProperty('fd')) { +/** + * Captures a manually created event and sends it to Sentry. + * + * @param event The event to send to Sentry. + * @returns The generated eventId. + */ +function captureEvent(event, hint) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); +} - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { +/** + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. + */ +function configureScope(callback) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); +} - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); +/** + * Records a new breadcrumb which will be attached to future events. + * + * Breadcrumbs will be added to subsequent events to provide more context on + * user's actions prior to an error or crash. + * + * @param breadcrumb The breadcrumb to record. + */ +function addBreadcrumb(breadcrumb) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); +} - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +/** + * Sets context data with the given name. + * @param name of the context + * @param context Any kind of data. This data will be normalized. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContext(name, context) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); +} - var fileSize; +/** + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. + */ +function setExtras(extras) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); +} - if (err) { - callback(err); - return; - } +/** + * Set key:value that will be sent as extra data with the event. + * @param key String of extra + * @param extra Any kind of data. This data will be normalized. + */ +function setExtra(key, extra) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); +} - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } +/** + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. + */ +function setTags(tags) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); +} - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); +/** + * Set key:value that will be sent as tags data with the event. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key String key of tag + * @param value Value of tag + */ +function setTag(key, value) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); +} - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); +/** + * Updates user context information for future events. + * + * @param user User context object to be set in the current context. Pass `null` to unset the user. + */ +function setUser(user) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); +} - // something else - } else { - callback('Unknown stream'); - } -}; +/** + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. + * + * This is essentially a convenience function for: + * + * pushScope(); + * callback(); + * popScope(); + * + * @param callback that will be enclosed into push/popScope. + */ +function withScope(callback) { + (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); +} -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } +/** + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call + * `startTransaction` directly on the hub. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started + */ +function startTransaction( + context, + customSamplingContext, +) { + return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); +} - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +//# sourceMappingURL=exports.js.map - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; +/***/ }), +/* 1617 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // skip nullish headers. - if (header == null) { - continue; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), +/* harmony export */ "createTransport": () => (/* binding */ createTransport) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1618); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1625); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1619); - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } +const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; +/** + * Creates an instance of a Sentry `Transport` + * + * @param options + * @param makeRequest + */ +function createTransport( + options, + makeRequest, + buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), +) { + let rateLimits = {}; -FormData.prototype._getContentDisposition = function(value, options) { + const flush = (timeout) => buffer.drain(timeout); - var filename - , contentDisposition - ; + function send(envelope) { + const filteredEnvelopeItems = []; - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } + // Drop rate limited items from envelope + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { + const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); + } else { + filteredEnvelopeItems.push(item); + } + }); - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } + // Skip sending if envelope is empty after filtering out rate limited events + if (filteredEnvelopeItems.length === 0) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); + } - return contentDisposition; -}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); -FormData.prototype._getContentType = function(value, options) { + // Creates client report for each item in an envelope + const recordEnvelopeLoss = (reason) => { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); + }); + }; - // use custom content-type above all - var contentType = options.contentType; + const requestTask = () => + makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( + response => { + // We don't want to throw on NOK responses, but we want to at least log them + if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); + } - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } + rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); + }, + error => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); + recordEnvelopeLoss('network_error'); + }, + ); - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); + return buffer.add(requestTask).then( + result => result, + error => { + if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); + recordEnvelopeLoss('queue_overflow'); + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); + } else { + throw error; + } + }, + ); } - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } + return { + send, + flush, + }; +} - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); +function getEventForEnvelopeItem(item, type) { + if (type !== 'event' && type !== 'transaction') { + return undefined; } - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } + return Array.isArray(item) ? (item )[1] : undefined; +} - return contentType; -}; -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; +//# sourceMappingURL=base.js.map - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } - next(footer); - }.bind(this); -}; +/***/ }), +/* 1618 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) +/* harmony export */ }); +/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1619); +/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1613); -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - return formHeaders; -}; +/** + * Creates an new PromiseBuffer object with the specified limit + * @param limit max number of promises that can be stored in the buffer + */ +function makePromiseBuffer(limit) { + const buffer = []; -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; + function isReady() { + return limit === undefined || buffer.length < limit; + } -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + /** + * Remove a promise from the queue. + * + * @param task Can be any PromiseLike<T> + * @returns Removed promise. + */ + function remove(task) { + return buffer.splice(buffer.indexOf(task), 1)[0]; } - return this._boundary; -}; + /** + * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. + * + * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: + * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor + * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By + * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer + * limit check. + * @returns The original promise. + */ + function add(taskProducer) { + if (!isReady()) { + return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); + } -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); + // start the task and add its promise to the queue + const task = taskProducer(); + if (buffer.indexOf(task) === -1) { + buffer.push(task); + } + void task + .then(() => remove(task)) + // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` + // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't + // have promises, so TS has to polyfill when down-compiling.) + .then(null, () => + remove(task).then(null, () => { + // We have to add another catch here because `remove()` starts a new promise chain. + }), + ); + return task; + } - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { + /** + * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or + * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to + * `true`. + * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and + * `false` otherwise + */ + function drain(timeout) { + return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { + let counter = buffer.length; - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + if (!counter) { + return resolve(true); } - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); - } - } + // wait for `timeout` ms and then resolve to `false` (if not cancelled first) + const capturedSetTimeout = setTimeout(() => { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); + + // if all promises resolve in time, cancel the timer and resolve to `true` + buffer.forEach(item => { + void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { + if (!--counter) { + clearTimeout(capturedSetTimeout); + resolve(true); + } + }, reject); + }); + }); } - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; + return { + $: buffer, + add, + drain, + }; +} + + +//# sourceMappingURL=promisebuffer.js.map -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } - this._boundary = boundary; -}; +/***/ }), +/* 1619 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "SentryError": () => (/* binding */ SentryError) +/* harmony export */ }); +/** An error emitted by Sentry SDKs and related utilities. */ +class SentryError extends Error { + /** Display name of this error instance. */ - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } + constructor( message, logLevel = 'warn') { + super(message);this.message = message;; - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); + this.name = new.target.prototype.constructor.name; + // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line + // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes + // instances of `SentryError` fail `obj instanceof SentryError` checks. + Object.setPrototypeOf(this, new.target.prototype); + this.logLevel = logLevel; } +} - return knownLength; -}; -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; +//# sourceMappingURL=error.js.map - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - return hasKnownLength; -}; +/***/ }), +/* 1620 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), +/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), +/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), +/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), +/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), +/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) +/* harmony export */ }); +/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1621); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; - } +/** + * Creates an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. + */ +function createEnvelope(headers, items = []) { + return [headers, items] ; +} - values.forEach(function(length) { - knownLength += length; - }); +/** + * Add an item to an envelope. + * Make sure to always explicitly provide the generic to this function + * so that the envelope types resolve correctly. + */ +function addItemToEnvelope(envelope, newItem) { + const [headers, items] = envelope; + return [headers, [...items, newItem]] ; +} - cb(null, knownLength); +/** + * Convenience function to loop through the items and item types of an envelope. + * (This function was mostly created because working with envelope types is painful at the moment) + */ +function forEachEnvelopeItem( + envelope, + callback, +) { + const envelopeItems = envelope[1]; + envelopeItems.forEach((envelopeItem) => { + const envelopeItemType = envelopeItem[0].type; + callback(envelopeItem, envelopeItemType); }); -}; - -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; +} - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { +function encodeUTF8(input, textEncoder) { + const utf8 = textEncoder || new TextEncoder(); + return utf8.encode(input); +} - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); +/** + * Serializes an envelope. + */ +function serializeEnvelope(envelope, textEncoder) { + const [envHeaders, items] = envelope; - // use custom params - } else { + // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data + let parts = JSON.stringify(envHeaders); - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; + function append(next) { + if (typeof parts === 'string') { + parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; + } else { + parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); } } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } + for (const item of items) { + const [itemHeaders, payload] = item; - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } + append(`\n${JSON.stringify(itemHeaders)}\n`); - // add content length - if (length) { - request.setHeader('Content-Length', length); + if (typeof payload === 'string' || payload instanceof Uint8Array) { + append(payload); + } else { + let stringifiedPayload; + try { + stringifiedPayload = JSON.stringify(payload); + } catch (e) { + // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still + // fails, we try again after normalizing it again with infinite normalization depth. This of course has a + // performance impact but in this case a performance hit is better than throwing. + stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); + } + append(stringifiedPayload); } + } - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); + return typeof parts === 'string' ? parts : concatBuffers(parts); +} - return cb.call(this, error, responce); - }; +function concatBuffers(buffers) { + const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); - onResponse = callback.bind(this, null); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const buffer of buffers) { + merged.set(buffer, offset); + offset += buffer.length; + } - request.on('error', callback); - request.on('response', onResponse); - } - }.bind(this)); + return merged; +} - return request; -}; +/** + * Creates attachment envelope items + */ +function createAttachmentEnvelopeItem( + attachment, + textEncoder, +) { + const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; + return [ + (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ + type: 'attachment', + length: buffer.length, + filename: attachment.filename, + content_type: attachment.contentType, + attachment_type: attachment.attachmentType, + }), + buffer, + ]; +} -FormData.prototype.toString = function () { - return '[object FormData]'; +const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { + session: 'session', + sessions: 'session', + attachment: 'attachment', + transaction: 'transaction', + event: 'error', + client_report: 'internal', + user_report: 'default', }; +/** + * Maps the type of an envelope item to a data category. + */ +function envelopeItemTypeToDataCategory(type) { + return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; +} -/***/ }), -/* 1632 */ -/***/ ((module) => { - -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); - return dst; -}; +//# sourceMappingURL=envelope.js.map /***/ }), -/* 1633 */ -/***/ ((module) => { +/* 1621 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "normalize": () => (/* binding */ normalize), +/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), +/* harmony export */ "walk": () => (/* binding */ visit) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1622); +/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); +/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1623); -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; - - -/***/ }), -/* 1634 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -var utils = __webpack_require__(1604); /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. + * Recursively normalizes the given object. * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 + * - Creates a copy to prevent original input mutation + * - Skips non-enumerable properties + * - When stringifying, calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format + * - Translates known global objects/classes to a string representations + * - Takes care of `Error` object serialization + * - Optionally limits depth of final output + * - Optionally limits number of properties/elements included in any single object/array + * + * @param input The object to be normalized. + * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) + * @param maxProperties The max number of elements or properties to be included in any single array or + * object in the normallized output. + * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - function getMergedValue(target, source) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge(target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(config1[prop], config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function normalize(input, depth = +Infinity, maxProperties = +Infinity) { + try { + // since we're at the outermost level, we don't provide a key + return visit('', input, depth, maxProperties); + } catch (err) { + return { ERROR: `**non-serializable** (${err})` }; } +} - // eslint-disable-next-line consistent-return - function defaultToConfig2(prop) { - if (!utils.isUndefined(config2[prop])) { - return getMergedValue(undefined, config2[prop]); - } else if (!utils.isUndefined(config1[prop])) { - return getMergedValue(undefined, config1[prop]); - } - } +/** JSDoc */ +function normalizeToSize( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + object, + // Default Node.js REPL depth + depth = 3, + // 100kB, as 200kB is max payload size, so half sounds reasonable + maxSize = 100 * 1024, +) { + const normalized = normalize(object, depth); - // eslint-disable-next-line consistent-return - function mergeDirectKeys(prop) { - if (prop in config2) { - return getMergedValue(config1[prop], config2[prop]); - } else if (prop in config1) { - return getMergedValue(undefined, config1[prop]); - } + if (jsonSize(normalized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); } - var mergeMap = { - 'url': valueFromConfig2, - 'method': valueFromConfig2, - 'data': valueFromConfig2, - 'baseURL': defaultToConfig2, - 'transformRequest': defaultToConfig2, - 'transformResponse': defaultToConfig2, - 'paramsSerializer': defaultToConfig2, - 'timeout': defaultToConfig2, - 'timeoutMessage': defaultToConfig2, - 'withCredentials': defaultToConfig2, - 'adapter': defaultToConfig2, - 'responseType': defaultToConfig2, - 'xsrfCookieName': defaultToConfig2, - 'xsrfHeaderName': defaultToConfig2, - 'onUploadProgress': defaultToConfig2, - 'onDownloadProgress': defaultToConfig2, - 'decompress': defaultToConfig2, - 'maxContentLength': defaultToConfig2, - 'maxBodyLength': defaultToConfig2, - 'beforeRedirect': defaultToConfig2, - 'transport': defaultToConfig2, - 'httpAgent': defaultToConfig2, - 'httpsAgent': defaultToConfig2, - 'cancelToken': defaultToConfig2, - 'socketPath': defaultToConfig2, - 'responseEncoding': defaultToConfig2, - 'validateStatus': mergeDirectKeys - }; - - utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { - var merge = mergeMap[prop] || mergeDeepProperties; - var configValue = merge(prop); - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; -}; - - -/***/ }), -/* 1635 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return normalized ; +} -"use strict"; +/** + * Visits a node to perform normalization on it + * + * @param key The key corresponding to the given node + * @param value The node to be visited + * @param depth Optional number indicating the maximum recursion depth + * @param maxProperties Optional maximum number of properties/elements included in any single object/array + * @param memo Optional Memo class handling decycling + */ +function visit( + key, + value, + depth = +Infinity, + maxProperties = +Infinity, + memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), +) { + const [memoize, unmemoize] = memo; + // Get the simple cases out of the way first + if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { + return value ; + } -var VERSION = (__webpack_require__(1629).version); -var AxiosError = __webpack_require__(1613); + const stringified = stringifyValue(key, value); -var validators = {}; + // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. + // Everything else will have already been serialized, so if we don't see that pattern, we're done. + if (!stringified.startsWith('[object ')) { + return stringified; + } -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { - validators[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); + // From here on, we can assert that `value` is either an object or an array. -var deprecatedWarnings = {}; + // Do not normalize objects that we know have already been normalized. As a general rule, the + // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that + // have already been normalized. + if ((value )['__sentry_skip_normalization__']) { + return value ; + } -/** - * Transitional option validator - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * @returns {function} - */ -validators.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + // We're also done if we've reached the max depth + if (depth === 0) { + // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. + return stringified.replace('object ', ''); } - // eslint-disable-next-line func-names - return function(value, opt, opts) { - if (validator === false) { - throw new AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED - ); - } + // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. + if (memoize(value)) { + return '[Circular ~]'; + } - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); + // If the value has a `toJSON` method, we call it to extract more information + const valueWithToJSON = value ; + if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { + try { + const jsonValue = valueWithToJSON.toJSON(); + // We need to normalize the return value of `.toJSON()` in case it has circular references + return visit('', jsonValue, depth - 1, maxProperties, memo); + } catch (err) { + // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) } + } - return validator ? validator(value, opt, opts) : true; - }; -}; + // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse + // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each + // property/entry, and keep track of the number of items we add to it. + const normalized = (Array.isArray(value) ? [] : {}) ; + let numAdded = 0; -/** - * Assert object's properties type - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - */ + // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant + // properties are non-enumerable and otherwise would get missed. + const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); - } - var keys = Object.keys(options); - var i = keys.length; - while (i-- > 0) { - var opt = keys[i]; - var validator = schema[opt]; - if (validator) { - var value = options[opt]; - var result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); - } + for (const visitKey in visitable) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { continue; } - if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); - } - } -} - -module.exports = { - assertOptions: assertOptions, - validators: validators -}; + if (numAdded >= maxProperties) { + normalized[visitKey] = '[MaxProperties ~]'; + break; + } -/***/ }), -/* 1636 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // Recursively visit all the child nodes + const visitValue = visitable[visitKey]; + normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); -"use strict"; + numAdded++; + } + // Once we've visited all the branches, remove the parent from memo storage + unmemoize(value); -var CanceledError = __webpack_require__(1624); + // Return accumulated values + return normalized; +} /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. + * Stringify the given value. Handles various known special values and types. * - * @class - * @param {Function} executor The executor function. + * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn + * the number 1231 into "[Object Number]", nor on `null`, as it will throw. + * + * @param value The value to stringify + * @returns A stringified representation of the given value */ -function CancelToken(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } +function stringifyValue( + key, + // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for + // our internal use, it'll do + value, +) { + try { + if (key === 'domain' && value && typeof value === 'object' && (value )._events) { + return '[Domain]'; + } - var resolvePromise; + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); + // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first + // which won't throw if they are not present. - var token = this; + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; + } - // eslint-disable-next-line func-names - this.promise.then(function(cancel) { - if (!token._listeners) return; + // eslint-disable-next-line no-restricted-globals + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } - var i; - var l = token._listeners.length; + // eslint-disable-next-line no-restricted-globals + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } - for (i = 0; i < l; i++) { - token._listeners[i](cancel); + // React's SyntheticEvent thingy + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { + return '[SyntheticEvent]'; } - token._listeners = null; - }); - // eslint-disable-next-line func-names - this.promise.then = function(onfulfilled) { - var _resolve; - // eslint-disable-next-line func-names - var promise = new Promise(function(resolve) { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); + if (typeof value === 'number' && value !== value) { + return '[NaN]'; + } - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; + // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) + if (value === void 0) { + return '[undefined]'; + } - return promise; - }; + if (typeof value === 'function') { + return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; + } - executor(function cancel(message) { - if (token.reason) { - // Cancellation has already been requested - return; + if (typeof value === 'symbol') { + return `[${String(value)}]`; } - token.reason = new CanceledError(message); - resolvePromise(token.reason); - }); -} + // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion + if (typeof value === 'bigint') { + return `[BigInt: ${String(value)}]`; + } -/** - * Throws a `CanceledError` if cancellation has been requested. - */ -CancelToken.prototype.throwIfRequested = function throwIfRequested() { - if (this.reason) { - throw this.reason; + // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting + // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as + // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), + // we can make sure that only plain objects come out that way. + return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; + } catch (err) { + return `**non-serializable** (${err})`; } -}; +} -/** - * Subscribe to the cancel signal - */ +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} -CancelToken.prototype.subscribe = function subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } +/** Calculates bytes size of input object */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); +} - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } -}; + +//# sourceMappingURL=normalize.js.map + + +/***/ }), +/* 1622 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) +/* harmony export */ }); +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-explicit-any */ /** - * Unsubscribe from the cancel signal + * Helper to decycle json objects */ - -CancelToken.prototype.unsubscribe = function unsubscribe(listener) { - if (!this._listeners) { - return; +function memoBuilder() { + const hasWeakSet = typeof WeakSet === 'function'; + const inner = hasWeakSet ? new WeakSet() : []; + function memoize(obj) { + if (hasWeakSet) { + if (inner.has(obj)) { + return true; + } + inner.add(obj); + return false; + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < inner.length; i++) { + const value = inner[i]; + if (value === obj) { + return true; + } + } + inner.push(obj); + return false; } - var index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); + + function unmemoize(obj) { + if (hasWeakSet) { + inner.delete(obj); + } else { + for (let i = 0; i < inner.length; i++) { + if (inner[i] === obj) { + inner.splice(i, 1); + break; + } + } + } } -}; + return [memoize, unmemoize]; +} -/** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ -CancelToken.source = function source() { - var cancel; - var token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token: token, - cancel: cancel - }; -}; -module.exports = CancelToken; +//# sourceMappingURL=memo.js.map /***/ }), -/* 1637 */ -/***/ ((module) => { +/* 1623 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), +/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), +/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), +/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), +/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) +/* harmony export */ }); +/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1624); +const STACKTRACE_LIMIT = 50; + /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. + * Creates a stack parser with the supplied line parsers * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` + * StackFrames are returned in the correct order for Sentry Exception + * frames and with Sentry SDK internal frames removed from the top and bottom * - * @param {Function} callback - * @returns {Function} */ -module.exports = function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -}; +function createStackParser(...parsers) { + const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); + return (stack, skipFirst = 0) => { + const frames = []; -/***/ }), -/* 1638 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + for (const line of stack.split('\n').slice(skipFirst)) { + // https://github.com/getsentry/sentry-javascript/issues/5459 + // Remove webpack (error: *) wrappers + const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); -"use strict"; + for (const parser of sortedParsers) { + const frame = parser(cleanedLine); + if (frame) { + frames.push(frame); + break; + } + } + } -var utils = __webpack_require__(1604); + return stripSentryFramesAndReverse(frames); + }; +} /** - * Determines whether the payload is an error thrown by Axios + * Gets a stack parser implementation from Options.stackParser + * @see Options * - * @param {*} payload The value to test - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + * If options contains an array of line parsers, it is converted into a parser */ -module.exports = function isAxiosError(payload) { - return utils.isObject(payload) && (payload.isAxiosError === true); -}; +function stackParserFromStackParserOptions(stackParser) { + if (Array.isArray(stackParser)) { + return createStackParser(...stackParser); + } + return stackParser; +} +/** + * @hidden + */ +function stripSentryFramesAndReverse(stack) { + if (!stack.length) { + return []; + } -/***/ }), -/* 1639 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + let localStack = stack; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Hub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.Hub), -/* harmony export */ "SDK_VERSION": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_1__.SDK_VERSION), -/* harmony export */ "Scope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.Scope), -/* harmony export */ "addBreadcrumb": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.addBreadcrumb), -/* harmony export */ "addGlobalEventProcessor": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor), -/* harmony export */ "captureEvent": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureEvent), -/* harmony export */ "captureException": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureException), -/* harmony export */ "captureMessage": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.captureMessage), -/* harmony export */ "configureScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.configureScope), -/* harmony export */ "createTransport": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_4__.createTransport), -/* harmony export */ "getCurrentHub": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.getHubFromCarrier), -/* harmony export */ "makeMain": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_0__.makeMain), -/* harmony export */ "setContext": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setContext), -/* harmony export */ "setExtra": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtra), -/* harmony export */ "setExtras": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setExtras), -/* harmony export */ "setTag": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTag), -/* harmony export */ "setTags": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setTags), -/* harmony export */ "setUser": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.setUser), -/* harmony export */ "startTransaction": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.startTransaction), -/* harmony export */ "withScope": () => (/* reexport safe */ _sentry_core__WEBPACK_IMPORTED_MODULE_3__.withScope), -/* harmony export */ "NodeClient": () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_5__.NodeClient), -/* harmony export */ "close": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.close), -/* harmony export */ "defaultIntegrations": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.defaultStackParser), -/* harmony export */ "flush": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.flush), -/* harmony export */ "getSentryRelease": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.getSentryRelease), -/* harmony export */ "init": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.init), -/* harmony export */ "lastEventId": () => (/* reexport safe */ _sdk_js__WEBPACK_IMPORTED_MODULE_7__.lastEventId), -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.addRequestDataToEvent), -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.extractRequestData), -/* harmony export */ "deepReadDirSync": () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_9__.deepReadDirSync), -/* harmony export */ "Handlers": () => (/* reexport module object */ _handlers_js__WEBPACK_IMPORTED_MODULE_11__), -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _transports_http_js__WEBPACK_IMPORTED_MODULE_13__.makeNodeTransport), -/* harmony export */ "Integrations": () => (/* binding */ INTEGRATIONS) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1718); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1654); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1641); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1655); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1656); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1665); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1673); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1689); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1705); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1714); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _handlers_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1715); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1690); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1674); + const firstFrameFunction = localStack[0].function || ''; + const lastFrameFunction = localStack[localStack.length - 1].function || ''; + + // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); + } + + // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) + if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { + localStack = localStack.slice(0, -1); + } + + // The frame where the crash happened, should be the last entry in the array + return localStack + .slice(0, STACKTRACE_LIMIT) + .map(frame => ({ + ...frame, + filename: frame.filename || localStack[0].filename, + function: frame.function || '?', + })) + .reverse(); +} +const defaultFunctionName = '<anonymous>'; +/** + * Safely extract function name from itself + */ +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } +} +// eslint-disable-next-line complexity +function node(getModule) { + const FILENAME_MATCH = /^\s*[-]{4,}$/; + const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; + // eslint-disable-next-line complexity + return (line) => { + if (line.match(FILENAME_MATCH)) { + return { + filename: line, + }; + } + const lineMatch = line.match(FULL_MATCH); + if (!lineMatch) { + return undefined; + } + let object; + let method; + let functionName; + let typeName; + let methodName; + if (lineMatch[1]) { + functionName = lineMatch[1]; + let methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') { + methodStart--; + } + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + const objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = undefined; + } + if (method) { + typeName = object; + methodName = method; + } + if (method === '<anonymous>') { + methodName = undefined; + functionName = undefined; + } + if (functionName === undefined) { + methodName = methodName || '<anonymous>'; + functionName = typeName ? `${typeName}.${methodName}` : methodName; + } -; -; + const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; + const isNative = lineMatch[5] === 'native'; + const isInternal = + isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); -; -; + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 + const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); -const INTEGRATIONS = { - ..._sentry_core__WEBPACK_IMPORTED_MODULE_14__, - ..._integrations_index_js__WEBPACK_IMPORTED_MODULE_12__, -}; + return { + filename, + module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), + function: functionName, + lineno: parseInt(lineMatch[3], 10) || undefined, + colno: parseInt(lineMatch[4], 10) || undefined, + in_app, + }; + }; +} -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/core. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getMainCarrier)(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain__WEBPACK_IMPORTED_MODULE_10__; +/** + * Node.js stack line parser + * + * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. + * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain + */ +function nodeStackLineParser(getModule) { + return [90, node(getModule)]; } -//# sourceMappingURL=index.js.map +//# sourceMappingURL=stacktrace.js.map /***/ }), -/* 1640 */ +/* 1624 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "API_VERSION": () => (/* binding */ API_VERSION), -/* harmony export */ "Hub": () => (/* binding */ Hub), -/* harmony export */ "getCurrentHub": () => (/* binding */ getCurrentHub), -/* harmony export */ "getHubFromCarrier": () => (/* binding */ getHubFromCarrier), -/* harmony export */ "getMainCarrier": () => (/* binding */ getMainCarrier), -/* harmony export */ "makeMain": () => (/* binding */ makeMain), -/* harmony export */ "setHubOnCarrier": () => (/* binding */ setHubOnCarrier) +/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1644); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1645); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1641); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1642); - - - - -const NIL_EVENT_ID = '00000000000000000000000000000000'; - /** - * API compatibility version of this hub. + * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, + * descriptors, and functions. * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 * - * @hidden - */ -const API_VERSION = 4; - -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -const DEFAULT_BREADCRUMBS = 100; - -/** - * A layer in the process stack. - * @hidden - */ - -/** - * @inheritDoc + * @param ops Array result of expression conversion + * @returns The value of the expression */ -class Hub { - /** Is a {@link Layer}[] containing the client and scope */ - __init() {this._stack = [{}];} - - /** Contains the last event id of a captured event. */ - - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - constructor(client, scope = new _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope(), _version = API_VERSION) {;this._version = _version;Hub.prototype.__init.call(this); - this.getStackTop().scope = scope; - if (client) { - this.bindClient(client); - } - } - - /** - * @inheritDoc - */ - isOlderThan(version) { - return this._version < version; - } - - /** - * @inheritDoc - */ - bindClient(client) { - const top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); +function _optionalChain(ops) { + let lastAccessLHS = undefined; + let value = ops[0]; + let i = 1; + while (i < ops.length) { + const op = ops[i] ; + const fn = ops[i + 1] ; + i += 2; + // by checking for loose equality to `null`, we catch both `null` and `undefined` + if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { + // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it + return; } - } - - /** - * @inheritDoc - */ - pushScope() { - // We want to clone the content of prev scope - const scope = _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope, - }); - return scope; - } - - /** - * @inheritDoc - */ - popScope() { - if (this.getStack().length <= 1) return false; - return !!this.getStack().pop(); - } - - /** - * @inheritDoc - */ - withScope(callback) { - const scope = this.pushScope(); - try { - callback(scope); - } finally { - this.popScope(); + if (op === 'access' || op === 'optionalAccess') { + lastAccessLHS = value; + value = fn(value); + } else if (op === 'call' || op === 'optionalCall') { + value = fn((...args) => (value ).call(lastAccessLHS, ...args)); + lastAccessLHS = undefined; } } + return value; +} - /** - * @inheritDoc - */ - getClient() { - return this.getStackTop().client ; - } - - /** Returns the scope of the top stack. */ - getScope() { - return this.getStackTop().scope; - } +// Sucrase version +// function _optionalChain(ops) { +// let lastAccessLHS = undefined; +// let value = ops[0]; +// let i = 1; +// while (i < ops.length) { +// const op = ops[i]; +// const fn = ops[i + 1]; +// i += 2; +// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { +// return undefined; +// } +// if (op === 'access' || op === 'optionalAccess') { +// lastAccessLHS = value; +// value = fn(value); +// } else if (op === 'call' || op === 'optionalCall') { +// value = fn((...args) => value.call(lastAccessLHS, ...args)); +// lastAccessLHS = undefined; +// } +// } +// return value; +// } - /** Returns the scope stack for domains or the process. */ - getStack() { - return this._stack; - } - /** Returns the topmost scope layer in the order domain > local > process. */ - getStackTop() { - return this._stack[this._stack.length - 1]; - } +//# sourceMappingURL=_optionalChain.js.map - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint) { - const syntheticException = new Error('Sentry syntheticException'); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureException( - exception, - { - originalException: exception, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - ) { - const syntheticException = new Error(message); - this._lastEventId = - this._withClient((client, scope) => { - return client.captureMessage( - message, - level, - { - originalException: message, - syntheticException, - ...hint, - }, - scope, - ); - }) || NIL_EVENT_ID; - return this._lastEventId; - } +/***/ }), +/* 1625 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - captureEvent(event, hint) { - const clientId = - this._withClient((client, scope) => { - return client.captureEvent(event, { ...hint }, scope); - }) || NIL_EVENT_ID; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), +/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), +/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), +/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), +/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) +/* harmony export */ }); +// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend - if (event.type !== 'transaction') { - this._lastEventId = clientId; - } +const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds - return clientId; +/** + * Extracts Retry-After value from the request header or returns default value + * @param header string representation of 'Retry-After' header + * @param now current unix timestamp + * + */ +function parseRetryAfterHeader(header, now = Date.now()) { + const headerDelay = parseInt(`${header}`, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; } - /** - * @inheritDoc - */ - lastEventId() { - return this._lastEventId; + const headerDate = Date.parse(`${header}`); + if (!isNaN(headerDate)) { + return headerDate - now; } - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, hint) { - const { scope, client } = this.getStackTop(); - - if (!scope || !client) return; + return DEFAULT_RETRY_AFTER; +} - // eslint-disable-next-line @typescript-eslint/unbound-method - const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = - (client.getOptions && client.getOptions()) || {}; +/** + * Gets the time that given category is disabled until for rate limiting + */ +function disabledUntil(limits, category) { + return limits[category] || limits.all || 0; +} - if (maxBreadcrumbs <= 0) return; +/** + * Checks if a category is rate limited + */ +function isRateLimited(limits, category, now = Date.now()) { + return disabledUntil(limits, category) > now; +} - const timestamp = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dateTimestampInSeconds)(); - const mergedBreadcrumb = { timestamp, ...breadcrumb }; - const finalBreadcrumb = beforeBreadcrumb - ? ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => beforeBreadcrumb(mergedBreadcrumb, hint)) ) - : mergedBreadcrumb; +/** + * Update ratelimits from incoming headers. + * Returns true if headers contains a non-empty rate limiting header. + */ +function updateRateLimits( + limits, + { statusCode, headers }, + now = Date.now(), +) { + const updatedRateLimits = { + ...limits, + }; - if (finalBreadcrumb === null) return; + // "The name is case-insensitive." + // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get + const rateLimitHeader = headers && headers['x-sentry-rate-limits']; + const retryAfterHeader = headers && headers['retry-after']; - scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); + if (rateLimitHeader) { + /** + * rate limit headers are of the form + * <header>,<header>,.. + * where each <header> is of the form + * <retry_after>: <categories>: <scope>: <reason_code> + * where + * <retry_after> is a delay in seconds + * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form + * <category>;<category>;... + * <scope> is what's being limited (org, project, or key) - ignored by SDK + * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK + */ + for (const limit of rateLimitHeader.trim().split(',')) { + const [retryAfter, categories] = limit.split(':', 2); + const headerDelay = parseInt(retryAfter, 10); + const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default + if (!categories) { + updatedRateLimits.all = now + delay; + } else { + for (const category of categories.split(';')) { + updatedRateLimits[category] = now + delay; + } + } + } + } else if (retryAfterHeader) { + updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); + } else if (statusCode === 429) { + updatedRateLimits.all = now + 60 * 1000; } - /** - * @inheritDoc - */ - setUser(user) { - const scope = this.getScope(); - if (scope) scope.setUser(user); - } + return updatedRateLimits; +} - /** - * @inheritDoc - */ - setTags(tags) { - const scope = this.getScope(); - if (scope) scope.setTags(tags); - } - /** - * @inheritDoc - */ - setExtras(extras) { - const scope = this.getScope(); - if (scope) scope.setExtras(extras); - } +//# sourceMappingURL=ratelimit.js.map - /** - * @inheritDoc - */ - setTag(key, value) { - const scope = this.getScope(); - if (scope) scope.setTag(key, value); - } - /** - * @inheritDoc - */ - setExtra(key, extra) { - const scope = this.getScope(); - if (scope) scope.setExtra(key, extra); - } +/***/ }), +/* 1626 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - setContext(name, context) { - const scope = this.getScope(); - if (scope) scope.setContext(name, context); - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1628); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1615); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1633); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1613); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1627); - /** - * @inheritDoc - */ - configureScope(callback) { - const { scope, client } = this.getStackTop(); - if (scope && client) { - callback(scope); - } - } - /** - * @inheritDoc - */ - run(callback) { - const oldHub = makeMain(this); - try { - callback(this); - } finally { - makeMain(oldHub); - } - } - /** - * @inheritDoc - */ - getIntegration(integration) { - const client = this.getClient(); - if (!client) return null; - try { - return client.getIntegration(integration); - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); - return null; - } - } - /** - * @inheritDoc - */ - startTransaction(context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - } - /** - * @inheritDoc - */ - traceHeaders() { - return this._callExtensionMethod('traceHeaders'); - } - /** - * @inheritDoc - */ - captureSession(endSession = false) { - // both send the update and pull the session from the scope - if (endSession) { - return this.endSession(); - } - // only send the update - this._sendSessionUpdate(); - } +/** + * The Sentry Node SDK Client. + * + * @see NodeClientOptions for documentation on configuration options. + * @see SentryClient for usage documentation. + */ +class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { /** - * @inheritDoc + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. */ - endSession() { - const layer = this.getStackTop(); - const scope = layer && layer.scope; - const session = scope && scope.getSession(); - if (session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.closeSession)(session); - } - this._sendSessionUpdate(); + constructor(options) { + options._metadata = options._metadata || {}; + options._metadata.sdk = options._metadata.sdk || { + name: 'sentry.javascript.node', + packages: [ + { + name: 'npm:@sentry/node', + version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, + }, + ], + version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, + }; + + // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util + options.transportOptions = { + textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), + ...options.transportOptions, + }; - // the session is over; take it off of the scope - if (scope) { - scope.setSession(); - } + super(options); } /** * @inheritDoc */ - startSession(context) { - const { scope, client } = this.getStackTop(); - const { release, environment } = (client && client.getOptions()) || {}; - - // Will fetch userAgent if called from browser sdk - const { userAgent } = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.navigator || {}; - - const session = (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.makeSession)({ - release, - environment, - ...(scope && { user: scope.getUser() }), - ...(userAgent && { userAgent }), - ...context, - }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const requestSession = scope.getRequestSession(); - if (scope) { - // End existing session if there's one - const currentSession = scope.getSession && scope.getSession(); - if (currentSession && currentSession.status === 'ok') { - (0,_session_js__WEBPACK_IMPORTED_MODULE_3__.updateSession)(currentSession, { status: 'exited' }); + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; } - this.endSession(); - - // Afterwards we set the new session on the scope - scope.setSession(session); } - return session; + return super.captureException(exception, hint, scope); } /** - * Returns if default PII should be sent to Sentry and propagated in ourgoing requests - * when Tracing is used. + * @inheritDoc */ - shouldSendDefaultPii() { - const client = this.getClient(); - const options = client && client.getOptions(); - return Boolean(options && options.sendDefaultPii); - } + captureEvent(event, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + const eventType = event.type || 'exception'; + const isException = + eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; - /** - * Sends the current Session on the scope - */ - _sendSessionUpdate() { - const { scope, client } = this.getStackTop(); - if (!scope) return; + // If the event is of type Exception, then a request session should be captured + if (isException) { + const requestSession = scope.getRequestSession(); - const session = scope.getSession(); - if (session) { - if (client && client.captureSession) { - client.captureSession(session); + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === 'ok') { + requestSession.status = 'errored'; + } } } + + return super.captureEvent(event, hint, scope); } /** - * Internal helper function to call a method on the top client if it exists. * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. + * @inheritdoc */ - _withClient(callback) { - const { scope, client } = this.getStackTop(); - return client && callback(client, scope); + close(timeout) { + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); + return super.close(timeout); } - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _callExtensionMethod(method, ...args) { - const carrier = getMainCarrier(); - const sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); + /** Method that initialises an instance of SessionFlusher on Client */ + initSessionFlusher() { + const { release, environment } = this._options; + if (!release) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } else { + this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { + release, + environment, + }); } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); } -} - -/** - * Returns the global shim registry. - * - * FIXME: This function is problematic, because despite always returning a valid Carrier, - * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check - * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. - **/ -function getMainCarrier() { - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ = _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.GLOBAL_OBJ; -} - -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - const registry = getMainCarrier(); - const oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} - -/** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. - */ -function getCurrentHub() { - // Get main carrier (global for every environment) - const registry = getMainCarrier(); - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { - setHubOnCarrier(registry, new Hub()); + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + eventFromException(exception, hint) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); } - // Prefer domains over global if they are there (applicable only to Node environment) - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.isNodeEnv)()) { - return getHubFromActiveDomain(registry); + /** + * @inheritDoc + */ + eventFromMessage( + message, + // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + ) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( + (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), + ); } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - const sentry = getMainCarrier().__SENTRY__; - const activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; - - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); - } + /** + * @inheritDoc + */ + _prepareEvent(event, hint, scope) { + event.platform = event.platform || 'node'; + event.contexts = { + ...event.contexts, + runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { + name: 'node', + version: global.process.version, + }, + }; + event.server_name = + event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); + return super._prepareEvent(event, hint, scope); + } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { - const registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, _scope_js__WEBPACK_IMPORTED_MODULE_0__.Scope.clone(registryHubTopStack.scope))); + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + _captureRequestSession() { + if (!this._sessionFlusher) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } else { + this._sessionFlusher.incrementSessionStatusCount(); } - - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); } } -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); -} - -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.getGlobalSingleton)('hub', () => new Hub(), carrier); -} - -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - * @returns A boolean indicating success or failure - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) return false; - const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {}); - __SENTRY__.hub = hub; - return true; -} - -//# sourceMappingURL=hub.js.map +//# sourceMappingURL=client.js.map /***/ }), -/* 1641 */ +/* 1627 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Scope": () => (/* binding */ Scope), -/* harmony export */ "addGlobalEventProcessor": () => (/* binding */ addGlobalEventProcessor) +/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), +/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), +/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), +/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1644); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1642); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1621); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1608); /** - * Default value for maximum number of breadcrumbs added to an event. + * Extracts stack frames from the error.stack string */ -const DEFAULT_MAX_BREADCRUMBS = 100; +function parseStackFrames(stackParser, error) { + return stackParser(error.stack || '', 1); +} /** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. + * Extracts stack frames from the error and builds a Sentry Exception */ -class Scope { - /** Flag if notifying is happening. */ - - /** Callback for client to receive scope changes. */ +function exceptionFromError(stackParser, error) { + const exception = { + type: error.name || error.constructor.name, + value: error.message, + }; - /** Callback list that will be called after {@link applyToEvent}. */ + const frames = parseStackFrames(stackParser, error); + if (frames.length) { + exception.stacktrace = { frames }; + } - /** Array of breadcrumbs. */ + return exception; +} - /** User */ +/** + * Builds and Event from a Exception + * @hidden + */ +function eventFromUnknownInput(stackParser, exception, hint) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let ex = exception; + const providedMechanism = + hint && hint.data && (hint.data ).mechanism; + const mechanism = providedMechanism || { + handled: true, + type: 'generic', + }; - /** Tags */ + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(exception)) { + // This will allow us to group events based on top-level keys + // which is much better than creating new group when any key/value change + const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; - /** Extra */ + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); + const client = hub.getClient(); + const normalizeDepth = client && client.getOptions().normalizeDepth; + hub.configureScope(scope => { + scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); + }); - /** Contexts */ + ex = (hint && hint.syntheticException) || new Error(message); + (ex ).message = message; + } else { + // This handles when someone does: `throw "something awesome";` + // We use synthesized Error here so we can extract a (rough) stack trace. + ex = (hint && hint.syntheticException) || new Error(exception ); + (ex ).message = exception ; + } + mechanism.synthetic = true; + } - /** Attachments */ + const event = { + exception: { + values: [exceptionFromError(stackParser, ex )], + }, + }; - /** - * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get - * sent to Sentry - */ + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); - /** Fingerprint */ + return { + ...event, + event_id: hint && hint.event_id, + }; +} - /** Severity */ +/** + * Builds and Event from a Message + * @hidden + */ +function eventFromMessage( + stackParser, + message, // eslint-disable-next-line deprecation/deprecation + level = 'info', + hint, + attachStacktrace, +) { + const event = { + event_id: hint && hint.event_id, + level, + message, + }; - /** Transaction Name */ + if (attachStacktrace && hint && hint.syntheticException) { + const frames = parseStackFrames(stackParser, hint.syntheticException); + if (frames.length) { + event.exception = { + values: [ + { + value: message, + stacktrace: { frames }, + }, + ], + }; + } + } - /** Span */ + return event; +} - /** Session */ - /** Request Mode Session Status */ +//# sourceMappingURL=eventbuilder.js.map - // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method. - constructor() { - this._notifyingListeners = false; - this._scopeListeners = []; - this._eventProcessors = []; - this._breadcrumbs = []; - this._attachments = []; - this._user = {}; - this._tags = {}; - this._extra = {}; - this._contexts = {}; - this._sdkProcessingMetadata = {}; - } +/***/ }), +/* 1628 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - static clone(scope) { - const newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = [...scope._breadcrumbs]; - newScope._tags = { ...scope._tags }; - newScope._extra = { ...scope._extra }; - newScope._contexts = { ...scope._contexts }; - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = [...scope._eventProcessors]; - newScope._requestSession = scope._requestSession; - newScope._attachments = [...scope._attachments]; - newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata }; - } - return newScope; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1629); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1613); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1604); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1621); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1609); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1619); +/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1630); +/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1632); +/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1631); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1602); +/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1603); - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - addScopeListener(callback) { - this._scopeListeners.push(callback); - } - /** - * @inheritDoc - */ - addEventProcessor(callback) { - this._eventProcessors.push(callback); - return this; - } - /** - * @inheritDoc - */ - setUser(user) { - this._user = user || {}; - if (this._session) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_0__.updateSession)(this._session, { user }); - } - this._notifyScopeListeners(); - return this; - } - /** - * @inheritDoc - */ - getUser() { - return this._user; - } - /** - * @inheritDoc - */ - getRequestSession() { - return this._requestSession; - } - /** - * @inheritDoc - */ - setRequestSession(requestSession) { - this._requestSession = requestSession; - return this; - } - /** - * @inheritDoc - */ - setTags(tags) { - this._tags = { - ...this._tags, - ...tags, - }; - this._notifyScopeListeners(); - return this; - } +const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; + +/** + * Base implementation for all JavaScript SDK clients. + * + * Call the constructor with the corresponding options + * specific to the client subclass. To access these options later, use + * {@link Client.getOptions}. + * + * If a Dsn is specified in the options, it will be parsed and stored. Use + * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is + * invalid, the constructor will throw a {@link SentryException}. Note that + * without a valid Dsn, the SDK will not send any events to Sentry. + * + * Before sending an event, it is passed through + * {@link BaseClient._prepareEvent} to add SDK information and scope data + * (breadcrumbs and context). To add more custom information, override this + * method and extend the resulting prepared event. + * + * To issue automatically created events (e.g. via instrumentation), use + * {@link Client.captureEvent}. It will prepare the event and pass it through + * the callback lifecycle. To issue auto-breadcrumbs, use + * {@link Client.addBreadcrumb}. + * + * @example + * class NodeClient extends BaseClient<NodeOptions> { + * public constructor(options: NodeOptions) { + * super(options); + * } + * + * // ... + * } + */ +class BaseClient { + /** Options passed to the SDK. */ + + /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ + + /** Array of set up integrations. */ + __init() {this._integrations = {};} + + /** Indicates whether this client's integrations have been set up. */ + __init2() {this._integrationsInitialized = false;} - /** - * @inheritDoc - */ - setTag(key, value) { - this._tags = { ...this._tags, [key]: value }; - this._notifyScopeListeners(); - return this; - } + /** Number of calls being processed */ + __init3() {this._numProcessing = 0;} - /** - * @inheritDoc - */ - setExtras(extras) { - this._extra = { - ...this._extra, - ...extras, - }; - this._notifyScopeListeners(); - return this; - } + /** Holds flushable */ + __init4() {this._outcomes = {};} /** - * @inheritDoc + * Initializes this client instance. + * + * @param options Options for the client. */ - setExtra(key, extra) { - this._extra = { ...this._extra, [key]: extra }; - this._notifyScopeListeners(); - return this; + constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); + this._options = options; + if (options.dsn) { + this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); + const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); + this._transport = options.transport({ + recordDroppedEvent: this.recordDroppedEvent.bind(this), + ...options.transportOptions, + url, + }); + } else { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); + } } /** * @inheritDoc */ - setFingerprint(fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + captureException(exception, hint, scope) { + // ensure we haven't captured this very object before + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); + return; + } + + let eventId; + this._process( + this.eventFromException(exception, hint) + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); + + return eventId; } /** * @inheritDoc */ - setLevel( + captureMessage( + message, // eslint-disable-next-line deprecation/deprecation level, + hint, + scope, ) { - this._level = level; - this._notifyScopeListeners(); - return this; - } + let eventId; - /** - * @inheritDoc - */ - setTransactionName(name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; + const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) + ? this.eventFromMessage(String(message), level, hint) + : this.eventFromException(message, hint); + + this._process( + promisedEvent + .then(event => this._captureEvent(event, hint, scope)) + .then(result => { + eventId = result; + }), + ); + + return eventId; } /** * @inheritDoc */ - setContext(key, context) { - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } else { - this._contexts[key] = context; + captureEvent(event, hint, scope) { + // ensure we haven't captured this very object before + if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); + return; } - this._notifyScopeListeners(); - return this; - } + let eventId; - /** - * @inheritDoc - */ - setSpan(span) { - this._span = span; - this._notifyScopeListeners(); - return this; + this._process( + this._captureEvent(event, hint, scope).then(result => { + eventId = result; + }), + ); + + return eventId; } /** * @inheritDoc */ - getSpan() { - return this._span; + captureSession(session) { + if (!this._isEnabled()) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); + return; + } + + if (!(typeof session.release === 'string')) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); + } else { + this.sendSession(session); + // After sending, we set init false to indicate it's not the first occurrence + (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); + } } /** * @inheritDoc */ - getTransaction() { - // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will - // have a pointer to the currently-active transaction. - const span = this.getSpan(); - return span && span.transaction; + getDsn() { + return this._dsn; } /** * @inheritDoc */ - setSession(session) { - if (!session) { - delete this._session; - } else { - this._session = session; - } - this._notifyScopeListeners(); - return this; + getOptions() { + return this._options; } /** * @inheritDoc */ - getSession() { - return this._session; + getTransport() { + return this._transport; } /** * @inheritDoc */ - update(captureContext) { - if (!captureContext) { - return this; - } - - if (typeof captureContext === 'function') { - const updatedScope = (captureContext )(this); - return updatedScope instanceof Scope ? updatedScope : this; - } - - if (captureContext instanceof Scope) { - this._tags = { ...this._tags, ...captureContext._tags }; - this._extra = { ...this._extra, ...captureContext._extra }; - this._contexts = { ...this._contexts, ...captureContext._contexts }; - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; - } - if (captureContext._level) { - this._level = captureContext._level; - } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; - } - if (captureContext._requestSession) { - this._requestSession = captureContext._requestSession; - } - } else if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext ; - this._tags = { ...this._tags, ...captureContext.tags }; - this._extra = { ...this._extra, ...captureContext.extra }; - this._contexts = { ...this._contexts, ...captureContext.contexts }; - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - if (captureContext.requestSession) { - this._requestSession = captureContext.requestSession; - } + flush(timeout) { + const transport = this._transport; + if (transport) { + return this._isClientDoneProcessing(timeout).then(clientFinished => { + return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); + }); + } else { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); } - - return this; } /** * @inheritDoc */ - clear() { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._requestSession = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - this._attachments = []; - return this; + close(timeout) { + return this.flush(timeout).then(result => { + this.getOptions().enabled = false; + return result; + }); } - /** - * @inheritDoc - */ - addBreadcrumb(breadcrumb, maxBreadcrumbs) { - const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; - - // No data has been changed, so don't notify scope listeners - if (maxCrumbs <= 0) { - return this; + /** + * Sets up the integrations + */ + setupIntegrations() { + if (this._isEnabled() && !this._integrationsInitialized) { + this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); + this._integrationsInitialized = true; } - - const mergedBreadcrumb = { - timestamp: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dateTimestampInSeconds)(), - ...breadcrumb, - }; - this._breadcrumbs = [...this._breadcrumbs, mergedBreadcrumb].slice(-maxCrumbs); - this._notifyScopeListeners(); - - return this; } /** - * @inheritDoc + * Gets an installed integration by its `id`. + * + * @returns The installed integration or `undefined` if no integration with that `id` was installed. */ - clearBreadcrumbs() { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; + getIntegrationById(integrationId) { + return this._integrations[integrationId]; } /** * @inheritDoc */ - addAttachment(attachment) { - this._attachments.push(attachment); - return this; + getIntegration(integration) { + try { + return (this._integrations[integration.id] ) || null; + } catch (_oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); + return null; + } } /** * @inheritDoc */ - getAttachments() { - return this._attachments; + sendEvent(event, hint = {}) { + if (this._dsn) { + let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); + + for (const attachment of hint.attachments || []) { + env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( + env, + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( + attachment, + this._options.transportOptions && this._options.transportOptions.textEncoder, + ), + ); + } + + this._sendEnvelope(env); + } } /** * @inheritDoc */ - clearAttachments() { - this._attachments = []; - return this; + sendSession(session) { + if (this._dsn) { + const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); + this._sendEnvelope(env); + } } /** - * Applies data from the scope to the event and runs all event processors on it. - * - * @param event Event - * @param hint Object containing additional information about the original exception, for use by the event processors. - * @hidden + * @inheritDoc */ - applyToEvent(event, hint = {}) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = { ...this._extra, ...event.extra }; - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = { ...this._tags, ...event.tags }; - } - if (this._user && Object.keys(this._user).length) { - event.user = { ...this._user, ...event.user }; - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = { ...this._contexts, ...event.contexts }; - } - if (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; - } + recordDroppedEvent(reason, category, _event) { + // Note: we use `event` in replay, where we overwrite this hook. - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relies on that. - if (this._span) { - event.contexts = { trace: this._span.getTraceContext(), ...event.contexts }; - const transactionName = this._span.transaction && this._span.transaction.name; - if (transactionName) { - event.tags = { transaction: transactionName, ...event.tags }; - } + if (this._options.sendClientReports) { + // We want to track each category (error, transaction, session) separately + // but still keep the distinction between different type of outcomes. + // We could use nested maps, but it's much easier to read and type this way. + // A correct type for map-based implementation if we want to go that route + // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` + // With typescript 4.1 we could even use template literal types + const key = `${reason}:${category}`; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); + + // The following works because undefined + 1 === NaN and NaN is falsy + this._outcomes[key] = this._outcomes[key] + 1 || 1; } + } - this._applyFingerprint(event); + /** Updates existing session based on the provided event */ + _updateSessionFromEvent(session, event) { + let crashed = false; + let errored = false; + const exceptions = event.exception && event.exception.values; - event.breadcrumbs = [...(event.breadcrumbs || []), ...this._breadcrumbs]; - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; + if (exceptions) { + errored = true; - event.sdkProcessingMetadata = { ...event.sdkProcessingMetadata, ...this._sdkProcessingMetadata }; + for (const ex of exceptions) { + const mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } + } + } - return this._notifyEventProcessors([...getGlobalEventProcessors(), ...this._eventProcessors], event, hint); + // A session is updated and that session update is sent in only one of the two following scenarios: + // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update + // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update + const sessionNonTerminal = session.status === 'ok'; + const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); + + if (shouldUpdateAndSend) { + (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { + ...(crashed && { status: 'crashed' }), + errors: session.errors || Number(errored || crashed), + }); + this.captureSession(session); + } } /** - * Add data which will be accessible during event processing but won't get sent to Sentry + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise */ - setSDKProcessingMetadata(newData) { - this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData }; + _isClientDoneProcessing(timeout) { + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { + let ticked = 0; + const tick = 1; - return this; + const interval = setInterval(() => { + if (this._numProcessing == 0) { + clearInterval(interval); + resolve(true); + } else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } + } + }, tick); + }); + } + + /** Determines whether this SDK is enabled and a valid Dsn is present. */ + _isEnabled() { + return this.getOptions().enabled !== false && this._dsn !== undefined; } /** - * This will be called after {@link applyToEvent} is finished. + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. */ - _notifyEventProcessors( - processors, - event, - hint, - index = 0, - ) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.SyncPromise((resolve, reject) => { - const processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } else { - const result = processor({ ...event }, hint) ; + _prepareEvent(event, hint, scope) { + const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); + const prepared = { + ...event, + event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), + timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.dateTimestampInSeconds)(), + }; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - processor.id && - result === null && - _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.log(`Event processor "${processor.id}" dropped event`); + this._applyClientOptions(prepared); + this._applyIntegrationsMetadata(prepared); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.isThenable)(result)) { - void result - .then(final => this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve)) - .then(null, reject); - } else { - void this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } + // If we have scope given to us, use it as the base for further modifications. + // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. + let finalScope = scope; + if (hint.captureContext) { + finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); + } + + // We prepare the result here with a resolved Event. + let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); + + // This should be the last thing called, since we want that + // {@link Hub.addEventProcessor} gets the finished prepared event. + // + // We need to check for the existence of `finalScope.getAttachments` + // because `getAttachments` can be undefined if users are using an older version + // of `@sentry/core` that does not have the `getAttachments` method. + // See: https://github.com/getsentry/sentry-javascript/issues/5229 + if (finalScope && finalScope.getAttachments) { + // Collect attachments from the hint and scope + const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; + + if (attachments.length) { + hint.attachments = attachments; + } + + // In case we have a hub we reassign it. + result = finalScope.applyToEvent(prepared, hint); + } + + return result.then(evt => { + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); } + return evt; }); } /** - * This will be called on every set call. + * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. + * Normalized keys: + * - `breadcrumbs.data` + * - `user` + * - `contexts` + * - `extra` + * @param event Event + * @returns Normalized event */ - _notifyScopeListeners() { - // We need this check for this._notifyingListeners to be able to work on scope during updates - // If this check is not here we'll produce endless recursion when something is done with the scope - // during the callback. - if (!this._notifyingListeners) { - this._notifyingListeners = true; - this._scopeListeners.forEach(callback => { - callback(this); - }); - this._notifyingListeners = false; + _normalizeEvent(event, depth, maxBreadth) { + if (!event) { + return null; } - } - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - _applyFingerprint(event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint ? (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.arrayify)(event.fingerprint) : []; + const normalized = { + ...event, + ...(event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map(b => ({ + ...b, + ...(b.data && { + data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), + }), + })), + }), + ...(event.user && { + user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), + }), + ...(event.contexts && { + contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), + }), + ...(event.extra && { + extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), + }), + }; - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); - } + // event.contexts.trace stores information about a Transaction. Similarly, + // event.spans[] stores information about child Spans. Given that a + // Transaction is conceptually a Span, normalization should apply to both + // Transactions and Spans consistently. + // For now the decision is to skip normalization of Transactions and Spans, + // so this block overwrites the normalized event to add back the original + // Transaction information prior to normalization. + if (event.contexts && event.contexts.trace && normalized.contexts) { + normalized.contexts.trace = event.contexts.trace; - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; + // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it + if (event.contexts.trace.data) { + normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); + } } - } -} - -/** - * Returns the global event processors. - */ -function getGlobalEventProcessors() { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.getGlobalSingleton)('globalEventProcessors', () => []); -} - -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} - - -//# sourceMappingURL=scope.js.map - - -/***/ }), -/* 1642 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "closeSession": () => (/* binding */ closeSession), -/* harmony export */ "makeSession": () => (/* binding */ makeSession), -/* harmony export */ "updateSession": () => (/* binding */ updateSession) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); + // event.spans[].data may contain circular/dangerous data so we need to normalize it + if (event.spans) { + normalized.spans = event.spans.map(span => { + // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable + if (span.data) { + span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); + } + return span; + }); + } -/** - * Creates a new `Session` object by setting certain default parameters. If optional @param context - * is passed, the passed properties are applied to the session object. - * - * @param context (optional) additional properties to be applied to the returned session object - * - * @returns a new `Session` object - */ -function makeSession(context) { - // Both timestamp and started are in seconds since the UNIX epoch. - const startingTime = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); + return normalized; + } - const session = { - sid: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(), - init: true, - timestamp: startingTime, - started: startingTime, - duration: 0, - status: 'ok', - errors: 0, - ignoreDuration: false, - toJSON: () => sessionToJSON(session), - }; + /** + * Enhances event using the client configuration. + * It takes care of all "static" values like environment, release and `dist`, + * as well as truncating overly long values. + * @param event event instance to be enhanced + */ + _applyClientOptions(event) { + const options = this.getOptions(); + const { environment, release, dist, maxValueLength = 250 } = options; - if (context) { - updateSession(session, context); - } + if (!('environment' in event)) { + event.environment = 'environment' in options ? environment : 'production'; + } - return session; -} + if (event.release === undefined && release !== undefined) { + event.release = release; + } -/** - * Updates a session object with the properties passed in the context. - * - * Note that this function mutates the passed object and returns void. - * (Had to do this instead of returning a new and updated session because closing and sending a session - * makes an update to the session after it was passed to the sending logic. - * @see BaseClient.captureSession ) - * - * @param session the `Session` to update - * @param context the `SessionContext` holding the properties that should be updated in @param session - */ -// eslint-disable-next-line complexity -function updateSession(session, context = {}) { - if (context.user) { - if (!session.ipAddress && context.user.ip_address) { - session.ipAddress = context.user.ip_address; + if (event.dist === undefined && dist !== undefined) { + event.dist = dist; } - if (!session.did && !context.did) { - session.did = context.user.id || context.user.email || context.user.username; + if (event.message) { + event.message = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); } - } - session.timestamp = context.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.timestampInSeconds)(); + const exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); + } - if (context.ignoreDuration) { - session.ignoreDuration = context.ignoreDuration; - } - if (context.sid) { - // Good enough uuid validation. — Kamil - session.sid = context.sid.length === 32 ? context.sid : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.uuid4)(); - } - if (context.init !== undefined) { - session.init = context.init; - } - if (!session.did && context.did) { - session.did = `${context.did}`; - } - if (typeof context.started === 'number') { - session.started = context.started; - } - if (session.ignoreDuration) { - session.duration = undefined; - } else if (typeof context.duration === 'number') { - session.duration = context.duration; - } else { - const duration = session.timestamp - session.started; - session.duration = duration >= 0 ? duration : 0; - } - if (context.release) { - session.release = context.release; - } - if (context.environment) { - session.environment = context.environment; - } - if (!session.ipAddress && context.ipAddress) { - session.ipAddress = context.ipAddress; - } - if (!session.userAgent && context.userAgent) { - session.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - session.errors = context.errors; - } - if (context.status) { - session.status = context.status; + const request = event.request; + if (request && request.url) { + request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); + } } -} -/** - * Closes a session by setting its status and updating the session object with it. - * Internally calls `updateSession` to update the passed session object. - * - * Note that this function mutates the passed session (@see updateSession for explanation). - * - * @param session the `Session` object to be closed - * @param status the `SessionStatus` with which the session was closed. If you don't pass a status, - * this function will keep the previously set status, unless it was `'ok'` in which case - * it is changed to `'exited'`. - */ -function closeSession(session, status) { - let context = {}; - if (status) { - context = { status }; - } else if (session.status === 'ok') { - context = { status: 'exited' }; + /** + * This function adds all used integrations to the SDK info in the event. + * @param event The event that will be filled with all integrations. + */ + _applyIntegrationsMetadata(event) { + const integrationsArray = Object.keys(this._integrations); + if (integrationsArray.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; + } } - updateSession(session, context); -} + /** + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope + */ + _captureEvent(event, hint = {}, scope) { + return this._processEvent(event, hint, scope).then( + finalEvent => { + return finalEvent.event_id; + }, + reason => { + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for + // control flow, log just the message (no stack) as a log-level log. + const sentryError = reason ; + if (sentryError.logLevel === 'log') { + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); + } else { + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); + } + } + return undefined; + }, + ); + } -/** - * Serializes a passed session object to a JSON object with a slightly different structure. - * This is necessary because the Sentry backend requires a slightly different schema of a session - * than the one the JS SDKs use internally. - * - * @param session the session to be converted - * - * @returns a JSON object of the passed session - */ -function sessionToJSON(session) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ - sid: `${session.sid}`, - init: session.init, - // Make sure that sec is converted to ms for date constructor - started: new Date(session.started * 1000).toISOString(), - timestamp: new Date(session.timestamp * 1000).toISOString(), - status: session.status, - errors: session.errors, - did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined, - duration: session.duration, - attrs: { - release: session.release, - environment: session.environment, - ip_address: session.ipAddress, - user_agent: session.userAgent, - }, - }); -} + /** + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + */ + _processEvent(event, hint, scope) { + const options = this.getOptions(); + const { sampleRate } = options; + if (!this._isEnabled()) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); + } -//# sourceMappingURL=session.js.map + const isTransaction = event.type === 'transaction'; + const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; + const beforeSendProcessor = options[beforeSendProcessorName]; + // 1.0 === 100% events are sent + // 0.0 === 0% events are sent + // Sampling for transaction happens somewhere else + if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { + this.recordDroppedEvent('sample_rate', 'error', event); + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( + new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( + `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, + 'log', + ), + ); + } -/***/ }), -/* 1643 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { + return this._prepareEvent(event, hint, scope) + .then(prepared => { + if (prepared === null) { + this.recordDroppedEvent('event_processor', event.type || 'error', event); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_browserPerformanceTimeOriginMode": () => (/* binding */ _browserPerformanceTimeOriginMode), -/* harmony export */ "browserPerformanceTimeOrigin": () => (/* binding */ browserPerformanceTimeOrigin), -/* harmony export */ "dateTimestampInSeconds": () => (/* binding */ dateTimestampInSeconds), -/* harmony export */ "timestampInSeconds": () => (/* binding */ timestampInSeconds), -/* harmony export */ "timestampWithMs": () => (/* binding */ timestampWithMs), -/* harmony export */ "usingPerformanceAPI": () => (/* binding */ usingPerformanceAPI) -/* harmony export */ }); -/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1645); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); -/* module decorator */ module = __webpack_require__.hmd(module); + const isInternalException = hint.data && (hint.data ).__sentry__ === true; + if (isInternalException || !beforeSendProcessor) { + return prepared; + } + const beforeSendResult = beforeSendProcessor(prepared, hint); + return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); + }) + .then(processedEvent => { + if (processedEvent === null) { + this.recordDroppedEvent('before_send', event.type || 'error', event); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); + } + const session = scope && scope.getSession(); + if (!isTransaction && session) { + this._updateSessionFromEvent(session, processedEvent); + } -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); + // None of the Sentry built event processor will update transaction name, + // so if the transaction name has been changed by an event processor, we know + // it has to come from custom event processor added by a user + const transactionInfo = processedEvent.transaction_info; + if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { + const source = 'custom'; + processedEvent.transaction_info = { + ...transactionInfo, + source, + changes: [ + ...transactionInfo.changes, + { + source, + // use the same timestamp as the processed event. + timestamp: processedEvent.timestamp , + propagations: transactionInfo.propagations, + }, + ], + }; + } -/** - * An object that can return the current timestamp in seconds since the UNIX epoch. - */ + this.sendEvent(processedEvent, hint); + return processedEvent; + }) + .then(null, reason => { + if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { + throw reason; + } -/** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". - */ -const dateTimestampSource = { - nowSeconds: () => Date.now() / 1000, -}; + this.captureException(reason, { + data: { + __sentry__: true, + }, + originalException: reason , + }); + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( + `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, + ); + }); + } -/** - * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance} - * for accessing a high-resolution monotonic clock. - */ + /** + * Occupies the client with processing and event + */ + _process(promise) { + this._numProcessing++; + void promise.then( + value => { + this._numProcessing--; + return value; + }, + reason => { + this._numProcessing--; + return reason; + }, + ); + } -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - const { performance } = WINDOW; - if (!performance || !performance.now) { - return undefined; + /** + * @inheritdoc + */ + _sendEnvelope(envelope) { + if (this._transport && this._dsn) { + this._transport.send(envelope).then(null, reason => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); + }); + } else { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); + } } - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - const timeOrigin = Date.now() - performance.now(); + /** + * Clears outcomes on this client and returns them. + */ + _clearOutcomes() { + const outcomes = this._outcomes; + this._outcomes = {}; + return Object.keys(outcomes).map(key => { + const [reason, category] = key.split(':') ; + return { + reason, + category, + quantity: outcomes[key], + }; + }); + } + + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - return { - now: () => performance.now(), - timeOrigin, - }; } /** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. + * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. */ -function getNodePerformance() { - try { - const perfHooks = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.dynamicRequire)(module, 'perf_hooks') ; - return perfHooks.performance; - } catch (_) { - return undefined; +function _validateBeforeSendResult( + beforeSendResult, + beforeSendProcessorName, +) { + const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; + if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { + return beforeSendResult.then( + event => { + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); + } + return event; + }, + e => { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); + }, + ); + } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { + throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); } + return beforeSendResult; } -/** - * The Performance API implementation for the current platform, if available. - */ -const platformPerformance = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__.isNodeEnv)() ? getNodePerformance() : getBrowserPerformance(); -const timestampSource = - platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000, - }; +//# sourceMappingURL=baseclient.js.map -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); +/***/ }), +/* 1629 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -// Re-exported with an old name for backwards-compatibility. -const timestampWithMs = timestampInSeconds; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), +/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), +/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) +/* harmony export */ }); +/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1619); -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -const usingPerformanceAPI = platformPerformance !== undefined; + +/** Regular expression used to parse a Dsn. */ +const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; + +function isValidProtocol(protocol) { + return protocol === 'http' || protocol === 'https'; +} /** - * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only. + * Renders the string representation of this Dsn. + * + * By default, this will render the public representation without the password + * component. To get the deprecated private representation, set `withPassword` + * to true. + * + * @param withPassword When set to true, the password will be included. */ -let _browserPerformanceTimeOriginMode; +function dsnToString(dsn, withPassword = false) { + const { host, path, pass, port, projectId, protocol, publicKey } = dsn; + return ( + `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + + `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` + ); +} /** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. + * Parses a Dsn from a given string. + * + * @param str A Dsn as string + * @returns Dsn as DsnComponents */ -const browserPerformanceTimeOrigin = (() => { - // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or - // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin - // data as reliable if they are within a reasonable threshold of the current time. +function dsnFromString(str) { + const match = DSN_REGEX.exec(str); - const { performance } = WINDOW; - if (!performance || !performance.now) { - _browserPerformanceTimeOriginMode = 'none'; - return undefined; + if (!match) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); } - const threshold = 3600 * 1000; - const performanceNow = performance.now(); - const dateNow = Date.now(); - - // if timeOrigin isn't available set delta to threshold so it isn't used - const timeOriginDelta = performance.timeOrigin - ? Math.abs(performance.timeOrigin + performanceNow - dateNow) - : threshold; - const timeOriginIsReliable = timeOriginDelta < threshold; + const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); + let path = ''; + let projectId = lastPath; - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - const navigationStart = performance.timing && performance.timing.navigationStart; - const hasNavigationStart = typeof navigationStart === 'number'; - // if navigationStart isn't available set delta to threshold so it isn't used - const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; - const navigationStartIsReliable = navigationStartDelta < threshold; + const split = projectId.split('/'); + if (split.length > 1) { + path = split.slice(0, -1).join('/'); + projectId = split.pop() ; + } - if (timeOriginIsReliable || navigationStartIsReliable) { - // Use the more reliable time origin - if (timeOriginDelta <= navigationStartDelta) { - _browserPerformanceTimeOriginMode = 'timeOrigin'; - return performance.timeOrigin; - } else { - _browserPerformanceTimeOriginMode = 'navigationStart'; - return navigationStart; + if (projectId) { + const projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; } } - // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. - _browserPerformanceTimeOriginMode = 'dateNow'; - return dateNow; -})(); - + return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); +} -//# sourceMappingURL=time.js.map +function dsnFromComponents(components) { + return { + protocol: components.protocol, + publicKey: components.publicKey || '', + pass: components.pass || '', + host: components.host, + port: components.port || '', + path: components.path || '', + projectId: components.projectId, + }; +} +function validateDsn(dsn) { + if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + return; + } -/***/ }), -/* 1644 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + const { port, projectId, protocol } = dsn; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "GLOBAL_OBJ": () => (/* binding */ GLOBAL_OBJ), -/* harmony export */ "getGlobalObject": () => (/* binding */ getGlobalObject), -/* harmony export */ "getGlobalSingleton": () => (/* binding */ getGlobalSingleton) -/* harmony export */ }); -/** Internal global with common properties and Sentry extensions */ + const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; + requiredComponents.forEach(component => { + if (!dsn[component]) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); + } + }); -// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification -// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js -// core-js has the following licence: -// -// Copyright (c) 2014-2022 Denis Pushkarev -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. + if (!projectId.match(/^\d+$/)) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); + } -/** Returns 'obj' if it's the global object, otherwise returns undefined */ -function isGlobalObj(obj) { - return obj && obj.Math == Math ? obj : undefined; -} + if (!isValidProtocol(protocol)) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); + } -/** Get's the global object for the current JavaScript runtime */ -const GLOBAL_OBJ = - (typeof globalThis == 'object' && isGlobalObj(globalThis)) || - // eslint-disable-next-line no-restricted-globals - (typeof window == 'object' && isGlobalObj(window)) || - (typeof self == 'object' && isGlobalObj(self)) || - (typeof global == 'object' && isGlobalObj(global)) || - (function () { - return this; - })() || - {}; + if (port && isNaN(parseInt(port, 10))) { + throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); + } -/** - * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8 - */ -function getGlobalObject() { - return GLOBAL_OBJ ; + return true; } -/** - * Returns a global singleton contained in the global `__SENTRY__` object. - * - * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory - * function and added to the `__SENTRY__` object. - * - * @param name name of the global singleton on __SENTRY__ - * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__` - * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value - * @returns the singleton - */ -function getGlobalSingleton(name, creator, obj) { - const gbl = (obj || GLOBAL_OBJ) ; - const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {}); - const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator()); - return singleton; +/** The Sentry Dsn, identifying a Sentry instance and project. */ +function makeDsn(from) { + const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); + validateDsn(components); + return components; } -//# sourceMappingURL=worldwide.js.map +//# sourceMappingURL=dsn.js.map /***/ }), -/* 1645 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { +/* 1630 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dynamicRequire": () => (/* binding */ dynamicRequire), -/* harmony export */ "isNodeEnv": () => (/* binding */ isNodeEnv), -/* harmony export */ "loadModule": () => (/* binding */ loadModule) +/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), +/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) /* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1646); -/* module decorator */ module = __webpack_require__.hmd(module); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1629); -/** - * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something, - * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere. - */ +const SENTRY_API_VERSION = '7'; -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - // explicitly check for browser bundles as those can be optimized statically - // by terser/rollup. - return ( - !(0,_env_js__WEBPACK_IMPORTED_MODULE_0__.isBrowserBundle)() && - Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' - ); +/** Returns the prefix to construct Sentry ingestion API endpoints. */ +function getBaseApiEndpoint(dsn) { + const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; + const port = dsn.port ? `:${dsn.port}` : ''; + return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; } -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); +/** Returns the ingest API endpoint for target. */ +function _getIngestEndpoint(dsn) { + return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; +} + +/** Returns a URL-encoded string with auth config suitable for a query string. */ +function _encodedAuth(dsn, sdkInfo) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.publicKey, + sentry_version: SENTRY_API_VERSION, + ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), + }); } /** - * Helper for dynamically loading module that should work with linked dependencies. - * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` - * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during - * build time. `require.resolve` is also not available in any other way, so we cannot create, - * a fake helper like we do with `dynamicRequire`. - * - * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. - * That is to mimic the behavior of `require.resolve` exactly. + * Returns the envelope endpoint URL with auth in the query string. * - * @param moduleName module name to require - * @returns possibly required module + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. */ -function loadModule(moduleName) { - let mod; +function getEnvelopeEndpointWithUrlEncodedAuth( + dsn, + // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below + // options: ClientOptions = {} as ClientOptions, + tunnelOrOptions = {} , +) { + // TODO (v8): Use this code instead + // const { tunnel, _metadata = {} } = options; + // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; - try { - mod = dynamicRequire(module, moduleName); - } catch (e) { - // no-empty - } + const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; + const sdkInfo = + typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; - try { - const { cwd } = dynamicRequire(module, 'process'); - mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ; - } catch (e) { - // no-empty + return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; +} + +/** Returns the url to the report dialog endpoint. */ +function getReportDialogEndpoint( + dsnLike, + dialogOptions + +, +) { + const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); + const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; + + let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; + for (const key in dialogOptions) { + if (key === 'dsn') { + continue; + } + + if (key === 'user') { + const user = dialogOptions.user; + if (!user) { + continue; + } + if (user.name) { + encodedOptions += `&name=${encodeURIComponent(user.name)}`; + } + if (user.email) { + encodedOptions += `&email=${encodeURIComponent(user.email)}`; + } + } else { + encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; + } } - return mod; + return `${endpoint}?${encodedOptions}`; } -//# sourceMappingURL=node.js.map +//# sourceMappingURL=api.js.map /***/ }), -/* 1646 */ +/* 1631 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isBrowserBundle": () => (/* binding */ isBrowserBundle) +/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), +/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), +/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) /* harmony export */ }); -/* - * This module exists for optimizations in the build process through rollup and terser. We define some global - * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these - * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will - * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to - * `logger` and preventing node-related code from appearing in browser bundles. +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1601); +/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1602); + + + + +const installedIntegrations = []; + +/** Map of integrations assigned to a client */ + +/** + * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to + * preseve the order of integrations in the array. * - * Attention: - * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by - * users. These fags should live in their respective packages, as we identified user tooling (specifically webpack) - * having issues tree-shaking these constants across package boundaries. - * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want - * users to be able to shake away expressions that it guards. + * @private + */ +function filterDuplicates(integrations) { + const integrationsByName = {}; + + integrations.forEach(currentInstance => { + const { name } = currentInstance; + + const existingInstance = integrationsByName[name]; + + // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a + // default instance to overwrite an existing user instance + if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { + return; + } + + integrationsByName[name] = currentInstance; + }); + + return Object.values(integrationsByName); +} + +/** Gets integrations to install */ +function getIntegrationsToSetup(options) { + const defaultIntegrations = options.defaultIntegrations || []; + const userIntegrations = options.integrations; + + // We flag default instances, so that later we can tell them apart from any user-created instances of the same class + defaultIntegrations.forEach(integration => { + integration.isDefaultInstance = true; + }); + + let integrations; + + if (Array.isArray(userIntegrations)) { + integrations = [...defaultIntegrations, ...userIntegrations]; + } else if (typeof userIntegrations === 'function') { + integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); + } else { + integrations = defaultIntegrations; + } + + const finalIntegrations = filterDuplicates(integrations); + + // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or + // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event + // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore + // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. + const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); + if (debugIndex !== -1) { + const [debugInstance] = finalIntegrations.splice(debugIndex, 1); + finalIntegrations.push(debugInstance); + } + + return finalIntegrations; +} + +/** + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations */ +function setupIntegrations(integrations) { + const integrationIndex = {}; + + integrations.forEach(integration => { + integrationIndex[integration.name] = integration; -/** - * Figures out if we're building a browser bundle. - * - * @returns true if this is a browser bundle build. - */ -function isBrowserBundle() { - return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__; + if (installedIntegrations.indexOf(integration.name) === -1) { + integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); + installedIntegrations.push(integration.name); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); + } + }); + + return integrationIndex; } -//# sourceMappingURL=env.js.map +//# sourceMappingURL=integration.js.map /***/ }), -/* 1647 */ +/* 1632 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addContextToFrame": () => (/* binding */ addContextToFrame), -/* harmony export */ "addExceptionMechanism": () => (/* binding */ addExceptionMechanism), -/* harmony export */ "addExceptionTypeValue": () => (/* binding */ addExceptionTypeValue), -/* harmony export */ "arrayify": () => (/* binding */ arrayify), -/* harmony export */ "checkOrSetAlreadyCaught": () => (/* binding */ checkOrSetAlreadyCaught), -/* harmony export */ "getEventDescription": () => (/* binding */ getEventDescription), -/* harmony export */ "parseSemver": () => (/* binding */ parseSemver), -/* harmony export */ "uuid4": () => (/* binding */ uuid4) +/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), +/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) /* harmony export */ }); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1648); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); - - - +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1629); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1620); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1611); -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - const gbl = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ ; - const crypto = gbl.crypto || gbl.msCrypto; - - if (crypto && crypto.randomUUID) { - return crypto.randomUUID().replace(/-/g, ''); - } - - const getRandomByte = - crypto && crypto.getRandomValues ? () => crypto.getRandomValues(new Uint8Array(1))[0] : () => Math.random() * 16; - - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - // Concatenating the following numbers as strings results in '10000000100040008000100000000000' - return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c => - // eslint-disable-next-line no-bitwise - ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16), - ); -} - -function getFirstException(event) { - return event.exception && event.exception.values ? event.exception.values[0] : undefined; -} - -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - const { message, event_id: eventId } = event; - if (message) { - return message; - } - const firstException = getFirstException(event); - if (firstException) { - if (firstException.type && firstException.value) { - return `${firstException.type}: ${firstException.value}`; - } - return firstException.type || firstException.value || eventId || '<unknown>'; +/** Extract sdk info from from the API metadata */ +function getSdkMetadataForEnvelopeHeader(metadata) { + if (!metadata || !metadata.sdk) { + return; } - return eventId || '<unknown>'; + const { name, version } = metadata.sdk; + return { name, version }; } /** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden - */ -function addExceptionTypeValue(event, value, type) { - const exception = (event.exception = event.exception || {}); - const values = (exception.values = exception.values || []); - const firstException = (values[0] = values[0] || {}); - if (!firstException.value) { - firstException.value = value || ''; - } - if (!firstException.type) { - firstException.type = type || 'Error'; + * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. + * Merge with existing data if any. + **/ +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; + event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; + return event; } -/** - * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed. - * - * @param event The event to modify. - * @param newMechanism Mechanism data to add to the event. - * @hidden - */ -function addExceptionMechanism(event, newMechanism) { - const firstException = getFirstException(event); - if (!firstException) { - return; - } +/** Creates an envelope from a Session */ +function createSessionEnvelope( + session, + dsn, + metadata, + tunnel, +) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const envelopeHeaders = { + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), + }; - const defaultMechanism = { type: 'generic', handled: true }; - const currentMechanism = firstException.mechanism; - firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; + const envelopeItem = + 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; - if (newMechanism && 'data' in newMechanism) { - const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data }; - firstException.mechanism.data = mergedData; - } + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); } -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -const SEMVER_REGEXP = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; - -/** - * Represents Semantic Versioning object - */ - /** - * Parses input into a SemVer interface - * @param input string representation of a semver version + * Create an Envelope from an event. */ -function parseSemver(input) { - const match = input.match(SEMVER_REGEXP) || []; - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - const patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} +function createEventEnvelope( + event, + dsn, + metadata, + tunnel, +) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const eventType = event.type || 'event'; -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext = 5) { - const lineno = frame.lineno || 0; - const maxLines = lines.length; - const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); + enhanceEventWithSdkInfo(event, metadata && metadata.sdk); - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); + const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); - frame.context_line = (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); + // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to + // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may + // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid + // of this `delete`, lest we miss putting it back in the next time the property is in use.) + delete event.sdkProcessingMetadata; - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map((line) => (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.snipLine)(line, 0)); + const eventItem = [{ type: eventType }, event]; + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); } -/** - * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object - * in question), and marks it captured if not. - * - * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and - * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so - * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because - * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not - * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This - * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we - * see it. - * - * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on - * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent - * object wrapper forms so that this check will always work. However, because we need to flag the exact object which - * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification - * must be done before the exception captured. - * - * @param A thrown exception to check or flag as having been seen - * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen) - */ -function checkOrSetAlreadyCaught(exception) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (exception && (exception ).__sentry_captured__) { - return true; - } - - try { - // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the - // `ExtraErrorData` integration - (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.addNonEnumerableProperty)(exception , '__sentry_captured__', true); - } catch (err) { - // `exception` is a primitive, so we can't mark it seen - } - - return false; -} +function createEventEnvelopeHeaders( + event, + sdkInfo, + tunnel, + dsn, +) { + const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; -/** - * Checks whether the given input is already an array, and if it isn't, wraps it in one. - * - * @param maybeArray Input to turn into an array, if necessary - * @returns The input, if already an array, or an array with the input as the only element, if not - */ -function arrayify(maybeArray) { - return Array.isArray(maybeArray) ? maybeArray : [maybeArray]; + return { + event_id: event.event_id , + sent_at: new Date().toISOString(), + ...(sdkInfo && { sdk: sdkInfo }), + ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), + ...(event.type === 'transaction' && + dynamicSamplingContext && { + trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), + }), + }; } -//# sourceMappingURL=misc.js.map +//# sourceMappingURL=envelope.js.map /***/ }), -/* 1648 */ +/* 1633 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "escapeStringForRegex": () => (/* binding */ escapeStringForRegex), -/* harmony export */ "isMatchingPattern": () => (/* binding */ isMatchingPattern), -/* harmony export */ "safeJoin": () => (/* binding */ safeJoin), -/* harmony export */ "snipLine": () => (/* binding */ snipLine), -/* harmony export */ "stringMatchesSomePattern": () => (/* binding */ stringMatchesSomePattern), -/* harmony export */ "truncate": () => (/* binding */ truncate) +/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) /* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string (0 = unlimited) - * @returns string Encoded - */ -function truncate(str, max = 0) { - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : `${str.substr(0, max)}...`; -} /** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded + * @inheritdoc */ -function snipLine(line, colno) { - let newLine = line; - const lineLength = newLine.length; - if (lineLength <= 150) { - return newLine; - } - if (colno > lineLength) { - // eslint-disable-next-line no-param-reassign - colno = lineLength; - } +class SessionFlusher { + __init() {this.flushTimeout = 60;} + __init2() {this._pendingAggregates = {};} - let start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } + __init3() {this._isEnabled = true;} - let end = Math.min(start + 140, lineLength); - if (end > lineLength - 5) { - end = lineLength; + constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); + this._client = client; + // Call to setInterval, so that flush is called every 60 seconds + this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); + this._sessionAttrs = attrs; } - if (end === lineLength) { - start = Math.max(end - 140, 0); + + /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ + flush() { + const sessionAggregates = this.getSessionAggregates(); + if (sessionAggregates.aggregates.length === 0) { + return; + } + this._pendingAggregates = {}; + this._client.sendSession(sessionAggregates); } - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = `'{snip} ${newLine}`; + /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ + getSessionAggregates() { + const aggregates = Object.keys(this._pendingAggregates).map((key) => { + return this._pendingAggregates[parseInt(key)]; + }); + + const sessionAggregates = { + attrs: this._sessionAttrs, + aggregates, + }; + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); } - if (end < lineLength) { - newLine += ' {snip}'; + + /** JSDoc */ + close() { + clearInterval(this._intervalId); + this._isEnabled = false; + this.flush(); } - return newLine; -} + /** + * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then + * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to + * `_incrementSessionStatusCount` along with the start date + */ + incrementSessionStatusCount() { + if (!this._isEnabled) { + return; + } + const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); + const requestSession = scope && scope.getRequestSession(); -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; + if (requestSession && requestSession.status) { + this._incrementSessionStatusCount(requestSession.status, new Date()); + // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in + // case captureRequestSession is called more than once to prevent double count + if (scope) { + scope.setRequestSession(undefined); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + } } - const output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < input.length; i++) { - const value = input[i]; - try { - output.push(String(value)); - } catch (e) { - output.push('[value cannot be serialized]'); + /** + * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of + * the session received + */ + _incrementSessionStatusCount(status, date) { + // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys + const sessionStartedTrunc = new Date(date).setSeconds(0, 0); + this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + + // corresponds to aggregated sessions in one specific minute bucket + // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} + const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; + if (!aggregationCounts.started) { + aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); } - } - return output.join(delimiter); + switch (status) { + case 'errored': + aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; + return aggregationCounts.errored; + case 'ok': + aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; + return aggregationCounts.exited; + default: + aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; + return aggregationCounts.crashed; + } + } } -/** - * Checks if the given value matches a regex or string - * - * @param value The string to test - * @param pattern Either a regex or a string against which `value` will be matched - * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match - * `pattern` if it contains `pattern`. Only applies to string-type patterns. - */ -function isMatchingPattern( - value, - pattern, - requireExactStringMatch = false, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(value)) { - return false; - } - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)) { - return pattern.test(value); - } - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(pattern)) { - return requireExactStringMatch ? value === pattern : value.includes(pattern); - } +//# sourceMappingURL=sessionflusher.js.map - return false; -} -/** - * Test the given string against an array of strings and regexes. By default, string matching is done on a - * substring-inclusion basis rather than a strict equality basis - * - * @param testString The string to test - * @param patterns The patterns against which to test the string - * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to - * count. If false, `testString` will match a string pattern if it contains that pattern. - * @returns - */ -function stringMatchesSomePattern( - testString, - patterns = [], - requireExactStringMatch = false, -) { - return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch)); -} +/***/ }), +/* 1634 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/** - * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to - * `new RegExp()`. - * - * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime - * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node - * 12+). - * - * @param regexString The string to escape - * @returns An version of the string with all special regex characters escaped - */ -function escapeStringForRegex(regexString) { - // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems - // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20. - return regexString.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) +/* harmony export */ }); +/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1635); -//# sourceMappingURL=string.js.map +; +//# sourceMappingURL=index.js.map /***/ }), -/* 1649 */ +/* 1635 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isDOMError": () => (/* binding */ isDOMError), -/* harmony export */ "isDOMException": () => (/* binding */ isDOMException), -/* harmony export */ "isElement": () => (/* binding */ isElement), -/* harmony export */ "isError": () => (/* binding */ isError), -/* harmony export */ "isErrorEvent": () => (/* binding */ isErrorEvent), -/* harmony export */ "isEvent": () => (/* binding */ isEvent), -/* harmony export */ "isInstanceOf": () => (/* binding */ isInstanceOf), -/* harmony export */ "isNaN": () => (/* binding */ isNaN), -/* harmony export */ "isPlainObject": () => (/* binding */ isPlainObject), -/* harmony export */ "isPrimitive": () => (/* binding */ isPrimitive), -/* harmony export */ "isRegExp": () => (/* binding */ isRegExp), -/* harmony export */ "isString": () => (/* binding */ isString), -/* harmony export */ "isSyntheticEvent": () => (/* binding */ isSyntheticEvent), -/* harmony export */ "isThenable": () => (/* binding */ isThenable) +/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) /* harmony export */ }); -// eslint-disable-next-line @typescript-eslint/unbound-method -const objectToString = Object.prototype.toString; +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1649); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1617); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); +/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); +/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (objectToString.call(wat)) { - case '[object Error]': - case '[object Exception]': - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -/** - * Checks whether given value is an instance of the given built-in class. - * - * @param wat The value to be checked - * @param className - * @returns A boolean representing the result. - */ -function isBuiltin(wat, className) { - return objectToString.call(wat) === `[object ${className}]`; -} -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return isBuiltin(wat, 'ErrorEvent'); -} -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return isBuiltin(wat, 'DOMError'); -} -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return isBuiltin(wat, 'DOMException'); -} -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return isBuiltin(wat, 'String'); -} -/** - * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return isBuiltin(wat, 'Object'); -} -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} +// Estimated maximum size for reasonable standalone event +const GZIP_THRESHOLD = 1024 * 32; /** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Gets a stream from a Uint8Array or string + * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); +function streamFromBody(body) { + return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ + read() { + this.push(body); + this.push(null); + }, + }); } /** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. */ -function isRegExp(wat) { - return isBuiltin(wat, 'RegExp'); -} +function makeNodeTransport(options) { + const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); + const isHttps = urlSegments.protocol === 'https:'; -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} + // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` + // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` + const proxy = applyNoProxyOption( + urlSegments, + options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, + ); -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; + const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; + const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; + + // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node + // versions(>= 8) as they had memory leaks when using it: #2555 + const agent = proxy + ? (new (__webpack_require__(1636))(proxy) ) + : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); + + const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); + return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); } /** - * Checks whether given value is NaN - * {@link isNaN}. + * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * @param transportUrl The URL the transport intends to send events to. + * @param proxy The client configured proxy. + * @returns A proxy the transport should use. */ -function isNaN(wat) { - return typeof wat === 'number' && wat !== wat; +function applyNoProxyOption(transportUrlSegments, proxy) { + const { no_proxy } = process.env; + + const urlIsExemptFromProxy = + no_proxy && + no_proxy + .split(',') + .some( + exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), + ); + + if (urlIsExemptFromProxy) { + return undefined; + } else { + return proxy; + } } /** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. + * Creates a RequestExecutor to be used with `createTransport`. */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } catch (_e) { - return false; - } +function createRequestExecutor( + options, + httpModule, + agent, +) { + const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); + return function makeRequest(request) { + return new Promise((resolve, reject) => { + let body = streamFromBody(request.body); + + const headers = { ...options.headers }; + + if (request.body.length > GZIP_THRESHOLD) { + headers['content-encoding'] = 'gzip'; + body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); + } + + const req = httpModule.request( + { + method: 'POST', + agent, + headers, + hostname, + path: `${pathname}${search}`, + port, + protocol, + ca: options.caCerts, + }, + res => { + res.on('data', () => { + // Drain socket + }); + + res.on('end', () => { + // Drain socket + }); + + res.setEncoding('utf8'); + + // "Key-value pairs of header names and values. Header names are lower-cased." + // https://nodejs.org/api/http.html#http_message_headers + const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); + const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); + + resolve({ + statusCode: res.statusCode, + headers: { + 'retry-after': retryAfterHeader, + 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, + }, + }); + }, + ); + + req.on('error', reject); + body.pipe(req); + }); + }; } -//# sourceMappingURL=is.js.map +//# sourceMappingURL=http.js.map /***/ }), -/* 1650 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1636 */ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addNonEnumerableProperty": () => (/* binding */ addNonEnumerableProperty), -/* harmony export */ "convertToPlainObject": () => (/* binding */ convertToPlainObject), -/* harmony export */ "dropUndefinedKeys": () => (/* binding */ dropUndefinedKeys), -/* harmony export */ "extractExceptionKeysForMessage": () => (/* binding */ extractExceptionKeysForMessage), -/* harmony export */ "fill": () => (/* binding */ fill), -/* harmony export */ "getOriginalFunction": () => (/* binding */ getOriginalFunction), -/* harmony export */ "markFunctionWrapped": () => (/* binding */ markFunctionWrapped), -/* harmony export */ "objectify": () => (/* binding */ objectify), -/* harmony export */ "urlEncode": () => (/* binding */ urlEncode) -/* harmony export */ }); -/* harmony import */ var _browser_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1651); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1648); - - - - -/** - * Replace a method in an object with a wrapped version of itself. - * - * @param source An object that contains a method to be wrapped. - * @param name The name of the method to be wrapped. - * @param replacementFactory A higher-order function that takes the original version of the given method and returns a - * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to - * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other - * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`. - * @returns void - */ -function fill(source, name, replacementFactory) { - if (!(name in source)) { - return; - } - const original = source[name] ; - const wrapped = replacementFactory(original) ; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__webpack_require__(1637)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - markFunctionWrapped(wrapped, original); - } catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } +/***/ }), +/* 1637 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - source[name] = wrapped; -} +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __importDefault(__webpack_require__(62)); +const tls_1 = __importDefault(__webpack_require__(145)); +const url_1 = __importDefault(__webpack_require__(63)); +const assert_1 = __importDefault(__webpack_require__(91)); +const debug_1 = __importDefault(__webpack_require__(1638)); +const agent_base_1 = __webpack_require__(1642); +const parse_proxy_response_1 = __importDefault(__webpack_require__(1648)); +const debug = debug_1.default('https-proxy-agent:agent'); /** - * Defines a non-enumerable property on the given object. + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. * - * @param obj The object on which to set the property - * @param name The name of the property to be set - * @param value The value to which to set the property - */ -function addNonEnumerableProperty(obj, name, value) { - Object.defineProperty(obj, name, { - // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it - value: value, - writable: true, - configurable: true, - }); -} - -/** - * Remembers the original function on the wrapped function and - * patches up the prototype. + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. * - * @param wrapped the wrapper function - * @param original the original function that gets wrapped - */ -function markFunctionWrapped(wrapped, original) { - const proto = original.prototype || {}; - wrapped.prototype = original.prototype = proto; - addNonEnumerableProperty(wrapped, '__sentry_original__', original); -} - -/** - * This extracts the original function if available. See - * `markFunctionWrapped` for more information. + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. * - * @param func the function to unwrap - * @returns the unwrapped version of the function if available. + * @api public */ -function getOriginalFunction(func) { - return func.__sentry_original__; +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } } - -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`) - .join('&'); +exports["default"] = HttpsProxyAgent; +function resume(socket) { + socket.resume(); } - -/** - * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their - * non-enumerable properties attached. - * - * @param value Initial source that we have to transform in order for it to be usable by the serializer - * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor - * an Error. - */ -function convertToPlainObject( - value, -) - - { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isError)(value)) { - return { - message: value.message, - name: value.name, - stack: value.stack, - ...getOwnProperties(value), - }; - } else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isEvent)(value)) { - const newObj - - = { - type: value.type, - target: serializeEventTarget(value.target), - currentTarget: serializeEventTarget(value.currentTarget), - ...getOwnProperties(value), - }; - - if (typeof CustomEvent !== 'undefined' && (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isInstanceOf)(value, CustomEvent)) { - newObj.detail = value.detail; - } - - return newObj; - } else { - return value; - } +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); } - -/** Creates a string representation of the target of an `Event` object */ -function serializeEventTarget(target) { - try { - return (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isElement)(target) ? (0,_browser_js__WEBPACK_IMPORTED_MODULE_1__.htmlTreeAsString)(target) : Object.prototype.toString.call(target); - } catch (_oO) { - return '<unknown>'; - } +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; } - -/** Filters out all but an object's own properties */ -function getOwnProperties(obj) { - if (typeof obj === 'object' && obj !== null) { - const extractedProps = {}; - for (const property in obj) { - if (Object.prototype.hasOwnProperty.call(obj, property)) { - extractedProps[property] = (obj )[property]; - } +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } - return extractedProps; - } else { - return {}; - } + return ret; } +//# sourceMappingURL=agent.js.map -/** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -function extractExceptionKeysForMessage(exception, maxLength = 40) { - const keys = Object.keys(convertToPlainObject(exception)); - keys.sort(); - - if (!keys.length) { - return '[object has no keys]'; - } - - if (keys[0].length >= maxLength) { - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(keys[0], maxLength); - } - - for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) { - const serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return (0,_string_js__WEBPACK_IMPORTED_MODULE_2__.truncate)(serialized, maxLength); - } - - return ''; -} +/***/ }), +/* 1638 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** - * Given any object, return a new object having removed all fields whose value was `undefined`. - * Works recursively on objects and arrays. - * - * Attention: This function keeps circular references in the returned object. + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function dropUndefinedKeys(inputValue) { - // This map keeps track of what already visited nodes map to. - // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular - // references as the input object. - const memoizationMap = new Map(); - // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API - return _dropUndefinedKeys(inputValue, memoizationMap); +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __webpack_require__(1639); +} else { + module.exports = __webpack_require__(1641); } -function _dropUndefinedKeys(inputValue, memoizationMap) { - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(inputValue)) { - // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } - - const returnValue = {}; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); - for (const key of Object.keys(inputValue)) { - if (typeof inputValue[key] !== 'undefined') { - returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap); - } - } +/***/ }), +/* 1639 */ +/***/ ((module, exports, __webpack_require__) => { - return returnValue ; - } +/* eslint-env browser */ - if (Array.isArray(inputValue)) { - // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object - const memoVal = memoizationMap.get(inputValue); - if (memoVal !== undefined) { - return memoVal ; - } +/** + * This is the web browser implementation of `debug()`. + */ - const returnValue = []; - // Store the mapping of this value in case we visit it again, in case of circular data - memoizationMap.set(inputValue, returnValue); +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; - inputValue.forEach((item) => { - returnValue.push(_dropUndefinedKeys(item, memoizationMap)); - }); + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); - return returnValue ; - } +/** + * Colors. + */ - return inputValue; -} +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Ensure that something is an object. - * - * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper - * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * @param wat The subject of the objectification - * @returns A version of `wat` which can safely be used with `Object` class methods + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -function objectify(wat) { - let objectified; - switch (true) { - case wat === undefined || wat === null: - objectified = new String(wat); - break; - // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason - // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as - // an object in order to wrap it. - case typeof wat === 'symbol' || typeof wat === 'bigint': - objectified = Object(wat); - break; +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } - // this will catch the remaining primitives: `String`, `Number`, and `Boolean` - case (0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isPrimitive)(wat): - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - objectified = new (wat ).constructor(wat); - break; + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - // by process of elimination, at this point we know that `wat` must already be an object - default: - objectified = wat; - break; - } - return objectified; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } - -//# sourceMappingURL=object.js.map - - -/***/ }), -/* 1651 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getDomElement": () => (/* binding */ getDomElement), -/* harmony export */ "getLocationHref": () => (/* binding */ getLocationHref), -/* harmony export */ "htmlTreeAsString": () => (/* binding */ htmlTreeAsString) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); - - - -// eslint-disable-next-line deprecation/deprecation -const WINDOW = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalObject)(); - /** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path + * Colorize log arguments if enabled. + * + * @api public */ -function htmlTreeAsString(elem, keyAttrs) { - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - let currentElem = elem ; - const MAX_TRAVERSE_HEIGHT = 5; - const MAX_OUTPUT_LEN = 80; - const out = []; - let height = 0; - let len = 0; - const separator = ' > '; - const sepLength = separator.length; - let nextStr; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem, keyAttrs); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } + if (!this.useColors) { + return; + } - out.push(nextStr); + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - len += nextStr.length; - currentElem = currentElem.parentNode; - } + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - return out.reverse().join(separator); - } catch (_oO) { - return '<unknown>'; - } + args.splice(lastC, 0, c); } /** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public */ -function _htmlElementAsString(el, keyAttrs) { - const elem = el - -; - - const out = []; - let className; - let classes; - let key; - let attr; - let i; - - if (!elem || !elem.tagName) { - return ''; - } - - out.push(elem.tagName.toLowerCase()); - - // Pairs of attribute keys defined in `serializeAttribute` and their values on element. - const keyAttrPairs = - keyAttrs && keyAttrs.length - ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) - : null; - - if (keyAttrPairs && keyAttrPairs.length) { - keyAttrPairs.forEach(keyAttrPair => { - out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); - }); - } else { - if (elem.id) { - out.push(`#${elem.id}`); - } +exports.log = console.debug || console.log || (() => {}); - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push(`.${classes[i]}`); - } - } - } - const allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push(`[${key}="${attr}"]`); - } - } - return out.join(''); +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * A safe form of location.href + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private */ -function getLocationHref() { - try { - return WINDOW.document.location.href; - } catch (oO) { - return ''; - } +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; } /** - * Gets a DOM element by using document.querySelector. - * - * This wrapper will first check for the existance of the function before - * actually calling it so that we don't have to take care of this check, - * every time we want to access the DOM. - * - * Reason: DOM/querySelector is not available in all environments. + * Localstorage attempts to return the localstorage. * - * We have to cast to any because utils can be consumed by a variety of environments, - * and we don't want to break TS users. If you know what element will be selected by - * `document.querySelector`, specify it as part of the generic call. For example, - * `const element = getDomElement<Element>('selector');` + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. * - * @param selector the selector string passed on to document.querySelector + * @return {LocalStorage} + * @api private */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getDomElement(selector) { - if (WINDOW.document && WINDOW.document.querySelector) { - return WINDOW.document.querySelector(selector) ; - } - return null; + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = __webpack_require__(1640)(exports); -//# sourceMappingURL=browser.js.map +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; /***/ }), -/* 1652 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1640 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SyncPromise": () => (/* binding */ SyncPromise), -/* harmony export */ "rejectedSyncPromise": () => (/* binding */ rejectedSyncPromise), -/* harmony export */ "resolvedSyncPromise": () => (/* binding */ resolvedSyncPromise) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -/* eslint-disable @typescript-eslint/explicit-function-return-type */ +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(1405); + createDebug.destroy = destroy; -/** SyncPromise internal states */ -var States; (function (States) { - /** Pending */ - const PENDING = 0; States[States["PENDING"] = PENDING] = "PENDING"; - /** Resolved / OK */ - const RESOLVED = 1; States[States["RESOLVED"] = RESOLVED] = "RESOLVED"; - /** Rejected / Error */ - const REJECTED = 2; States[States["REJECTED"] = REJECTED] = "REJECTED"; -})(States || (States = {})); + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -// Overloads so we can call resolvedSyncPromise without arguments and generic argument + /** + * The currently active debug mode names, and names to skip. + */ -/** - * Creates a resolved sync promise. - * - * @param value the value to resolve the promise with - * @returns the resolved sync promise - */ -function resolvedSyncPromise(value) { - return new SyncPromise(resolve => { - resolve(value); - }); -} + createDebug.names = []; + createDebug.skips = []; -/** - * Creates a rejected sync promise. - * - * @param value the value to reject the promise with - * @returns the rejected sync promise - */ -function rejectedSyncPromise(reason) { - return new SyncPromise((_, reject) => { - reject(reason); - }); -} + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -class SyncPromise { - __init() {this._state = States.PENDING;} - __init2() {this._handlers = [];} + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - constructor( - executor, - ) {;SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);SyncPromise.prototype.__init5.call(this);SyncPromise.prototype.__init6.call(this); - try { - executor(this._resolve, this._reject); - } catch (e) { - this._reject(e); - } - } + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - /** JSDoc */ - then( - onfulfilled, - onrejected, - ) { - return new SyncPromise((resolve, reject) => { - this._handlers.push([ - false, - result => { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result ); - } else { - try { - resolve(onfulfilled(result)); - } catch (e) { - reject(e); - } - } - }, - reason => { - if (!onrejected) { - reject(reason); - } else { - try { - resolve(onrejected(reason)); - } catch (e) { - reject(e); - } - } - }, - ]); - this._executeHandlers(); - }); - } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - /** JSDoc */ - catch( - onrejected, - ) { - return this.then(val => val, onrejected); - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - /** JSDoc */ - finally(onfinally) { - return new SyncPromise((resolve, reject) => { - let val; - let isRejected; + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } - return this.then( - value => { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, - reason => { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }, - ).then(() => { - if (isRejected) { - reject(val); - return; - } + const self = debug; - resolve(val ); - }); - }); - } + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - /** JSDoc */ - __init3() {this._resolve = (value) => { - this._setResult(States.RESOLVED, value); - };} + args[0] = createDebug.coerce(args[0]); - /** JSDoc */ - __init4() {this._reject = (reason) => { - this._setResult(States.REJECTED, reason); - };} + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - /** JSDoc */ - __init5() {this._setResult = (state, value) => { - if (this._state !== States.PENDING) { - return; - } + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isThenable)(value)) { - void (value ).then(this._resolve, this._reject); - return; - } + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - this._state = state; - this._value = value; + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - this._executeHandlers(); - };} + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - /** JSDoc */ - __init6() {this._executeHandlers = () => { - if (this._state === States.PENDING) { - return; - } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - const cachedHandlers = this._handlers.slice(); - this._handlers = []; + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } - cachedHandlers.forEach(handler => { - if (handler[0]) { - return; - } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - if (this._state === States.RESOLVED) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler[1](this._value ); - } + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - if (this._state === States.REJECTED) { - handler[2](this._value); - } + return debug; + } - handler[0] = true; - }); - };} -} + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; -//# sourceMappingURL=syncpromise.js.map + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; -/***/ }), -/* 1653 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CONSOLE_LEVELS": () => (/* binding */ CONSOLE_LEVELS), -/* harmony export */ "consoleSandbox": () => (/* binding */ consoleSandbox), -/* harmony export */ "logger": () => (/* binding */ logger) -/* harmony export */ }); -/* harmony import */ var _worldwide_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1644); + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -/** Prefix for logging strings */ -const PREFIX = 'Sentry Logger '; + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } -const CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ; + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } -/** - * Temporarily disable sentry console instrumentations. - * - * @param callback The function to run against the original `console` messages - * @returns The results of the callback - */ -function consoleSandbox(callback) { - if (!('console' in _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ)) { - return callback(); - } + let i; + let len; - const originalConsole = _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console ; - const wrappedLevels = {}; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - // Restore all wrapped console methods - CONSOLE_LEVELS.forEach(level => { - // TODO(v7): Remove this check as it's only needed for Node 6 - const originalWrappedFunc = - originalConsole[level] && (originalConsole[level] ).__sentry_original__; - if (level in originalConsole && originalWrappedFunc) { - wrappedLevels[level] = originalConsole[level] ; - originalConsole[level] = originalWrappedFunc ; - } - }); + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - try { - return callback(); - } finally { - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(level => { - originalConsole[level] = wrappedLevels[level ]; - }); - } -} + return false; + } -function makeLogger() { - let enabled = false; - const logger = { - enable: () => { - enabled = true; - }, - disable: () => { - enabled = false; - }, - }; + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - CONSOLE_LEVELS.forEach(name => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - logger[name] = (...args) => { - if (enabled) { - consoleSandbox(() => { - _worldwide_js__WEBPACK_IMPORTED_MODULE_0__.GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args); - }); - } - }; - }); - } else { - CONSOLE_LEVELS.forEach(name => { - logger[name] = () => undefined; - }); - } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - return logger ; -} + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -let logger; -if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - logger = (0,_worldwide_js__WEBPACK_IMPORTED_MODULE_0__.getGlobalSingleton)('logger', makeLogger); -} else { - logger = makeLogger(); -} + createDebug.enable(createDebug.load()); + return createDebug; +} -//# sourceMappingURL=logger.js.map +module.exports = setup; /***/ }), -/* 1654 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1641 */ +/***/ ((module, exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SDK_VERSION": () => (/* binding */ SDK_VERSION) -/* harmony export */ }); -const SDK_VERSION = '7.23.0'; +/** + * Module dependencies. + */ +const tty = __webpack_require__(1407); +const util = __webpack_require__(64); -//# sourceMappingURL=version.js.map +/** + * This is the Node.js implementation of `debug()`. + */ +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); -/***/ }), -/* 1655 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/** + * Colors. + */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addBreadcrumb": () => (/* binding */ addBreadcrumb), -/* harmony export */ "captureEvent": () => (/* binding */ captureEvent), -/* harmony export */ "captureException": () => (/* binding */ captureException), -/* harmony export */ "captureMessage": () => (/* binding */ captureMessage), -/* harmony export */ "configureScope": () => (/* binding */ configureScope), -/* harmony export */ "setContext": () => (/* binding */ setContext), -/* harmony export */ "setExtra": () => (/* binding */ setExtra), -/* harmony export */ "setExtras": () => (/* binding */ setExtras), -/* harmony export */ "setTag": () => (/* binding */ setTag), -/* harmony export */ "setTags": () => (/* binding */ setTags), -/* harmony export */ "setUser": () => (/* binding */ setUser), -/* harmony export */ "startTransaction": () => (/* binding */ startTransaction), -/* harmony export */ "withScope": () => (/* binding */ withScope) -/* harmony export */ }); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); +exports.colors = [6, 2, 3, 4, 5, 1]; +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __webpack_require__(1408); -// Note: All functions in this file are typed with a return value of `ReturnType<Hub[HUB_FUNCTION]>`, -// where HUB_FUNCTION is some method on the Hub class. -// -// This is done to make sure the top level SDK methods stay in sync with the hub methods. -// Although every method here has an explicit return type, some of them (that map to void returns) do not -// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable. + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} /** - * Captures an exception event and sends it to Sentry. + * Build up the default `inspectOpts` object from the environment variables. * - * @param exception An exception-like object. - * @param captureContext Additional scope data to apply to exception event. - * @returns The generated eventId. + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureException(exception, { captureContext }); + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); } /** - * Captures a message event and sends it to Sentry. + * Adds ANSI color escape codes if enabled. * - * @param message The message to send to Sentry. - * @param Severity Define the level of the message. - * @returns The generated eventId. + * @api public */ -function captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - captureContext, -) { - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - const level = typeof captureContext === 'string' ? captureContext : undefined; - const context = typeof captureContext !== 'string' ? { captureContext } : undefined; - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureMessage(message, level, context); + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; } /** - * Captures a manually created event and sends it to Sentry. - * - * @param event The event to send to Sentry. - * @returns The generated eventId. + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -function captureEvent(event, hint) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().captureEvent(event, hint); + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } /** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. + * Save `namespaces`. + * + * @param {String} namespaces + * @api private */ -function configureScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().configureScope(callback); +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } /** - * Records a new breadcrumb which will be attached to future events. + * Load `namespaces`. * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. * - * @param breadcrumb The breadcrumb to record. + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function addBreadcrumb(breadcrumb) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().addBreadcrumb(breadcrumb); + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } +module.exports = __webpack_require__(1640)(exports); + +const {formatters} = module.exports; + /** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. + * Map %o to `util.inspect()`, all on a single line. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setContext(name, context); + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), +/* 1642 */ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __webpack_require__(250); +const debug_1 = __importDefault(__webpack_require__(1643)); +const promisify_1 = __importDefault(__webpack_require__(1647)); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); } +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtras(extras); -} +/***/ }), +/* 1643 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. */ -function setExtra(key, extra) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setExtra(key, extra); -} -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTags(tags); +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __webpack_require__(1644); +} else { + module.exports = __webpack_require__(1646); } -/** - * Set key:value that will be sent as tags data with the event. - * - * Can also be used to unset a tag, by passing `undefined`. - * - * @param key String key of tag - * @param value Value of tag - */ -function setTag(key, value) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setTag(key, value); -} -/** - * Updates user context information for future events. - * - * @param user User context object to be set in the current context. Pass `null` to unset the user. - */ -function setUser(user) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().setUser(user); -} +/***/ }), +/* 1644 */ +/***/ ((module, exports, __webpack_require__) => { -/** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); - * - * @param callback that will be enclosed into push/popScope. - */ -function withScope(callback) { - (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().withScope(callback); -} +/* eslint-env browser */ /** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call - * `startTransaction` directly on the hub. - * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. - * - * @returns The transaction which was just started + * This is the web browser implementation of `debug()`. */ -function startTransaction( - context, - customSamplingContext, -) { - return (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().startTransaction({ ...context }, customSamplingContext); -} - - -//# sourceMappingURL=exports.js.map - - -/***/ }), -/* 1656 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_TRANSPORT_BUFFER_SIZE": () => (/* binding */ DEFAULT_TRANSPORT_BUFFER_SIZE), -/* harmony export */ "createTransport": () => (/* binding */ createTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1657); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1664); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1658); +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; -const DEFAULT_TRANSPORT_BUFFER_SIZE = 30; + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Creates an instance of a Sentry `Transport` - * - * @param options - * @param makeRequest + * Colors. */ -function createTransport( - options, - makeRequest, - buffer = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makePromiseBuffer)(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE), -) { - let rateLimits = {}; - - const flush = (timeout) => buffer.drain(timeout); - - function send(envelope) { - const filteredEnvelopeItems = []; - - // Drop rate limited items from envelope - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(envelope, (item, type) => { - const envelopeItemDataCategory = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type); - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.isRateLimited)(rateLimits, envelopeItemDataCategory)) { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event); - } else { - filteredEnvelopeItems.push(item); - } - }); - - // Skip sending if envelope is empty after filtering out rate limited events - if (filteredEnvelopeItems.length === 0) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const filteredEnvelope = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelope[0], filteredEnvelopeItems ); - - // Creates client report for each item in an envelope - const recordEnvelopeLoss = (reason) => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.forEachEnvelopeItem)(filteredEnvelope, (item, type) => { - const event = getEventForEnvelopeItem(item, type); - options.recordDroppedEvent(reason, (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.envelopeItemTypeToDataCategory)(type), event); - }); - }; - - const requestTask = () => - makeRequest({ body: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.serializeEnvelope)(filteredEnvelope, options.textEncoder) }).then( - response => { - // We don't want to throw on NOK responses, but we want to at least log them - if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); - } - rateLimits = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.updateRateLimits)(rateLimits, response); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Failed while sending event:', error); - recordEnvelopeLoss('network_error'); - }, - ); +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; - return buffer.add(requestTask).then( - result => result, - error => { - if (error instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SentryError) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error('Skipped sending event because buffer is full.'); - recordEnvelopeLoss('queue_overflow'); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.resolvedSyncPromise)(); - } else { - throw error; - } - }, - ); - } +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - return { - send, - flush, - }; -} +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -function getEventForEnvelopeItem(item, type) { - if (type !== 'event' && type !== 'transaction') { - return undefined; - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - return Array.isArray(item) ? (item )[1] : undefined; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } - -//# sourceMappingURL=base.js.map - - -/***/ }), -/* 1657 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makePromiseBuffer": () => (/* binding */ makePromiseBuffer) -/* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1658); -/* harmony import */ var _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1652); - - - /** - * Creates an new PromiseBuffer object with the specified limit - * @param limit max number of promises that can be stored in the buffer + * Colorize log arguments if enabled. + * + * @api public */ -function makePromiseBuffer(limit) { - const buffer = []; - - function isReady() { - return limit === undefined || buffer.length < limit; - } - - /** - * Remove a promise from the queue. - * - * @param task Can be any PromiseLike<T> - * @returns Removed promise. - */ - function remove(task) { - return buffer.splice(buffer.indexOf(task), 1)[0]; - } - - /** - * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. - * - * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: - * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor - * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By - * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer - * limit check. - * @returns The original promise. - */ - function add(taskProducer) { - if (!isReady()) { - return (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.rejectedSyncPromise)(new _error_js__WEBPACK_IMPORTED_MODULE_1__.SentryError('Not adding Promise because buffer limit was reached.')); - } - - // start the task and add its promise to the queue - const task = taskProducer(); - if (buffer.indexOf(task) === -1) { - buffer.push(task); - } - void task - .then(() => remove(task)) - // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` - // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't - // have promises, so TS has to polyfill when down-compiling.) - .then(null, () => - remove(task).then(null, () => { - // We have to add another catch here because `remove()` starts a new promise chain. - }), - ); - return task; - } - /** - * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or - * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to - * `true`. - * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and - * `false` otherwise - */ - function drain(timeout) { - return new _syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.SyncPromise((resolve, reject) => { - let counter = buffer.length; +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - if (!counter) { - return resolve(true); - } + if (!this.useColors) { + return; + } - // wait for `timeout` ms and then resolve to `false` (if not cancelled first) - const capturedSetTimeout = setTimeout(() => { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - // if all promises resolve in time, cancel the timer and resolve to `true` - buffer.forEach(item => { - void (0,_syncpromise_js__WEBPACK_IMPORTED_MODULE_0__.resolvedSyncPromise)(item).then(() => { - if (!--counter) { - clearTimeout(capturedSetTimeout); - resolve(true); - } - }, reject); - }); - }); - } + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - return { - $: buffer, - add, - drain, - }; + args.splice(lastC, 0, c); } +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); -//# sourceMappingURL=promisebuffer.js.map +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -/***/ }), -/* 1658 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SentryError": () => (/* binding */ SentryError) -/* harmony export */ }); -/** An error emitted by Sentry SDKs and related utilities. */ -class SentryError extends Error { - /** Display name of this error instance. */ + return r; +} - constructor( message, logLevel = 'warn') { - super(message);this.message = message;; +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - this.name = new.target.prototype.constructor.name; - // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line - // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes - // instances of `SentryError` fail `obj instanceof SentryError` checks. - Object.setPrototypeOf(this, new.target.prototype); - this.logLevel = logLevel; - } +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = __webpack_require__(1645)(exports); -//# sourceMappingURL=error.js.map +const {formatters} = module.exports; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -/***/ }), -/* 1659 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addItemToEnvelope": () => (/* binding */ addItemToEnvelope), -/* harmony export */ "createAttachmentEnvelopeItem": () => (/* binding */ createAttachmentEnvelopeItem), -/* harmony export */ "createEnvelope": () => (/* binding */ createEnvelope), -/* harmony export */ "envelopeItemTypeToDataCategory": () => (/* binding */ envelopeItemTypeToDataCategory), -/* harmony export */ "forEachEnvelopeItem": () => (/* binding */ forEachEnvelopeItem), -/* harmony export */ "serializeEnvelope": () => (/* binding */ serializeEnvelope) -/* harmony export */ }); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1660); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); +/***/ }), +/* 1645 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** - * Creates an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. */ -function createEnvelope(headers, items = []) { - return [headers, items] ; -} -/** - * Add an item to an envelope. - * Make sure to always explicitly provide the generic to this function - * so that the envelope types resolve correctly. - */ -function addItemToEnvelope(envelope, newItem) { - const [headers, items] = envelope; - return [headers, [...items, newItem]] ; -} +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __webpack_require__(1405); + createDebug.destroy = destroy; -/** - * Convenience function to loop through the items and item types of an envelope. - * (This function was mostly created because working with envelope types is painful at the moment) - */ -function forEachEnvelopeItem( - envelope, - callback, -) { - const envelopeItems = envelope[1]; - envelopeItems.forEach((envelopeItem) => { - const envelopeItemType = envelopeItem[0].type; - callback(envelopeItem, envelopeItemType); - }); -} + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -function encodeUTF8(input, textEncoder) { - const utf8 = textEncoder || new TextEncoder(); - return utf8.encode(input); -} + /** + * The currently active debug mode names, and names to skip. + */ -/** - * Serializes an envelope. - */ -function serializeEnvelope(envelope, textEncoder) { - const [envHeaders, items] = envelope; + createDebug.names = []; + createDebug.skips = []; - // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data - let parts = JSON.stringify(envHeaders); + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; - function append(next) { - if (typeof parts === 'string') { - parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts, textEncoder), next]; - } else { - parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : next); - } - } + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; - for (const item of items) { - const [itemHeaders, payload] = item; + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - append(`\n${JSON.stringify(itemHeaders)}\n`); + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; - if (typeof payload === 'string' || payload instanceof Uint8Array) { - append(payload); - } else { - let stringifiedPayload; - try { - stringifiedPayload = JSON.stringify(payload); - } catch (e) { - // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still - // fails, we try again after normalizing it again with infinite normalization depth. This of course has a - // performance impact but in this case a performance hit is better than throwing. - stringifiedPayload = JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_0__.normalize)(payload)); - } - append(stringifiedPayload); - } - } + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; - return typeof parts === 'string' ? parts : concatBuffers(parts); -} + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -function concatBuffers(buffers) { - const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); + const self = debug; - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const buffer of buffers) { - merged.set(buffer, offset); - offset += buffer.length; - } + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - return merged; -} + args[0] = createDebug.coerce(args[0]); -/** - * Creates attachment envelope items - */ -function createAttachmentEnvelopeItem( - attachment, - textEncoder, -) { - const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : attachment.data; + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - return [ - (0,_object_js__WEBPACK_IMPORTED_MODULE_1__.dropUndefinedKeys)({ - type: 'attachment', - length: buffer.length, - filename: attachment.filename, - content_type: attachment.contentType, - attachment_type: attachment.attachmentType, - }), - buffer, - ]; -} + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } -const ITEM_TYPE_TO_DATA_CATEGORY_MAP = { - session: 'session', - sessions: 'session', - attachment: 'attachment', - transaction: 'transaction', - event: 'error', - client_report: 'internal', - user_report: 'default', -}; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. -/** - * Maps the type of an envelope item to a data category. - */ -function envelopeItemTypeToDataCategory(type) { - return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; -} + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); -//# sourceMappingURL=envelope.js.map + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + return debug; + } -/***/ }), -/* 1660 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "normalize": () => (/* binding */ normalize), -/* harmony export */ "normalizeToSize": () => (/* binding */ normalizeToSize), -/* harmony export */ "walk": () => (/* binding */ visit) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _memo_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1661); -/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); -/* harmony import */ var _stacktrace_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1662); + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + namespaces = split[i].replace(/\*/g, '.*?'); -/** - * Recursively normalizes the given object. - * - * - Creates a copy to prevent original input mutation - * - Skips non-enumerable properties - * - When stringifying, calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format - * - Translates known global objects/classes to a string representations - * - Takes care of `Error` object serialization - * - Optionally limits depth of final output - * - Optionally limits number of properties/elements included in any single object/array - * - * @param input The object to be normalized. - * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.) - * @param maxProperties The max number of elements or properties to be included in any single array or - * object in the normallized output. - * @returns A normalized version of the object, or `"**non-serializable**"` if any errors are thrown during normalization. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function normalize(input, depth = +Infinity, maxProperties = +Infinity) { - try { - // since we're at the outermost level, we don't provide a key - return visit('', input, depth, maxProperties); - } catch (err) { - return { ERROR: `**non-serializable** (${err})` }; - } -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -/** JSDoc */ -function normalizeToSize( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object, - // Default Node.js REPL depth - depth = 3, - // 100kB, as 200kB is max payload size, so half sounds reasonable - maxSize = 100 * 1024, -) { - const normalized = normalize(object, depth); + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - if (jsonSize(normalized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - return normalized ; -} + let i; + let len; -/** - * Visits a node to perform normalization on it - * - * @param key The key corresponding to the given node - * @param value The node to be visited - * @param depth Optional number indicating the maximum recursion depth - * @param maxProperties Optional maximum number of properties/elements included in any single object/array - * @param memo Optional Memo class handling decycling - */ -function visit( - key, - value, - depth = +Infinity, - maxProperties = +Infinity, - memo = (0,_memo_js__WEBPACK_IMPORTED_MODULE_0__.memoBuilder)(), -) { - const [memoize, unmemoize] = memo; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - // Get the simple cases out of the way first - if (value === null || (['number', 'boolean', 'string'].includes(typeof value) && !(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isNaN)(value))) { - return value ; - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - const stringified = stringifyValue(key, value); + return false; + } - // Anything we could potentially dig into more (objects or arrays) will have come back as `"[object XXXX]"`. - // Everything else will have already been serialized, so if we don't see that pattern, we're done. - if (!stringified.startsWith('[object ')) { - return stringified; - } + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - // From here on, we can assert that `value` is either an object or an array. + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - // Do not normalize objects that we know have already been normalized. As a general rule, the - // "__sentry_skip_normalization__" property should only be used sparingly and only should only be set on objects that - // have already been normalized. - if ((value )['__sentry_skip_normalization__']) { - return value ; - } + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - // We're also done if we've reached the max depth - if (depth === 0) { - // At this point we know `serialized` is a string of the form `"[object XXXX]"`. Clean it up so it's just `"[XXXX]"`. - return stringified.replace('object ', ''); - } + createDebug.enable(createDebug.load()); + + return createDebug; +} - // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now. - if (memoize(value)) { - return '[Circular ~]'; - } +module.exports = setup; - // If the value has a `toJSON` method, we call it to extract more information - const valueWithToJSON = value ; - if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') { - try { - const jsonValue = valueWithToJSON.toJSON(); - // We need to normalize the return value of `.toJSON()` in case it has circular references - return visit('', jsonValue, depth - 1, maxProperties, memo); - } catch (err) { - // pass (The built-in `toJSON` failed, but we can still try to do it ourselves) - } - } - // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse - // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each - // property/entry, and keep track of the number of items we add to it. - const normalized = (Array.isArray(value) ? [] : {}) ; - let numAdded = 0; +/***/ }), +/* 1646 */ +/***/ ((module, exports, __webpack_require__) => { - // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant - // properties are non-enumerable and otherwise would get missed. - const visitable = (0,_object_js__WEBPACK_IMPORTED_MODULE_2__.convertToPlainObject)(value ); +/** + * Module dependencies. + */ - for (const visitKey in visitable) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { - continue; - } +const tty = __webpack_require__(1407); +const util = __webpack_require__(64); - if (numAdded >= maxProperties) { - normalized[visitKey] = '[MaxProperties ~]'; - break; - } +/** + * This is the Node.js implementation of `debug()`. + */ - // Recursively visit all the child nodes - const visitValue = visitable[visitKey]; - normalized[visitKey] = visit(visitKey, visitValue, depth - 1, maxProperties, memo); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - numAdded++; - } +/** + * Colors. + */ - // Once we've visited all the branches, remove the parent from memo storage - unmemoize(value); +exports.colors = [6, 2, 3, 4, 5, 1]; - // Return accumulated values - return normalized; +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __webpack_require__(1408); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** - * Stringify the given value. Handles various known special values and types. - * - * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn - * the number 1231 into "[Object Number]", nor on `null`, as it will throw. + * Build up the default `inspectOpts` object from the environment variables. * - * @param value The value to stringify - * @returns A stringified representation of the given value + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function stringifyValue( - key, - // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for - // our internal use, it'll do - value, -) { - try { - if (key === 'domain' && value && typeof value === 'object' && (value )._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); - // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first - // which won't throw if they are not present. + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } + obj[prop] = val; + return obj; +}, {}); - // eslint-disable-next-line no-restricted-globals - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - // eslint-disable-next-line no-restricted-globals - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} - // React's SyntheticEvent thingy - if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isSyntheticEvent)(value)) { - return '[SyntheticEvent]'; - } +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } +function formatArgs(args) { + const {namespace: name, useColors} = this; - // this catches `undefined` (but not `null`, which is a primitive and can be serialized on its own) - if (value === void 0) { - return '[undefined]'; - } + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; - if (typeof value === 'function') { - return `[Function: ${(0,_stacktrace_js__WEBPACK_IMPORTED_MODULE_3__.getFunctionName)(value)}]`; - } + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} - if (typeof value === 'symbol') { - return `[${String(value)}]`; - } +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} - // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion - if (typeof value === 'bigint') { - return `[BigInt: ${String(value)}]`; - } +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting - // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as - // `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class), - // we can make sure that only plain objects come out that way. - return `[object ${(Object.getPrototypeOf(value) ).constructor.name}]`; - } catch (err) { - return `**non-serializable** (${err})`; - } +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } -/** Calculates bytes size of input object */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -//# sourceMappingURL=normalize.js.map +function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -/***/ }), -/* 1661 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +module.exports = __webpack_require__(1645)(exports); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "memoBuilder": () => (/* binding */ memoBuilder) -/* harmony export */ }); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ +const {formatters} = module.exports; /** - * Helper to decycle json objects + * Map %o to `util.inspect()`, all on a single line. */ -function memoBuilder() { - const hasWeakSet = typeof WeakSet === 'function'; - const inner = hasWeakSet ? new WeakSet() : []; - function memoize(obj) { - if (hasWeakSet) { - if (inner.has(obj)) { - return true; - } - inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < inner.length; i++) { - const value = inner[i]; - if (value === obj) { - return true; - } - } - inner.push(obj); - return false; - } - function unmemoize(obj) { - if (hasWeakSet) { - inner.delete(obj); - } else { - for (let i = 0; i < inner.length; i++) { - if (inner[i] === obj) { - inner.splice(i, 1); - break; - } - } - } - } - return [memoize, unmemoize]; -} +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ -//# sourceMappingURL=memo.js.map +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /***/ }), -/* 1662 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1647 */ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createStackParser": () => (/* binding */ createStackParser), -/* harmony export */ "getFunctionName": () => (/* binding */ getFunctionName), -/* harmony export */ "nodeStackLineParser": () => (/* binding */ nodeStackLineParser), -/* harmony export */ "stackParserFromStackParserOptions": () => (/* binding */ stackParserFromStackParserOptions), -/* harmony export */ "stripSentryFramesAndReverse": () => (/* binding */ stripSentryFramesAndReverse) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1663); - -const STACKTRACE_LIMIT = 50; - -/** - * Creates a stack parser with the supplied line parsers - * - * StackFrames are returned in the correct order for Sentry Exception - * frames and with Sentry SDK internal frames removed from the top and bottom - * - */ -function createStackParser(...parsers) { - const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]); - - return (stack, skipFirst = 0) => { - const frames = []; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports["default"] = promisify; +//# sourceMappingURL=promisify.js.map - for (const line of stack.split('\n').slice(skipFirst)) { - // https://github.com/getsentry/sentry-javascript/issues/5459 - // Remove webpack (error: *) wrappers - const cleanedLine = line.replace(/\(error: (.*)\)/, '$1'); +/***/ }), +/* 1648 */ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - for (const parser of sortedParsers) { - const frame = parser(cleanedLine); +"use strict"; - if (frame) { - frames.push(frame); - break; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __importDefault(__webpack_require__(1638)); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); } - } - } - - return stripSentryFramesAndReverse(frames); - }; + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); } +exports["default"] = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + +/***/ }), +/* 1649 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) +/* harmony export */ }); /** - * Gets a stack parser implementation from Options.stackParser - * @see Options + * Polyfill for the nullish coalescing operator (`??`). * - * If options contains an array of line parsers, it is converted into a parser + * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the + * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. + * + * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * + * @param lhs The value of the expression to the left of the `??` + * @param rhsFn A function returning the value of the expression to the right of the `??` + * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value */ -function stackParserFromStackParserOptions(stackParser) { - if (Array.isArray(stackParser)) { - return createStackParser(...stackParser); - } - return stackParser; +function _nullishCoalesce(lhs, rhsFn) { + // by checking for loose equality to `null`, we catch both `null` and `undefined` + return lhs != null ? lhs : rhsFn(); } -/** - * @hidden - */ -function stripSentryFramesAndReverse(stack) { - if (!stack.length) { - return []; - } +// Sucrase version: +// function _nullishCoalesce(lhs, rhsFn) { +// if (lhs != null) { +// return lhs; +// } else { +// return rhsFn(); +// } +// } - let localStack = stack; - const firstFrameFunction = localStack[0].function || ''; - const lastFrameFunction = localStack[localStack.length - 1].function || ''; +//# sourceMappingURL=_nullishCoalesce.js.map - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); - } +/***/ }), +/* 1650 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(frame => ({ - ...frame, - filename: frame.filename || localStack[0].filename, - function: frame.function || '?', - })) - .reverse(); -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "close": () => (/* binding */ close), +/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), +/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), +/* harmony export */ "flush": () => (/* binding */ flush), +/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), +/* harmony export */ "init": () => (/* binding */ init), +/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), +/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1672); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1673); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1631); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1674); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1623); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1605); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1626); +/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1651); +/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1670); +/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1634); +/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1652); +/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1654); +/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1657); +/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1659); +/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1661); +/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1664); +/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1663); +/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1665); +/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1660); +/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1635); -const defaultFunctionName = '<anonymous>'; -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} -// eslint-disable-next-line complexity -function node(getModule) { - const FILENAME_MATCH = /^\s*[-]{4,}$/; - const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/; - // eslint-disable-next-line complexity - return (line) => { - if (line.match(FILENAME_MATCH)) { - return { - filename: line, - }; - } - const lineMatch = line.match(FULL_MATCH); - if (!lineMatch) { - return undefined; - } - let object; - let method; - let functionName; - let typeName; - let methodName; - if (lineMatch[1]) { - functionName = lineMatch[1]; - let methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - methodStart--; - } - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - const objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = undefined; - } - if (method) { - typeName = object; - methodName = method; - } - if (method === '<anonymous>') { - methodName = undefined; - functionName = undefined; - } - if (functionName === undefined) { - methodName = methodName || '<anonymous>'; - functionName = typeName ? `${typeName}.${methodName}` : methodName; - } - const filename = (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([lineMatch, 'access', _ => _[2], 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3('file://')]) ? lineMatch[2].substr(7) : lineMatch[2]; - const isNative = lineMatch[5] === 'native'; - const isInternal = - isNative || (filename && !filename.startsWith('/') && !filename.startsWith('.') && filename.indexOf(':\\') !== 1); - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - const in_app = !isInternal && filename !== undefined && !filename.includes('node_modules/'); - return { - filename, - module: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_0__._optionalChain)([getModule, 'optionalCall', _4 => _4(filename)]), - function: functionName, - lineno: parseInt(lineMatch[3], 10) || undefined, - colno: parseInt(lineMatch[4], 10) || undefined, - in_app, - }; - }; -} -/** - * Node.js stack line parser - * - * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`. - * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain - */ -function nodeStackLineParser(getModule) { - return [90, node(getModule)]; -} -//# sourceMappingURL=stacktrace.js.map +/* eslint-disable max-lines */ -/***/ }), -/* 1663 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +const defaultIntegrations = [ + // Common + new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), + new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), + // Native Wrappers + new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), + new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), + // Global Handlers + new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), + new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), + // Event Info + new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), + new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), + new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), + new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), + // Misc + new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), +]; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_optionalChain": () => (/* binding */ _optionalChain) -/* harmony export */ }); /** - * Polyfill for the optional chain operator, `?.`, given previous conversion of the expression into an array of values, - * descriptors, and functions. + * The Sentry Node SDK Client. * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) - * See https://github.com/alangpierce/sucrase/blob/265887868966917f3b924ce38dfad01fbab1329f/src/transformers/OptionalChainingNullishTransformer.ts#L15 + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. + * + * @example + * ``` + * + * const { init } = require('@sentry/node'); + * + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` + * + * @example + * ``` + * + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` * - * @param ops Array result of expression conversion - * @returns The value of the expression + * @see {@link NodeOptions} for documentation on configuration options. */ -function _optionalChain(ops) { - let lastAccessLHS = undefined; - let value = ops[0]; - let i = 1; - while (i < ops.length) { - const op = ops[i] ; - const fn = ops[i + 1] ; - i += 2; - // by checking for loose equality to `null`, we catch both `null` and `undefined` - if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { - // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it - return; +function init(options = {}) { + const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); + const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; + + options.defaultIntegrations = + options.defaultIntegrations === false + ? [] + : [ + ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), + ...autoloadedIntegrations, + ]; + + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; + } + + if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { + const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); + if (isFinite(tracesSampleRate)) { + options.tracesSampleRate = tracesSampleRate; } - if (op === 'access' || op === 'optionalAccess') { - lastAccessLHS = value; - value = fn(value); - } else if (op === 'call' || op === 'optionalCall') { - value = fn((...args) => (value ).call(lastAccessLHS, ...args)); - lastAccessLHS = undefined; + } + + if (options.release === undefined) { + const detectedRelease = getSentryRelease(); + if (detectedRelease !== undefined) { + options.release = detectedRelease; + } else { + // If release is not provided, then we should disable autoSessionTracking + options.autoSessionTracking = false; } } - return value; -} -// Sucrase version -// function _optionalChain(ops) { -// let lastAccessLHS = undefined; -// let value = ops[0]; -// let i = 1; -// while (i < ops.length) { -// const op = ops[i]; -// const fn = ops[i + 1]; -// i += 2; -// if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { -// return undefined; -// } -// if (op === 'access' || op === 'optionalAccess') { -// lastAccessLHS = value; -// value = fn(value); -// } else if (op === 'call' || op === 'optionalCall') { -// value = fn((...args) => value.call(lastAccessLHS, ...args)); -// lastAccessLHS = undefined; -// } -// } -// return value; -// } + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } + if (options.autoSessionTracking === undefined && options.dsn !== undefined) { + options.autoSessionTracking = true; + } -//# sourceMappingURL=_optionalChain.js.map + if (options.instrumenter === undefined) { + options.instrumenter = 'sentry'; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); + } -/***/ }), -/* 1664 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // TODO(v7): Refactor this to reduce the logic above + const clientOptions = { + ...options, + stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), + integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), + transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, + }; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_RETRY_AFTER": () => (/* binding */ DEFAULT_RETRY_AFTER), -/* harmony export */ "disabledUntil": () => (/* binding */ disabledUntil), -/* harmony export */ "isRateLimited": () => (/* binding */ isRateLimited), -/* harmony export */ "parseRetryAfterHeader": () => (/* binding */ parseRetryAfterHeader), -/* harmony export */ "updateRateLimits": () => (/* binding */ updateRateLimits) -/* harmony export */ }); -// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); -const DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds + if (options.autoSessionTracking) { + startSessionTracking(); + } +} /** - * Extracts Retry-After value from the request header or returns default value - * @param header string representation of 'Retry-After' header - * @param now current unix timestamp + * This is the getter for lastEventId. * + * @returns The last event id of a captured event. */ -function parseRetryAfterHeader(header, now = Date.now()) { - const headerDelay = parseInt(`${header}`, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } +function lastEventId() { + return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); +} - const headerDate = Date.parse(`${header}`); - if (!isNaN(headerDate)) { - return headerDate - now; +/** + * Call `flush()` on the current client, if there is one. See {@link Client.flush}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause + * the client to wait until all events are sent before resolving the promise. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). + */ +async function flush(timeout) { + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); + if (client) { + return client.flush(timeout); } - - return DEFAULT_RETRY_AFTER; + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); + return Promise.resolve(false); } /** - * Gets the time that given category is disabled until for rate limiting + * Call `close()` on the current client, if there is one. See {@link Client.close}. + * + * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this + * parameter will cause the client to wait until all events are sent before disabling itself. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). */ -function disabledUntil(limits, category) { - return limits[category] || limits.all || 0; +async function close(timeout) { + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); + if (client) { + return client.close(timeout); + } + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); + return Promise.resolve(false); } /** - * Checks if a category is rate limited + * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client */ -function isRateLimited(limits, category, now = Date.now()) { - return disabledUntil(limits, category) > now; +function isAutoSessionTrackingEnabled(client) { + if (client === undefined) { + return false; + } + const clientOptions = client && client.getOptions(); + if (clientOptions && clientOptions.autoSessionTracking !== undefined) { + return clientOptions.autoSessionTracking; + } + return false; } /** - * Update ratelimits from incoming headers. - * Returns true if headers contains a non-empty rate limiting header. + * Returns a release dynamically from environment variables. */ -function updateRateLimits( - limits, - { statusCode, headers }, - now = Date.now(), -) { - const updatedRateLimits = { - ...limits, - }; - - // "The name is case-insensitive." - // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - const rateLimitHeader = headers && headers['x-sentry-rate-limits']; - const retryAfterHeader = headers && headers['retry-after']; +function getSentryRelease(fallback) { + // Always read first as Sentry takes this as precedence + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; + } - if (rateLimitHeader) { - /** - * rate limit headers are of the form - * <header>,<header>,.. - * where each <header> is of the form - * <retry_after>: <categories>: <scope>: <reason_code> - * where - * <retry_after> is a delay in seconds - * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form - * <category>;<category>;... - * <scope> is what's being limited (org, project, or key) - ignored by SDK - * <reason_code> is an arbitrary string like "org_quota" - ignored by SDK - */ - for (const limit of rateLimitHeader.trim().split(',')) { - const [retryAfter, categories] = limit.split(':', 2); - const headerDelay = parseInt(retryAfter, 10); - const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - if (!categories) { - updatedRateLimits.all = now + delay; - } else { - for (const category of categories.split(';')) { - updatedRateLimits[category] = now + delay; - } - } - } - } else if (retryAfterHeader) { - updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now); - } else if (statusCode === 429) { - updatedRateLimits.all = now + 60 * 1000; + // This supports the variable that sentry-webpack-plugin injects + if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { + return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; } - return updatedRateLimits; + return ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env.GITHUB_SHA || + // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env.COMMIT_REF || + // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env.VERCEL_GIT_COMMIT_SHA || + process.env.VERCEL_GITHUB_COMMIT_SHA || + process.env.VERCEL_GITLAB_COMMIT_SHA || + process.env.VERCEL_BITBUCKET_COMMIT_SHA || + // Zeit (now known as Vercel) + process.env.ZEIT_GITHUB_COMMIT_SHA || + process.env.ZEIT_GITLAB_COMMIT_SHA || + process.env.ZEIT_BITBUCKET_COMMIT_SHA || + fallback + ); +} + +/** Node.js stack parser */ +const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); + +/** + * Enable automatic Session Tracking for the node process. + */ +function startSessionTracking() { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); + hub.startSession(); + // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because + // The 'beforeExit' event is not emitted for conditions causing explicit termination, + // such as calling process.exit() or uncaught exceptions. + // Ref: https://nodejs.org/api/process.html#process_event_beforeexit + process.on('beforeExit', () => { + const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); + const terminalStates = ['exited', 'crashed']; + // Only call endSession, if the Session exists on Scope and SessionStatus is not a + // Terminal Status i.e. Exited or Crashed because + // "When a session is moved away from ok it must not be updated anymore." + // Ref: https://develop.sentry.dev/sdk/sessions/ + if (session && !terminalStates.includes(session.status)) hub.endSession(); + }); } -//# sourceMappingURL=ratelimit.js.map +//# sourceMappingURL=sdk.js.map /***/ }), -/* 1665 */ +/* 1651 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "NodeClient": () => (/* binding */ NodeClient) +/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), +/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), +/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), +/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), +/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), +/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), +/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), +/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), +/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1667); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1654); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1672); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1652); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1666); - +/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1652); +/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1654); +/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1657); +/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1659); +/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1660); +/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); +/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1661); +/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1664); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1665); -/** - * The Sentry Node SDK Client. - * - * @see NodeClientOptions for documentation on configuration options. - * @see SentryClient for usage documentation. - */ -class NodeClient extends _sentry_core__WEBPACK_IMPORTED_MODULE_3__.BaseClient { - - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - constructor(options) { - options._metadata = options._metadata || {}; - options._metadata.sdk = options._metadata.sdk || { - name: 'sentry.javascript.node', - packages: [ - { - name: 'npm:@sentry/node', - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }, - ], - version: _sentry_core__WEBPACK_IMPORTED_MODULE_4__.SDK_VERSION, - }; - // Until node supports global TextEncoder in all versions we support, we are forced to pass it from util - options.transportOptions = { - textEncoder: new util__WEBPACK_IMPORTED_MODULE_1__.TextEncoder(), - ...options.transportOptions, - }; - super(options); - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const requestSession = scope.getRequestSession(); +//# sourceMappingURL=index.js.map - // Necessary checks to ensure this is code block is executed only within a request - // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - return super.captureException(exception, hint, scope); - } +/***/ }), +/* 1652 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only - // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload - // sent to the Server only when the `requestHandler` middleware is used - if (this._options.autoSessionTracking && this._sessionFlusher && scope) { - const eventType = event.type || 'exception'; - const isException = - eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Console": () => (/* binding */ Console) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); - // If the event is of type Exception, then a request session should be captured - if (isException) { - const requestSession = scope.getRequestSession(); - // Ensure that this is happening within the bounds of a request, and make sure not to override - // Session Status if Errored / Crashed - if (requestSession && requestSession.status === 'ok') { - requestSession.status = 'errored'; - } - } - } - return super.captureEvent(event, hint, scope); - } +/** Console module integration */ +class Console {constructor() { Console.prototype.__init.call(this); } /** - * - * @inheritdoc + * @inheritDoc */ - close(timeout) { - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([this, 'access', _ => _._sessionFlusher, 'optionalAccess', _2 => _2.close, 'call', _3 => _3()]); - return super.close(timeout); - } - - /** Method that initialises an instance of SessionFlusher on Client */ - initSessionFlusher() { - const { release, environment } = this._options; - if (!release) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); - } else { - this._sessionFlusher = new _sentry_core__WEBPACK_IMPORTED_MODULE_7__.SessionFlusher(this, { - release, - environment, - }); - } - } + static __initStatic() {this.id = 'Console';} /** * @inheritDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - eventFromException(exception, hint) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)((0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromUnknownInput)(this._options.stackParser, exception, hint)); - } + __init() {this.name = Console.id;} /** * @inheritDoc */ - eventFromMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - ) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.resolvedSyncPromise)( - (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_2__.eventFromMessage)(this._options.stackParser, message, level, hint, this._options.attachStacktrace), - ); + setupOnce() { + for (const level of ['debug', 'info', 'warn', 'error', 'log']) { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); + } } +} Console.__initStatic(); - /** - * @inheritDoc - */ - _prepareEvent(event, hint, scope) { - event.platform = event.platform || 'node'; - event.contexts = { - ...event.contexts, - runtime: (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _4 => _4.contexts, 'optionalAccess', _5 => _5.runtime]) || { - name: 'node', - version: global.process.version, - }, +/** + * Wrapper function that'll be used for every console level + */ +function createConsoleWrapper(level) { + return function consoleWrapper(originalConsoleMethod) { + const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); + + /* eslint-disable prefer-rest-params */ + return function () { + if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( + { + category: 'console', + level: sentryLevel, + message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), + }, + { + input: [...arguments], + level, + }, + ); + } + + originalConsoleMethod.apply(this, arguments); }; - event.server_name = - event.server_name || this.getOptions().serverName || global.process.env.SENTRY_NAME || os__WEBPACK_IMPORTED_MODULE_0__.hostname(); - return super._prepareEvent(event, hint, scope); - } + /* eslint-enable prefer-rest-params */ + }; +} - /** - * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment - * appropriate session aggregates bucket - */ - _captureRequestSession() { - if (!this._sessionFlusher) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); - } else { - this._sessionFlusher.incrementSessionStatusCount(); - } - } + +//# sourceMappingURL=console.js.map + + +/***/ }), +/* 1653 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), +/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), +/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) +/* harmony export */ }); +// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either +// +// a) moving `validSeverityLevels` to `@sentry/types`, +// b) moving the`SeverityLevel` type here, or +// c) importing `validSeverityLevels` from here into `@sentry/types`. +// +// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would +// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the +// type, reminding anyone who changes it to change this list also, will have to do. + +const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; + +/** + * Converts a string-based level into a member of the deprecated {@link Severity} enum. + * + * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. + * + * @param level String representation of Severity + * @returns Severity + */ +function severityFromString(level) { + return severityLevelFromString(level) ; +} + +/** + * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. + * + * @param level String representation of desired `SeverityLevel`. + * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. + */ +function severityLevelFromString(level) { + return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; } -//# sourceMappingURL=client.js.map +//# sourceMappingURL=severity.js.map /***/ }), -/* 1666 */ +/* 1654 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "eventFromMessage": () => (/* binding */ eventFromMessage), -/* harmony export */ "eventFromUnknownInput": () => (/* binding */ eventFromUnknownInput), -/* harmony export */ "exceptionFromError": () => (/* binding */ exceptionFromError), -/* harmony export */ "parseStackFrames": () => (/* binding */ parseStackFrames) +/* harmony export */ "Http": () => (/* binding */ Http) /* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1660); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1647); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1611); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1609); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1656); +/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1655); -/** - * Extracts stack frames from the error.stack string - */ -function parseStackFrames(stackParser, error) { - return stackParser(error.stack || '', 1); -} + + +const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); /** - * Extracts stack frames from the error and builds a Sentry Exception + * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing + * http requests and attaches trace data when tracing is enabled via its `tracing` option. */ -function exceptionFromError(stackParser, error) { - const exception = { - type: error.name || error.constructor.name, - value: error.message, - }; +class Http { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Http';} - const frames = parseStackFrames(stackParser, error); - if (frames.length) { - exception.stacktrace = { frames }; + /** + * @inheritDoc + */ + __init() {this.name = Http.id;} + + /** + * @inheritDoc + */ + constructor(options = {}) {;Http.prototype.__init.call(this); + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; } - return exception; -} + /** + * @inheritDoc + */ + setupOnce( + _addGlobalEventProcessor, + setupOnceGetCurrentHub, + ) { + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !this._tracing) { + return; + } + + const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); + + // Do not auto-instrument for other instrumenter + if (clientOptions && clientOptions.instrumenter !== 'sentry') { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); + return; + } + + // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions + // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. + const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; + + const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); + + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpModule = __webpack_require__(80); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); + + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const httpsModule = __webpack_require__(81); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); + } + } +}Http.__initStatic(); + +// for ease of reading below /** - * Builds and Event from a Exception - * @hidden + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) + * + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * + * @returns A function which accepts the exiting handler and returns a wrapped handler */ -function eventFromUnknownInput(stackParser, exception, hint) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let ex = exception; - const providedMechanism = - hint && hint.data && (hint.data ).mechanism; - const mechanism = providedMechanism || { - handled: true, - type: 'generic', - }; +function _createWrappedRequestMethodFactory( + breadcrumbsEnabled, + tracingOptions, +) { + // We're caching results so we don't have to recompute regexp every time we create a request. + const createSpanUrlMap = {}; + const headersUrlMap = {}; - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isError)(exception)) { - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.isPlainObject)(exception)) { - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - const message = `Non-Error exception captured with keys: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractExceptionKeysForMessage)(exception)}`; + const shouldCreateSpan = (url) => { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { + return true; + } - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub)(); - const client = hub.getClient(); - const normalizeDepth = client && client.getOptions().normalizeDepth; - hub.configureScope(scope => { - scope.setExtra('__serialized__', (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.normalizeToSize)(exception, normalizeDepth)); - }); + if (createSpanUrlMap[url]) { + return createSpanUrlMap[url]; + } - ex = (hint && hint.syntheticException) || new Error(message); - (ex ).message = message; - } else { - // This handles when someone does: `throw "something awesome";` - // We use synthesized Error here so we can extract a (rough) stack trace. - ex = (hint && hint.syntheticException) || new Error(exception ); - (ex ).message = exception ; + createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); + + return createSpanUrlMap[url]; + }; + + const shouldAttachTraceData = (url) => { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { + return true; } - mechanism.synthetic = true; - } - const event = { - exception: { - values: [exceptionFromError(stackParser, ex )], - }, + if (headersUrlMap[url]) { + return headersUrlMap[url]; + } + + headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); + + return headersUrlMap[url]; }; - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionTypeValue)(event, undefined, undefined); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.addExceptionMechanism)(event, mechanism); + return function wrappedRequestMethodFactory(originalRequestMethod) { + return function wrappedMethod( ...args) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const httpModule = this; + + const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); + const requestOptions = requestArgs[0]; + const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); + + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method + if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { + return originalRequestMethod.apply(httpModule, requestArgs); + } + + let requestSpan; + let parentSpan; + + const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); + + if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { + parentSpan = scope.getSpan(); + + if (parentSpan) { + requestSpan = parentSpan.startChild({ + description: `${requestOptions.method || 'GET'} ${requestUrl}`, + op: 'http.client', + }); + + if (shouldAttachTraceData(requestUrl)) { + const sentryTraceHeader = requestSpan.toTraceparent(); + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( + `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, + ); + + requestOptions.headers = { + ...requestOptions.headers, + 'sentry-trace': sentryTraceHeader, + }; + + if (parentSpan.transaction) { + const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); + const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); + + let newBaggageHeaderField; + if (!requestOptions.headers || !requestOptions.headers.baggage) { + newBaggageHeaderField = sentryBaggageHeader; + } else if (!sentryBaggageHeader) { + newBaggageHeaderField = requestOptions.headers.baggage; + } else if (Array.isArray(requestOptions.headers.baggage)) { + newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; + } else { + // Type-cast explanation: + // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity + // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. + newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; + } + + requestOptions.headers = { + ...requestOptions.headers, + // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined + ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), + }; + } + } else { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( + `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, + ); + } + + const transaction = parentSpan.transaction; + if (transaction) { + transaction.metadata.propagations++; + } + } + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalRequestMethod + .apply(httpModule, requestArgs) + .once('response', function ( res) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', requestUrl, req, res); + } + if (requestSpan) { + if (res.statusCode) { + requestSpan.setHttpStatus(res.statusCode); + } + requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); + requestSpan.finish(); + } + }) + .once('error', function () { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const req = this; - return { - ...event, - event_id: hint && hint.event_id, + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', requestUrl, req); + } + if (requestSpan) { + requestSpan.setHttpStatus(500); + requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); + requestSpan.finish(); + } + }); + }; }; } /** - * Builds and Event from a Message - * @hidden + * Captures Breadcrumb based on provided request/response pair */ -function eventFromMessage( - stackParser, - message, - // eslint-disable-next-line deprecation/deprecation - level = 'info', - hint, - attachStacktrace, -) { - const event = { - event_id: hint && hint.event_id, - level, - message, - }; - - if (attachStacktrace && hint && hint.syntheticException) { - const frames = parseStackFrames(stackParser, hint.syntheticException); - if (frames.length) { - event.exception = { - values: [ - { - value: message, - stacktrace: { frames }, - }, - ], - }; - } +function addRequestBreadcrumb(event, url, req, res) { + if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { + return; } - return event; + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( + { + category: 'http', + data: { + method: req.method, + status_code: res && res.statusCode, + url, + }, + type: 'http', + }, + { + event, + request: req, + response: res, + }, + ); } -//# sourceMappingURL=eventbuilder.js.map +//# sourceMappingURL=http.js.map /***/ }), -/* 1667 */ +/* 1655 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BaseClient": () => (/* binding */ BaseClient) +/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), +/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), +/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), +/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), +/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1652); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1643); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1660); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1648); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1658); -/* harmony import */ var _api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1669); -/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1671); -/* harmony import */ var _integration_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1670); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1641); -/* harmony import */ var _session_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1642); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); +const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); +/** + * Checks whether given url points to Sentry server + * @param url url to verify + */ +function isSentryRequest(url) { + const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); + return dsn ? url.includes(dsn.host) : false; +} -const ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; +/** + * Assemble a URL to be used for breadcrumbs and spans. + * + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL + */ +function extractUrl(requestOptions) { + const protocol = requestOptions.protocol || ''; + const hostname = requestOptions.hostname || requestOptions.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + const port = + !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; + const path = requestOptions.path ? requestOptions.path : '/'; + + return `${protocol}//${hostname}${port}${path}`; +} /** - * Base implementation for all JavaScript SDK clients. + * Handle various edge cases in the span description (for spans representing http(s) requests). * - * Call the constructor with the corresponding options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. + * @param description current `description` property of the span representing the request + * @param requestOptions Configuration data for the request + * @param Request Request object * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. + * @returns The cleaned description + */ +function cleanSpanDescription( + description, + requestOptions, + request, +) { + // nothing to clean + if (!description) { + return description; + } + + // eslint-disable-next-line prefer-const + let [method, requestUrl] = description.split(' '); + + // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, + // we're likely dealing with an internal route and this doesn't apply) + if (requestOptions.host && !requestOptions.protocol) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes + requestUrl = extractUrl(requestOptions); + } + + // internal routes can end up starting with a triple slash rather than a single one + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { + requestUrl = requestUrl.slice(2); + } + + return `${method} ${requestUrl}`; +} + +// the node types are missing a few properties which node's `urlToOptions` function spits out + +/** + * Convert a URL object into a RequestOptions object. * - * Before sending an event, it is passed through - * {@link BaseClient._prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. + * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the + * RequestOptions type above. * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + */ +function urlToOptions(url) { + const options = { + protocol: url.protocol, + hostname: + typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: `${url.pathname || ''}${url.search || ''}`, + href: url.href, + }; + if (url.port !== '') { + options.port = Number(url.port); + } + if (url.username || url.password) { + options.auth = `${url.username}:${url.password}`; + } + return options; +} + +/** + * Normalize inputs to `http(s).request()` and `http(s).get()`. * - * @example - * class NodeClient extends BaseClient<NodeOptions> { - * public constructor(options: NodeOptions) { - * super(options); - * } + * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: + * [ RequestOptions | string | URL ], + * [ RequestOptions | string | URL, RequestCallback ], + * [ string | URL, RequestOptions ], and + * [ string | URL, RequestOptions, RequestCallback ]. * - * // ... - * } + * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is + * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact + * with the args in a standard way. + * + * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. */ -class BaseClient { - /** Options passed to the SDK. */ +function normalizeRequestArgs( + httpModule, + requestArgs, +) { + let callback, requestOptions; + + // pop off the callback, if there is one + if (typeof requestArgs[requestArgs.length - 1] === 'function') { + callback = requestArgs.pop() ; + } + + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); + } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { + requestOptions = urlToOptions(requestArgs[0]); + } else { + requestOptions = requestArgs[0]; + } + + // if the options were given separately from the URL, fold them in + if (requestArgs.length === 2) { + requestOptions = { ...requestOptions, ...requestArgs[1] }; + } + + // Figure out the protocol if it's currently missing + if (requestOptions.protocol === undefined) { + // Worst case we end up populating protocol with undefined, which it already is + /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ + + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, + // as it will always return `http`, even when using `https` module. + // + // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + requestOptions.protocol = + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); + } else { + requestOptions.protocol = + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ + } - /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */ + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } else { + return [requestOptions]; + } +} - /** Array of set up integrations. */ - __init() {this._integrations = {};} - /** Indicates whether this client's integrations have been set up. */ - __init2() {this._integrationsInitialized = false;} +//# sourceMappingURL=http.js.map - /** Number of calls being processed */ - __init3() {this._numProcessing = 0;} - /** Holds flushable */ - __init4() {this._outcomes = {};} +/***/ }), +/* 1656 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * Initializes this client instance. - * - * @param options Options for the client. - */ - constructor(options) {;BaseClient.prototype.__init.call(this);BaseClient.prototype.__init2.call(this);BaseClient.prototype.__init3.call(this);BaseClient.prototype.__init4.call(this); - this._options = options; - if (options.dsn) { - this._dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.makeDsn)(options.dsn); - const url = (0,_api_js__WEBPACK_IMPORTED_MODULE_1__.getEnvelopeEndpointWithUrlEncodedAuth)(this._dsn, options); - this._transport = options.transport({ - recordDroppedEvent: this.recordDroppedEvent.bind(this), - ...options.transportOptions, - url, - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('No DSN provided, client will not do anything.'); - } - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), +/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), +/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), +/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), +/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), +/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) +/* harmony export */ }); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1610); +/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - captureException(exception, hint, scope) { - // ensure we haven't captured this very object before - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(exception)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; - } - let eventId; - this._process( - this.eventFromException(exception, hint) - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); - return eventId; - } +const BAGGAGE_HEADER_NAME = 'baggage'; - /** - * @inheritDoc - */ - captureMessage( - message, - // eslint-disable-next-line deprecation/deprecation - level, - hint, - scope, - ) { - let eventId; +const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; - const promisedEvent = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPrimitive)(message) - ? this.eventFromMessage(String(message), level, hint) - : this.eventFromException(message, hint); +const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; - this._process( - promisedEvent - .then(event => this._captureEvent(event, hint, scope)) - .then(result => { - eventId = result; - }), - ); +/** + * Max length of a serialized baggage string + * + * https://www.w3.org/TR/baggage/#limits + */ +const MAX_BAGGAGE_STRING_LENGTH = 8192; - return eventId; +/** + * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values + * from it. + * + * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. + * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. + */ +function baggageHeaderToDynamicSamplingContext( + // Very liberal definition of what any incoming header might look like + baggageHeader, +) { + if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { + return undefined; } - /** - * @inheritDoc - */ - captureEvent(event, hint, scope) { - // ensure we haven't captured this very object before - if (hint && hint.originalException && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.checkOrSetAlreadyCaught)(hint.originalException)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(ALREADY_SEEN_ERROR); - return; + // Intermediary object to store baggage key value pairs of incoming baggage headers on. + // It is later used to read Sentry-DSC-values from. + let baggageObject = {}; + + if (Array.isArray(baggageHeader)) { + // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it + baggageObject = baggageHeader.reduce((acc, curr) => { + const currBaggageObject = baggageHeaderToObject(curr); + return { + ...acc, + ...currBaggageObject, + }; + }, {}); + } else { + // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but + // this is how we choose to handle it) + if (!baggageHeader) { + return undefined; } - let eventId; + baggageObject = baggageHeaderToObject(baggageHeader); + } - this._process( - this._captureEvent(event, hint, scope).then(result => { - eventId = result; - }), - ); + // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. + const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { + if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { + const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); + acc[nonPrefixedKey] = value; + } + return acc; + }, {}); - return eventId; + // Only return a dynamic sampling context object if there are keys in it. + // A keyless object means there were no sentry values on the header, which means that there is no DSC. + if (Object.keys(dynamicSamplingContext).length > 0) { + return dynamicSamplingContext ; + } else { + return undefined; } +} - /** - * @inheritDoc - */ - captureSession(session) { - if (!this._isEnabled()) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('SDK not enabled, will not capture session.'); - return; - } +/** + * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". + * + * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility + * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is + * `undefined` the function will return `undefined`. + * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` + * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. + */ +function dynamicSamplingContextToSentryBaggageHeader( + // this also takes undefined for convenience and bundle size in other places + dynamicSamplingContext, +) { + // Prefix all DSC keys with "sentry-" and put them into a new object + const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( + (acc, [dscKey, dscValue]) => { + if (dscValue) { + acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; + } + return acc; + }, + {}, + ); - if (!(typeof session.release === 'string')) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn('Discarded session because of missing or non-string release'); + return objectToBaggageHeader(sentryPrefixedDSC); +} + +/** + * Will parse a baggage header, which is a simple key-value map, into a flat object. + * + * @param baggageHeader The baggage header to parse. + * @returns a flat object containing all the key-value pairs from `baggageHeader`. + */ +function baggageHeaderToObject(baggageHeader) { + return baggageHeader + .split(',') + .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) + .reduce((acc, [key, value]) => { + acc[key] = value; + return acc; + }, {}); +} + +/** + * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. + * + * @param object The object to turn into a baggage header. + * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header + * is not spec compliant. + */ +function objectToBaggageHeader(object) { + if (Object.keys(object).length === 0) { + // An empty baggage header is not spec compliant: We return undefined. + return undefined; + } + + return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { + const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; + const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; + if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( + `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, + ); + return baggageHeader; } else { - this.sendSession(session); - // After sending, we set init false to indicate it's not the first occurrence - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { init: false }); + return newBaggageHeader; } - } + }, ''); +} + + +//# sourceMappingURL=baggage.js.map - /** - * @inheritDoc - */ - getDsn() { - return this._dsn; - } - /** - * @inheritDoc - */ - getOptions() { - return this._options; - } +/***/ }), +/* 1657 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - /** - * @inheritDoc - */ - getTransport() { - return this._transport; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); - /** - * @inheritDoc - */ - flush(timeout) { - const transport = this._transport; - if (transport) { - return this._isClientDoneProcessing(timeout).then(clientFinished => { - return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed); - }); - } else { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(true); - } - } - /** - * @inheritDoc - */ - close(timeout) { - return this.flush(timeout).then(result => { - this.getOptions().enabled = false; - return result; - }); - } - /** - * Sets up the integrations - */ - setupIntegrations() { - if (this._isEnabled() && !this._integrationsInitialized) { - this._integrations = (0,_integration_js__WEBPACK_IMPORTED_MODULE_7__.setupIntegrations)(this._options.integrations); - this._integrationsInitialized = true; - } - } +/** Global Exception handler */ +class OnUncaughtException { /** - * Gets an installed integration by its `id`. - * - * @returns The installed integration or `undefined` if no integration with that `id` was installed. + * @inheritDoc */ - getIntegrationById(integrationId) { - return this._integrations[integrationId]; - } + static __initStatic() {this.id = 'OnUncaughtException';} /** * @inheritDoc */ - getIntegration(integration) { - try { - return (this._integrations[integration.id] ) || null; - } catch (_oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); - return null; - } - } + __init() {this.name = OnUncaughtException.id;} /** * @inheritDoc */ - sendEvent(event, hint = {}) { - if (this._dsn) { - let env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createEventEnvelope)(event, this._dsn, this._options._metadata, this._options.tunnel); - - for (const attachment of hint.attachments || []) { - env = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.addItemToEnvelope)( - env, - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.createAttachmentEnvelopeItem)( - attachment, - this._options.transportOptions && this._options.transportOptions.textEncoder, - ), - ); - } + __init2() {this.handler = this._makeErrorHandler();} - this._sendEnvelope(env); - } - } + // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` /** * @inheritDoc */ - sendSession(session) { - if (this._dsn) { - const env = (0,_envelope_js__WEBPACK_IMPORTED_MODULE_8__.createSessionEnvelope)(session, this._dsn, this._options._metadata, this._options.tunnel); - this._sendEnvelope(env); - } + constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); + this._options = { + exitEvenIfOtherHandlersAreRegistered: true, + ...options, + }; } /** * @inheritDoc */ - recordDroppedEvent(reason, category, _event) { - // Note: we use `event` in replay, where we overwrite this hook. - - if (this._options.sendClientReports) { - // We want to track each category (error, transaction, session) separately - // but still keep the distinction between different type of outcomes. - // We could use nested maps, but it's much easier to read and type this way. - // A correct type for map-based implementation if we want to go that route - // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>` - // With typescript 4.1 we could even use template literal types - const key = `${reason}:${category}`; - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(`Adding outcome: "${key}"`); - - // The following works because undefined + 1 === NaN and NaN is falsy - this._outcomes[key] = this._outcomes[key] + 1 || 1; - } + setupOnce() { + global.process.on('uncaughtException', this.handler); } - /** Updates existing session based on the provided event */ - _updateSessionFromEvent(session, event) { - let crashed = false; - let errored = false; - const exceptions = event.exception && event.exception.values; + /** + * @hidden + */ + _makeErrorHandler() { + const timeout = 2000; + let caughtFirstError = false; + let caughtSecondError = false; + let calledFatalError = false; + let firstError; - if (exceptions) { - errored = true; + return (error) => { + let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); - for (const ex of exceptions) { - const mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } + if (this._options.onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = this._options.onFatalError; + } else if (client && client.getOptions().onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = client.getOptions().onFatalError ; } - } - // A session is updated and that session update is sent in only one of the two following scenarios: - // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update - // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update - const sessionNonTerminal = session.status === 'ok'; - const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); + // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not + // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust + // exit behaviour of the SDK accordingly: + // - If other listeners are attached, do not exit. + // - If the only listener attached is ours, exit. + const userProvidedListenersCount = global.process + .listeners('uncaughtException') + .reduce((acc, listener) => { + if ( + listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself + listener === this.handler // filter the handler we registered ourselves) + ) { + return acc; + } else { + return acc + 1; + } + }, 0); - if (shouldUpdateAndSend) { - (0,_session_js__WEBPACK_IMPORTED_MODULE_5__.updateSession)(session, { - ...(crashed && { status: 'crashed' }), - errors: session.errors || Number(errored || crashed), - }); - this.captureSession(session); - } - } + const processWouldExit = userProvidedListenersCount === 0; + const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; - /** - * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying - * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. - * - * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not - * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to - * `true`. - * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and - * `false` otherwise - */ - _isClientDoneProcessing(timeout) { - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.SyncPromise(resolve => { - let ticked = 0; - const tick = 1; + if (!caughtFirstError) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const interval = setInterval(() => { - if (this._numProcessing == 0) { - clearInterval(interval); - resolve(true); + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; + + if (hub.getIntegration(OnUncaughtException)) { + hub.withScope((scope) => { + scope.setLevel('fatal'); + hub.captureException(error, { + originalException: error, + data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, + }); + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } + }); } else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); + if (!calledFatalError && shouldApplyFatalHandlingLogic) { + calledFatalError = true; + onFatalError(error); + } + } + } else { + if (shouldApplyFatalHandlingLogic) { + if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( + 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', + ); + (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); + } else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(() => { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } else { + // it was probably case 2, our first error finished capturing while we waited, cool, do nothing + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc } } - }, tick); - }); - } - - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - _isEnabled() { - return this.getOptions().enabled !== false && this._dsn !== undefined; + } + }; } +} OnUncaughtException.__initStatic(); - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - _prepareEvent(event, hint, scope) { - const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = this.getOptions(); - const prepared = { - ...event, - event_id: event.event_id || hint.event_id || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.uuid4)(), - timestamp: event.timestamp || (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.dateTimestampInSeconds)(), - }; - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); +//# sourceMappingURL=onuncaughtexception.js.map - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - let finalScope = scope; - if (hint.captureContext) { - finalScope = _scope_js__WEBPACK_IMPORTED_MODULE_11__.Scope.clone(finalScope).update(hint.captureContext); - } - // We prepare the result here with a resolved Event. - let result = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.resolvedSyncPromise)(prepared); +/***/ }), +/* 1658 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - // - // We need to check for the existence of `finalScope.getAttachments` - // because `getAttachments` can be undefined if users are using an older version - // of `@sentry/core` that does not have the `getAttachments` method. - // See: https://github.com/getsentry/sentry-javascript/issues/5229 - if (finalScope && finalScope.getAttachments) { - // Collect attachments from the hint and scope - const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()]; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1614); - if (attachments.length) { - hint.attachments = attachments; - } - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - return result.then(evt => { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return this._normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); - } - return evt; - }); - } +const DEFAULT_SHUTDOWN_TIMEOUT = 2000; - /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event - */ - _normalizeEvent(event, depth, maxBreadth) { - if (!event) { - return null; - } +/** + * @hidden + */ +function logAndExitProcess(error) { + // eslint-disable-next-line no-console + console.error(error && error.stack ? error.stack : error); - const normalized = { - ...event, - ...(event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(b => ({ - ...b, - ...(b.data && { - data: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(b.data, depth, maxBreadth), - }), - })), - }), - ...(event.user && { - user: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.user, depth, maxBreadth), - }), - ...(event.contexts && { - contexts: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts, depth, maxBreadth), - }), - ...(event.extra && { - extra: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.extra, depth, maxBreadth), - }), - }; + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace && normalized.contexts) { - normalized.contexts.trace = event.contexts.trace; + if (client === undefined) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); + } - // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it - if (event.contexts.trace.data) { - normalized.contexts.trace.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(event.contexts.trace.data, depth, maxBreadth); + const options = client.getOptions(); + const timeout = + (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + client.close(timeout).then( + (result) => { + if (!result) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); } - } + global.process.exit(1); + }, + error => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); + }, + ); +} - // event.spans[].data may contain circular/dangerous data so we need to normalize it - if (event.spans) { - normalized.spans = event.spans.map(span => { - // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable - if (span.data) { - span.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.normalize)(span.data, depth, maxBreadth); - } - return span; - }); - } - return normalized; - } +//# sourceMappingURL=errorhandling.js.map - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - _applyClientOptions(event) { - const options = this.getOptions(); - const { environment, release, dist, maxValueLength = 250 } = options; - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; - } +/***/ }), +/* 1659 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - if (event.release === undefined && release !== undefined) { - event.release = release; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) +/* harmony export */ }); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1614); +/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; - } - if (event.message) { - event.message = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(event.message, maxValueLength); - } - const exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(exception.value, maxValueLength); - } - const request = event.request; - if (request && request.url) { - request.url = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_13__.truncate)(request.url, maxValueLength); - } - } +/** Global Promise Rejection handler */ +class OnUnhandledRejection { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'OnUnhandledRejection';} /** - * This function adds all used integrations to the SDK info in the event. - * @param event The event that will be filled with all integrations. + * @inheritDoc */ - _applyIntegrationsMetadata(event) { - const integrationsArray = Object.keys(this._integrations); - if (integrationsArray.length > 0) { - event.sdk = event.sdk || {}; - event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationsArray]; - } - } + __init() {this.name = OnUnhandledRejection.id;} /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope + * @inheritDoc */ - _captureEvent(event, hint = {}, scope) { - return this._processEvent(event, hint, scope).then( - finalEvent => { - return finalEvent.event_id; - }, - reason => { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for - // control flow, log just the message (no stack) as a log-level log. - const sentryError = reason ; - if (sentryError.logLevel === 'log') { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.log(sentryError.message); - } else { - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn(sentryError); - } - } - return undefined; - }, - ); + constructor( + _options + + = { mode: 'warn' }, + ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} + + /** + * @inheritDoc + */ + setupOnce() { + global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + } + + /** + * Send an exception with reason + * @param reason string + * @param promise promise + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any + sendUnhandledPromise(reason, promise) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); + if (hub.getIntegration(OnUnhandledRejection)) { + hub.withScope((scope) => { + scope.setExtra('unhandledPromiseRejection', true); + hub.captureException(reason, { + originalException: promise, + data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, + }); + }); + } + this._handleRejection(reason); } /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + * Handler for `mode` option */ - _processEvent(event, hint, scope) { - const options = this.getOptions(); - const { sampleRate } = options; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _handleRejection(reason) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + const rejectionWarning = + 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; - if (!this._isEnabled()) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)(new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('SDK not enabled, will not capture event.', 'log')); + /* eslint-disable no-console */ + if (this._options.mode === 'warn') { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); + } else if (this._options.mode === 'strict') { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { + console.warn(rejectionWarning); + }); + (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); } + /* eslint-enable no-console */ + } +} OnUnhandledRejection.__initStatic(); - const isTransaction = event.type === 'transaction'; - const beforeSendProcessorName = isTransaction ? 'beforeSendTransaction' : 'beforeSend'; - const beforeSendProcessor = options[beforeSendProcessorName]; - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - this.recordDroppedEvent('sample_rate', 'error', event); - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_6__.rejectedSyncPromise)( - new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, - 'log', - ), - ); - } +//# sourceMappingURL=onunhandledrejection.js.map - return this._prepareEvent(event, hint, scope) - .then(prepared => { - if (prepared === null) { - this.recordDroppedEvent('event_processor', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError('An event processor returned `null`, will not send event.', 'log'); - } - const isInternalException = hint.data && (hint.data ).__sentry__ === true; - if (isInternalException || !beforeSendProcessor) { - return prepared; - } +/***/ }), +/* 1660 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1602); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1601); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1613); +/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1627); +/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1661); - const beforeSendResult = beforeSendProcessor(prepared, hint); - return _validateBeforeSendResult(beforeSendResult, beforeSendProcessorName); - }) - .then(processedEvent => { - if (processedEvent === null) { - this.recordDroppedEvent('before_send', event.type || 'error', event); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` returned \`null\`, will not send event.`, 'log'); - } - const session = scope && scope.getSession(); - if (!isTransaction && session) { - this._updateSessionFromEvent(session, processedEvent); - } - // None of the Sentry built event processor will update transaction name, - // so if the transaction name has been changed by an event processor, we know - // it has to come from custom event processor added by a user - const transactionInfo = processedEvent.transaction_info; - if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { - const source = 'custom'; - processedEvent.transaction_info = { - ...transactionInfo, - source, - changes: [ - ...transactionInfo.changes, - { - source, - // use the same timestamp as the processed event. - timestamp: processedEvent.timestamp , - propagations: transactionInfo.propagations, - }, - ], - }; - } - this.sendEvent(processedEvent, hint); - return processedEvent; - }) - .then(null, reason => { - if (reason instanceof _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError) { - throw reason; - } - this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason , - }); - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError( - `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, - ); - }); - } +const DEFAULT_KEY = 'cause'; +const DEFAULT_LIMIT = 5; + +/** Adds SDK info to an event. */ +class LinkedErrors { /** - * Occupies the client with processing and event + * @inheritDoc */ - _process(promise) { - this._numProcessing++; - void promise.then( - value => { - this._numProcessing--; - return value; - }, - reason => { - this._numProcessing--; - return reason; - }, - ); - } + static __initStatic() {this.id = 'LinkedErrors';} /** - * @inheritdoc + * @inheritDoc */ - _sendEnvelope(envelope) { - if (this._transport && this._dsn) { - this._transport.send(envelope).then(null, reason => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Error while sending event:', reason); - }); - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.error('Transport disabled'); - } + __init() {this.name = LinkedErrors.id;} + + /** + * @inheritDoc + */ + + /** + * @inheritDoc + */ + + /** + * @inheritDoc + */ + constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); + this._key = options.key || DEFAULT_KEY; + this._limit = options.limit || DEFAULT_LIMIT; } /** - * Clears outcomes on this client and returns them. + * @inheritDoc */ - _clearOutcomes() { - const outcomes = this._outcomes; - this._outcomes = {}; - return Object.keys(outcomes).map(key => { - const [reason, category] = key.split(':') ; - return { - reason, - category, - quantity: outcomes[key], - }; + setupOnce() { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); + const self = hub.getIntegration(LinkedErrors); + const client = hub.getClient(); + if (client && self && self._handler && typeof self._handler === 'function') { + await self._handler(client.getOptions().stackParser, event, hint); + } + return event; }); } /** * @inheritDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + _handler(stackParser, event, hint) { + if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { + return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); + } -} + return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { + void this._walkErrorTree(stackParser, hint.originalException , this._key) + .then((linkedErrors) => { + if (event && event.exception && event.exception.values) { + event.exception.values = [...linkedErrors, ...event.exception.values]; + } + resolve(event); + }) + .then(null, () => { + resolve(event); + }); + }); + } -/** - * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so. - */ -function _validateBeforeSendResult( - beforeSendResult, - beforeSendProcessorName, -) { - const invalidValueError = `\`${beforeSendProcessorName}\` must return \`null\` or a valid event.`; - if ((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isThenable)(beforeSendResult)) { - return beforeSendResult.then( - event => { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(event) && event !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); - } - return event; - }, - e => { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(`\`${beforeSendProcessorName}\` rejected with ${e}`); - }, - ); - } else if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isPlainObject)(beforeSendResult) && beforeSendResult !== null) { - throw new _sentry_utils__WEBPACK_IMPORTED_MODULE_14__.SentryError(invalidValueError); + /** + * @inheritDoc + */ + async _walkErrorTree( + stackParser, + error, + key, + stack = [], + ) { + if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { + return Promise.resolve(stack); + } + + const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); + + // If the ContextLines integration is enabled, we add source code context to linked errors + // because we can't guarantee the order that integrations are run. + const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); + if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { + await contextLines.addSourceContextToFrames(exception.stacktrace.frames); + } + + return new Promise((resolve, reject) => { + void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) + .then(resolve) + .then(null, () => { + reject(); + }); + }); } - return beforeSendResult; -} +}LinkedErrors.__initStatic(); -//# sourceMappingURL=baseclient.js.map +//# sourceMappingURL=linkederrors.js.map /***/ }), -/* 1668 */ +/* 1661 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "dsnFromString": () => (/* binding */ dsnFromString), -/* harmony export */ "dsnToString": () => (/* binding */ dsnToString), -/* harmony export */ "makeDsn": () => (/* binding */ makeDsn) +/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), +/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) /* harmony export */ }); -/* harmony import */ var _error_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1658); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1608); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1662); +/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); -/** Regular expression used to parse a Dsn. */ -const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; -function isValidProtocol(protocol) { - return protocol === 'http' || protocol === 'https'; + + +const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); +const DEFAULT_LINES_OF_CONTEXT = 7; + +// TODO: Replace with promisify when minimum supported node >= v8 +function readTextFileAsync(path) { + return new Promise((resolve, reject) => { + (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { + if (err) reject(err); + else resolve(data); + }); + }); } /** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. + * Resets the file cache. Exists for testing purposes. + * @hidden */ -function dsnToString(dsn, withPassword = false) { - const { host, path, pass, port, projectId, protocol, publicKey } = dsn; - return ( - `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` + - `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}` - ); +function resetFileContentCache() { + FILE_CONTENT_CACHE.clear(); } -/** - * Parses a Dsn from a given string. - * - * @param str A Dsn as string - * @returns Dsn as DsnComponents - */ -function dsnFromString(str) { - const match = DSN_REGEX.exec(str); +/** Add node modules / packages to the event */ +class ContextLines { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'ContextLines';} - if (!match) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${str}`); - } + /** + * @inheritDoc + */ + __init() {this.name = ContextLines.id;} - const [protocol, publicKey, pass = '', host, port = '', lastPath] = match.slice(1); - let path = ''; - let projectId = lastPath; + constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} - const split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop() ; + /** Get's the number of context lines to add */ + get _contextLines() { + return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; } - if (projectId) { - const projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor) { + addGlobalEventProcessor(event => this.addSourceContext(event)); } - return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey }); -} - -function dsnFromComponents(components) { - return { - protocol: components.protocol, - publicKey: components.publicKey || '', - pass: components.pass || '', - host: components.host, - port: components.port || '', - path: components.path || '', - projectId: components.projectId, - }; -} + /** Processes an event and adds context lines */ + async addSourceContext(event) { + if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { + for (const exception of event.exception.values) { + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { + await this.addSourceContextToFrames(exception.stacktrace.frames); + } + } + } -function validateDsn(dsn) { - if (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - return; + return event; } - const { port, projectId, protocol } = dsn; + /** Adds context lines to frames */ + async addSourceContextToFrames(frames) { + const contextLines = this._contextLines; - const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId']; - requiredComponents.forEach(component => { - if (!dsn[component]) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: ${component} missing`); - } - }); + for (const frame of frames) { + // Only add context if we have a filename and it hasn't already been added + if (frame.filename && frame.context_line === undefined) { + const sourceFile = await _readSourceFile(frame.filename); - if (!projectId.match(/^\d+$/)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); + if (sourceFile) { + try { + const lines = sourceFile.split('\n'); + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); + } catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + } + } } +}ContextLines.__initStatic(); - if (!isValidProtocol(protocol)) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); +/** + * Reads file contents and caches them in a global LRU cache. + * + * @param filename filepath to read content from. + */ +async function _readSourceFile(filename) { + const cachedFile = FILE_CONTENT_CACHE.get(filename); + // We have a cache hit + if (cachedFile !== undefined) { + return cachedFile; } - if (port && isNaN(parseInt(port, 10))) { - throw new _error_js__WEBPACK_IMPORTED_MODULE_0__.SentryError(`Invalid Sentry Dsn: Invalid port ${port}`); + let content = null; + try { + content = await readTextFileAsync(filename); + } catch (_) { + // } - return true; -} - -/** The Sentry Dsn, identifying a Sentry instance and project. */ -function makeDsn(from) { - const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from); - validateDsn(components); - return components; + FILE_CONTENT_CACHE.set(filename, content); + return content; } -//# sourceMappingURL=dsn.js.map +//# sourceMappingURL=contextlines.js.map /***/ }), -/* 1669 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getEnvelopeEndpointWithUrlEncodedAuth": () => (/* binding */ getEnvelopeEndpointWithUrlEncodedAuth), -/* harmony export */ "getReportDialogEndpoint": () => (/* binding */ getReportDialogEndpoint) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1668); +/* 1662 */ +/***/ (function(module, exports, __webpack_require__) { +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** + * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most + * recently used items while discarding least recently used items when its limit + * is reached. + * + * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/> + * See README.md for details. + * + * Illustration of the design: + * + * entry entry entry entry + * ______ ______ ______ ______ + * | head |.newer => | |.newer => | |.newer => | tail | + * | A | | B | | C | | D | + * |______| <= older.|______| <= older.|______| <= older.|______| + * + * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added + */ +(function(g,f){ + const e = true ? exports : 0; + f(e); + if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } +})(this, function(exports) { -const SENTRY_API_VERSION = '7'; +const NEWER = Symbol('newer'); +const OLDER = Symbol('older'); -/** Returns the prefix to construct Sentry ingestion API endpoints. */ -function getBaseApiEndpoint(dsn) { - const protocol = dsn.protocol ? `${dsn.protocol}:` : ''; - const port = dsn.port ? `:${dsn.port}` : ''; - return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`; -} +function LRUMap(limit, entries) { + if (typeof limit !== 'number') { + // called as (entries) + entries = limit; + limit = 0; + } -/** Returns the ingest API endpoint for target. */ -function _getIngestEndpoint(dsn) { - return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; -} + this.size = 0; + this.limit = limit; + this.oldest = this.newest = undefined; + this._keymap = new Map(); -/** Returns a URL-encoded string with auth config suitable for a query string. */ -function _encodedAuth(dsn, sdkInfo) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.urlEncode)({ - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.publicKey, - sentry_version: SENTRY_API_VERSION, - ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }), - }); + if (entries) { + this.assign(entries); + if (limit < 1) { + this.limit = this.size; + } + } } -/** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ -function getEnvelopeEndpointWithUrlEncodedAuth( - dsn, - // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below - // options: ClientOptions = {} as ClientOptions, - tunnelOrOptions = {} , -) { - // TODO (v8): Use this code instead - // const { tunnel, _metadata = {} } = options; - // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`; - - const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel; - const sdkInfo = - typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk; +exports.LRUMap = LRUMap; - return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; +function Entry(key, value) { + this.key = key; + this.value = value; + this[NEWER] = undefined; + this[OLDER] = undefined; } -/** Returns the url to the report dialog endpoint. */ -function getReportDialogEndpoint( - dsnLike, - dialogOptions - -, -) { - const dsn = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.makeDsn)(dsnLike); - const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`; - let encodedOptions = `dsn=${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.dsnToString)(dsn)}`; - for (const key in dialogOptions) { - if (key === 'dsn') { - continue; +LRUMap.prototype._markEntryAsUsed = function(entry) { + if (entry === this.newest) { + // Already the most recenlty used entry, so no need to update the list + return; + } + // HEAD--------------TAIL + // <.older .newer> + // <--- add direction -- + // A B C <D> E + if (entry[NEWER]) { + if (entry === this.oldest) { + this.oldest = entry[NEWER]; } + entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. + } + if (entry[OLDER]) { + entry[OLDER][NEWER] = entry[NEWER]; // C. --> E + } + entry[NEWER] = undefined; // D --x + entry[OLDER] = this.newest; // D. --> E + if (this.newest) { + this.newest[NEWER] = entry; // E. <-- D + } + this.newest = entry; +}; - if (key === 'user') { - const user = dialogOptions.user; - if (!user) { - continue; - } - if (user.name) { - encodedOptions += `&name=${encodeURIComponent(user.name)}`; - } - if (user.email) { - encodedOptions += `&email=${encodeURIComponent(user.email)}`; - } +LRUMap.prototype.assign = function(entries) { + let entry, limit = this.limit || Number.MAX_VALUE; + this._keymap.clear(); + let it = entries[Symbol.iterator](); + for (let itv = it.next(); !itv.done; itv = it.next()) { + let e = new Entry(itv.value[0], itv.value[1]); + this._keymap.set(e.key, e); + if (!entry) { + this.oldest = e; } else { - encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`; + entry[NEWER] = e; + e[OLDER] = entry; + } + entry = e; + if (limit-- == 0) { + throw new Error('overflow'); } } + this.newest = entry; + this.size = this._keymap.size; +}; - return `${endpoint}?${encodedOptions}`; -} - - -//# sourceMappingURL=api.js.map - - -/***/ }), -/* 1670 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getIntegrationsToSetup": () => (/* binding */ getIntegrationsToSetup), -/* harmony export */ "installedIntegrations": () => (/* binding */ installedIntegrations), -/* harmony export */ "setupIntegrations": () => (/* binding */ setupIntegrations) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1640); -/* harmony import */ var _scope_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1641); +LRUMap.prototype.get = function(key) { + // First, find our cache entry + var entry = this._keymap.get(key); + if (!entry) return; // Not cached. Sorry. + // As <key> was found in the cache, register it as being requested recently + this._markEntryAsUsed(entry); + return entry.value; +}; +LRUMap.prototype.set = function(key, value) { + var entry = this._keymap.get(key); + if (entry) { + // update existing + entry.value = value; + this._markEntryAsUsed(entry); + return this; + } + // new entry + this._keymap.set(key, (entry = new Entry(key, value))); -const installedIntegrations = []; + if (this.newest) { + // link previous tail to the new tail (entry) + this.newest[NEWER] = entry; + entry[OLDER] = this.newest; + } else { + // we're first in -- yay + this.oldest = entry; + } -/** Map of integrations assigned to a client */ + // add new entry to the end of the linked list -- it's now the freshest entry. + this.newest = entry; + ++this.size; + if (this.size > this.limit) { + // we hit the limit -- remove the head + this.shift(); + } -/** - * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to - * preseve the order of integrations in the array. - * - * @private - */ -function filterDuplicates(integrations) { - const integrationsByName = {}; + return this; +}; - integrations.forEach(currentInstance => { - const { name } = currentInstance; +LRUMap.prototype.shift = function() { + // todo: handle special case when limit == 1 + var entry = this.oldest; + if (entry) { + if (this.oldest[NEWER]) { + // advance the list + this.oldest = this.oldest[NEWER]; + this.oldest[OLDER] = undefined; + } else { + // the cache is exhausted + this.oldest = undefined; + this.newest = undefined; + } + // Remove last strong reference to <entry> and remove links from the purged + // entry being returned: + entry[NEWER] = entry[OLDER] = undefined; + this._keymap.delete(entry.key); + --this.size; + return [entry.key, entry.value]; + } +}; - const existingInstance = integrationsByName[name]; +// ---------------------------------------------------------------------------- +// Following code is optional and can be removed without breaking the core +// functionality. - // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a - // default instance to overwrite an existing user instance - if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { - return; - } +LRUMap.prototype.find = function(key) { + let e = this._keymap.get(key); + return e ? e.value : undefined; +}; - integrationsByName[name] = currentInstance; - }); +LRUMap.prototype.has = function(key) { + return this._keymap.has(key); +}; - return Object.values(integrationsByName); -} +LRUMap.prototype['delete'] = function(key) { + var entry = this._keymap.get(key); + if (!entry) return; + this._keymap.delete(entry.key); + if (entry[NEWER] && entry[OLDER]) { + // relink the older entry with the newer entry + entry[OLDER][NEWER] = entry[NEWER]; + entry[NEWER][OLDER] = entry[OLDER]; + } else if (entry[NEWER]) { + // remove the link to us + entry[NEWER][OLDER] = undefined; + // link the newer entry to head + this.oldest = entry[NEWER]; + } else if (entry[OLDER]) { + // remove the link to us + entry[OLDER][NEWER] = undefined; + // link the newer entry to head + this.newest = entry[OLDER]; + } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { + this.oldest = this.newest = undefined; + } -/** Gets integrations to install */ -function getIntegrationsToSetup(options) { - const defaultIntegrations = options.defaultIntegrations || []; - const userIntegrations = options.integrations; + this.size--; + return entry.value; +}; - // We flag default instances, so that later we can tell them apart from any user-created instances of the same class - defaultIntegrations.forEach(integration => { - integration.isDefaultInstance = true; - }); +LRUMap.prototype.clear = function() { + // Not clearing links should be safe, as we don't expose live links to user + this.oldest = this.newest = undefined; + this.size = 0; + this._keymap.clear(); +}; - let integrations; - if (Array.isArray(userIntegrations)) { - integrations = [...defaultIntegrations, ...userIntegrations]; - } else if (typeof userIntegrations === 'function') { - integrations = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.arrayify)(userIntegrations(defaultIntegrations)); +function EntryIterator(oldestEntry) { this.entry = oldestEntry; } +EntryIterator.prototype[Symbol.iterator] = function() { return this; } +EntryIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: [ent.key, ent.value] }; } else { - integrations = defaultIntegrations; + return { done: true, value: undefined }; } +}; - const finalIntegrations = filterDuplicates(integrations); - // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or - // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event - // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore - // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array. - const debugIndex = finalIntegrations.findIndex(integration => integration.name === 'Debug'); - if (debugIndex !== -1) { - const [debugInstance] = finalIntegrations.splice(debugIndex, 1); - finalIntegrations.push(debugInstance); +function KeyIterator(oldestEntry) { this.entry = oldestEntry; } +KeyIterator.prototype[Symbol.iterator] = function() { return this; } +KeyIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.key }; + } else { + return { done: true, value: undefined }; } +}; - return finalIntegrations; -} +function ValueIterator(oldestEntry) { this.entry = oldestEntry; } +ValueIterator.prototype[Symbol.iterator] = function() { return this; } +ValueIterator.prototype.next = function() { + let ent = this.entry; + if (ent) { + this.entry = ent[NEWER]; + return { done: false, value: ent.value }; + } else { + return { done: true, value: undefined }; + } +}; -/** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations - */ -function setupIntegrations(integrations) { - const integrationIndex = {}; - integrations.forEach(integration => { - integrationIndex[integration.name] = integration; +LRUMap.prototype.keys = function() { + return new KeyIterator(this.oldest); +}; - if (installedIntegrations.indexOf(integration.name) === -1) { - integration.setupOnce(_scope_js__WEBPACK_IMPORTED_MODULE_1__.addGlobalEventProcessor, _hub_js__WEBPACK_IMPORTED_MODULE_2__.getCurrentHub); - installedIntegrations.push(integration.name); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log(`Integration installed: ${integration.name}`); - } - }); +LRUMap.prototype.values = function() { + return new ValueIterator(this.oldest); +}; - return integrationIndex; -} +LRUMap.prototype.entries = function() { + return this; +}; + +LRUMap.prototype[Symbol.iterator] = function() { + return new EntryIterator(this.oldest); +}; +LRUMap.prototype.forEach = function(fun, thisObj) { + if (typeof thisObj !== 'object') { + thisObj = this; + } + let entry = this.oldest; + while (entry) { + fun.call(thisObj, entry.value, entry.key, this); + entry = entry[NEWER]; + } +}; -//# sourceMappingURL=integration.js.map +/** Returns a JSON (array) representation */ +LRUMap.prototype.toJSON = function() { + var s = new Array(this.size), i = 0, entry = this.oldest; + while (entry) { + s[i++] = { key: entry.key, value: entry.value }; + entry = entry[NEWER]; + } + return s; +}; + +/** Returns a String representation */ +LRUMap.prototype.toString = function() { + var s = '', entry = this.oldest; + while (entry) { + s += String(entry.key)+':'+entry.value; + entry = entry[NEWER]; + if (entry) { + s += ' < '; + } + } + return s; +}; + +}); /***/ }), -/* 1671 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1663 */ +/***/ ((module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createEventEnvelope": () => (/* binding */ createEventEnvelope), -/* harmony export */ "createSessionEnvelope": () => (/* binding */ createSessionEnvelope) +/* harmony export */ "Modules": () => (/* binding */ Modules) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1659); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); -/** Extract sdk info from from the API metadata */ -function getSdkMetadataForEnvelopeHeader(metadata) { - if (!metadata || !metadata.sdk) { - return; - } - const { name, version } = metadata.sdk; - return { name, version }; -} -/** - * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. - * Merge with existing data if any. - **/ -function enhanceEventWithSdkInfo(event, sdkInfo) { - if (!sdkInfo) { - return event; +let moduleCache; + +/** Extract information about paths */ +function getPaths() { + try { + return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; + } catch (e) { + return []; } - event.sdk = event.sdk || {}; - event.sdk.name = event.sdk.name || sdkInfo.name; - event.sdk.version = event.sdk.version || sdkInfo.version; - event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])]; - event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])]; - return event; } -/** Creates an envelope from a Session */ -function createSessionEnvelope( - session, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const envelopeHeaders = { - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - }; +/** Extract information about package.json modules */ +function collectModules() - const envelopeItem = - 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session]; + { + const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; + const paths = getPaths(); + const infos - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [envelopeItem]); -} + = {}; + const seen -/** - * Create an Envelope from an event. - */ -function createEventEnvelope( - event, - dsn, - metadata, - tunnel, -) { - const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); - const eventType = event.type || 'event'; + = {}; - enhanceEventWithSdkInfo(event, metadata && metadata.sdk); + paths.forEach(path => { + let dir = path; - const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); + /** Traverse directories upward in the search of package.json file */ + const updir = () => { + const orig = dir; + dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); - // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to - // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may - // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid - // of this `delete`, lest we miss putting it back in the next time the property is in use.) - delete event.sdkProcessingMetadata; + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } - const eventItem = [{ type: eventType }, event]; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.createEnvelope)(envelopeHeaders, [eventItem]); + const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); + seen[orig] = true; + + if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { + return updir(); + } + + try { + const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) + +; + infos[info.name] = info.version; + } catch (_oO) { + // no-empty + } + }; + + updir(); + }); + + return infos; } -function createEventEnvelopeHeaders( - event, - sdkInfo, - tunnel, - dsn, -) { - const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; +/** Add node modules / packages to the event */ +class Modules {constructor() { Modules.prototype.__init.call(this); } + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Modules';} + + /** + * @inheritDoc + */ + __init() {this.name = Modules.id;} + + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + addGlobalEventProcessor(event => { + if (!getCurrentHub().getIntegration(Modules)) { + return event; + } + return { + ...event, + modules: { + ...event.modules, + ...this._getModules(), + }, + }; + }); + } - return { - event_id: event.event_id , - sent_at: new Date().toISOString(), - ...(sdkInfo && { sdk: sdkInfo }), - ...(!!tunnel && { dsn: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dsnToString)(dsn) }), - ...(event.type === 'transaction' && - dynamicSamplingContext && { - trace: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.dropUndefinedKeys)({ ...dynamicSamplingContext }), - }), - }; -} + /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ + _getModules() { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; + } +} Modules.__initStatic(); -//# sourceMappingURL=envelope.js.map +//# sourceMappingURL=modules.js.map /***/ }), -/* 1672 */ +/* 1664 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SessionFlusher": () => (/* binding */ SessionFlusher) +/* harmony export */ "Context": () => (/* binding */ Context), +/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), +/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), +/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) /* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(846); +/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); +/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); -/** - * @inheritdoc - */ -class SessionFlusher { - __init() {this.flushTimeout = 60;} - __init2() {this._pendingAggregates = {};} - __init3() {this._isEnabled = true;} - constructor(client, attrs) {;SessionFlusher.prototype.__init.call(this);SessionFlusher.prototype.__init2.call(this);SessionFlusher.prototype.__init3.call(this); - this._client = client; - // Call to setInterval, so that flush is called every 60 seconds - this._intervalId = setInterval(() => this.flush(), this.flushTimeout * 1000); - this._sessionAttrs = attrs; + + +// TODO: Required until we drop support for Node v8 +const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); +const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); + +/** Add node modules / packages to the event */ +class Context { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'Context';} + + /** + * @inheritDoc + */ + __init() {this.name = Context.id;} + + /** + * Caches context so it's only evaluated once + */ + + constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); + // } - /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSession` */ - flush() { - const sessionAggregates = this.getSessionAggregates(); - if (sessionAggregates.aggregates.length === 0) { - return; - } - this._pendingAggregates = {}; - this._client.sendSession(sessionAggregates); + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor) { + addGlobalEventProcessor(event => this.addContext(event)); } - /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ - getSessionAggregates() { - const aggregates = Object.keys(this._pendingAggregates).map((key) => { - return this._pendingAggregates[parseInt(key)]; - }); + /** Processes an event and adds context */ + async addContext(event) { + if (this._cachedContext === undefined) { + this._cachedContext = this._getContexts(); + } - const sessionAggregates = { - attrs: this._sessionAttrs, - aggregates, + const updatedContext = this._updateContext(await this._cachedContext); + + event.contexts = { + ...event.contexts, + app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, + os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, + device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, + culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, }; - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dropUndefinedKeys)(sessionAggregates); - } - /** JSDoc */ - close() { - clearInterval(this._intervalId); - this._isEnabled = false; - this.flush(); + return event; } /** - * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then - * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to - * `_incrementSessionStatusCount` along with the start date + * Updates the context with dynamic values that can change */ - incrementSessionStatusCount() { - if (!this._isEnabled) { - return; + _updateContext(contexts) { + // Only update properties if they exist + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { + contexts.app.app_memory = process.memoryUsage().rss; } - const scope = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getScope(); - const requestSession = scope && scope.getRequestSession(); - if (requestSession && requestSession.status) { - this._incrementSessionStatusCount(requestSession.status, new Date()); - // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in - // case captureRequestSession is called more than once to prevent double count - if (scope) { - scope.setRequestSession(undefined); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { + contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); } + + return contexts; } /** - * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of - * the session received + * Gets the contexts for the current environment */ - _incrementSessionStatusCount(status, date) { - // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys - const sessionStartedTrunc = new Date(date).setSeconds(0, 0); - this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + async _getContexts() { + const contexts = {}; - // corresponds to aggregated sessions in one specific minute bucket - // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} - const aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; - if (!aggregationCounts.started) { - aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); + if (this._options.os) { + contexts.os = await getOsContext(); } - switch (status) { - case 'errored': - aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; - return aggregationCounts.errored; - case 'ok': - aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; - return aggregationCounts.exited; - default: - aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; - return aggregationCounts.crashed; + if (this._options.app) { + contexts.app = getAppContext(); } - } -} - - -//# sourceMappingURL=sessionflusher.js.map + if (this._options.device) { + contexts.device = getDeviceContext(this._options.device); + } -/***/ }), -/* 1673 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + if (this._options.culture) { + const culture = getCultureContext(); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_0__.makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1674); + if (culture) { + contexts.culture = culture; + } + } + return contexts; + } +}Context.__initStatic(); -; -//# sourceMappingURL=index.js.map +/** + * Returns the operating system context. + * + * Based on the current platform, this uses a different strategy to provide the + * most accurate OS information. Since this might involve spawning subprocesses + * or accessing the file system, this should only be executed lazily and cached. + * + * - On macOS (Darwin), this will execute the `sw_vers` utility. The context + * has a `name`, `version`, `build` and `kernel_version` set. + * - On Linux, this will try to load a distribution release from `/etc` and set + * the `name`, `version` and `kernel_version` fields. + * - On all other platforms, only a `name` and `version` will be returned. Note + * that `version` might actually be the kernel version. + */ +async function getOsContext() { + const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); + switch (platformId) { + case 'darwin': + return getDarwinInfo(); + case 'linux': + return getLinuxInfo(); + default: + return { + name: PLATFORM_NAMES[platformId] || platformId, + version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + }; + } +} +function getCultureContext() { + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (typeof (process.versions ).icu !== 'string') { + // Node was built without ICU support + return; + } -/***/ }), -/* 1674 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Check that node was built with full Intl support. Its possible it was built without support for non-English + // locales which will make resolvedOptions inaccurate + // + // https://nodejs.org/api/intl.html#detecting-internationalization-support + const january = new Date(9e8); + const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); + if (spanish.format(january) === 'enero') { + const options = Intl.DateTimeFormat().resolvedOptions(); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "makeNodeTransport": () => (/* binding */ makeNodeTransport) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1688); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1656); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82); -/* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(stream__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(83); -/* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(zlib__WEBPACK_IMPORTED_MODULE_4__); + return { + locale: options.locale, + timezone: options.timeZone, + }; + } + } catch (err) { + // + } + return; +} +function getAppContext() { + const app_memory = process.memoryUsage().rss; + const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); + return { app_start_time, app_memory }; +} +/** + * Gets device information from os + */ +function getDeviceContext(deviceOpt) { + const device = {}; + // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). + // Hence, we only set boot time, if we get a valid uptime value. + // @see https://github.com/getsentry/sentry-javascript/issues/5856 + const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); + if (typeof uptime === 'number') { + device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); + } + device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); + if (deviceOpt === true || deviceOpt.memory) { + device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); + device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); + } -// Estimated maximum size for reasonable standalone event -const GZIP_THRESHOLD = 1024 * 32; + if (deviceOpt === true || deviceOpt.cpu) { + const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); + if (cpuInfo && cpuInfo.length) { + const firstCpu = cpuInfo[0]; -/** - * Gets a stream from a Uint8Array or string - * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0 - */ -function streamFromBody(body) { - return new stream__WEBPACK_IMPORTED_MODULE_2__.Readable({ - read() { - this.push(body); - this.push(null); - }, - }); + device.processor_count = cpuInfo.length; + device.cpu_description = firstCpu.model; + device.processor_frequency = firstCpu.speed; + } + } + + return device; } -/** - * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry. - */ -function makeNodeTransport(options) { - const urlSegments = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - const isHttps = urlSegments.protocol === 'https:'; +/** Mapping of Node's platform names to actual OS names. */ +const PLATFORM_NAMES = { + aix: 'IBM AIX', + freebsd: 'FreeBSD', + openbsd: 'OpenBSD', + sunos: 'SunOS', + win32: 'Windows', +}; - // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy` - // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy` - const proxy = applyNoProxyOption( - urlSegments, - options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy, - ); +/** Linux version file to check for a distribution. */ - const nativeHttpModule = isHttps ? https__WEBPACK_IMPORTED_MODULE_1__ : http__WEBPACK_IMPORTED_MODULE_0__; - const keepAlive = options.keepAlive === undefined ? false : options.keepAlive; +/** Mapping of linux release files located in /etc to distributions. */ +const LINUX_DISTROS = [ + { name: 'fedora-release', distros: ['Fedora'] }, + { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, + { name: 'redhat_version', distros: ['Red Hat Linux'] }, + { name: 'SuSE-release', distros: ['SUSE Linux'] }, + { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, + { name: 'debian_version', distros: ['Debian'] }, + { name: 'debian_release', distros: ['Debian'] }, + { name: 'arch-release', distros: ['Arch Linux'] }, + { name: 'gentoo-release', distros: ['Gentoo Linux'] }, + { name: 'novell-release', distros: ['SUSE Linux'] }, + { name: 'alpine-release', distros: ['Alpine Linux'] }, +]; - // TODO(v7): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node - // versions(>= 8) as they had memory leaks when using it: #2555 - const agent = proxy - ? (new (__webpack_require__(1675))(proxy) ) - : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 }); +/** Functions to extract the OS version from Linux release files. */ +const LINUX_VERSIONS - const requestExecutor = createRequestExecutor(options, (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(options.httpModule, () => ( nativeHttpModule)), agent); - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.createTransport)(options, requestExecutor); -} + = { + alpine: content => content, + arch: content => matchFirst(/distrib_release=(.*)/, content), + centos: content => matchFirst(/release ([^ ]+)/, content), + debian: content => content, + fedora: content => matchFirst(/release (..)/, content), + mint: content => matchFirst(/distrib_release=(.*)/, content), + red: content => matchFirst(/release ([^ ]+)/, content), + suse: content => matchFirst(/VERSION = (.*)\n/, content), + ubuntu: content => matchFirst(/distrib_release=(.*)/, content), +}; /** - * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion. + * Executes a regular expression with one capture group. * - * @param transportUrl The URL the transport intends to send events to. - * @param proxy The client configured proxy. - * @returns A proxy the transport should use. + * @param regex A regular expression to execute. + * @param text Content to execute the RegEx on. + * @returns The captured string if matched; otherwise undefined. */ -function applyNoProxyOption(transportUrlSegments, proxy) { - const { no_proxy } = process.env; +function matchFirst(regex, text) { + const match = regex.exec(text); + return match ? match[1] : undefined; +} - const urlIsExemptFromProxy = - no_proxy && - no_proxy - .split(',') - .some( - exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption), - ); +/** Loads the macOS operating system context. */ +async function getDarwinInfo() { + // Default values that will be used in case no operating system information + // can be loaded. The default version is computed via heuristics from the + // kernel version, but the build ID is missing. + const darwinInfo = { + kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + name: 'Mac OS X', + version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, + }; - if (urlIsExemptFromProxy) { - return undefined; - } else { - return proxy; - } -} + try { + // We try to load the actual macOS version by executing the `sw_vers` tool. + // This tool should be available on every standard macOS installation. In + // case this fails, we stick with the values computed above. -/** - * Creates a RequestExecutor to be used with `createTransport`. - */ -function createRequestExecutor( - options, - httpModule, - agent, -) { - const { hostname, pathname, port, protocol, search } = new url__WEBPACK_IMPORTED_MODULE_3__.URL(options.url); - return function makeRequest(request) { - return new Promise((resolve, reject) => { - let body = streamFromBody(request.body); + const output = await new Promise((resolve, reject) => { + (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { + if (error) { + reject(error); + return; + } + resolve(stdout); + }); + }); - const headers = { ...options.headers }; + darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); + darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); + darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); + } catch (e) { + // ignore + } - if (request.body.length > GZIP_THRESHOLD) { - headers['content-encoding'] = 'gzip'; - body = body.pipe((0,zlib__WEBPACK_IMPORTED_MODULE_4__.createGzip)()); - } + return darwinInfo; +} - const req = httpModule.request( - { - method: 'POST', - agent, - headers, - hostname, - path: `${pathname}${search}`, - port, - protocol, - ca: options.caCerts, - }, - res => { - res.on('data', () => { - // Drain socket - }); +/** Returns a distribution identifier to look up version callbacks. */ +function getLinuxDistroId(name) { + return name.split(' ')[0].toLowerCase(); +} - res.on('end', () => { - // Drain socket - }); +/** Loads the Linux operating system context. */ +async function getLinuxInfo() { + // By default, we cannot assume anything about the distribution or Linux + // version. `os.release()` returns the kernel version and we assume a generic + // "Linux" name, which will be replaced down below. + const linuxInfo = { + kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), + name: 'Linux', + }; - res.setEncoding('utf8'); + try { + // We start guessing the distribution by listing files in the /etc + // directory. This is were most Linux distributions (except Knoppix) store + // release files with certain distribution-dependent meta data. We search + // for exactly one known file defined in `LINUX_DISTROS` and exit if none + // are found. In case there are more than one file, we just stick with the + // first one. + const etcFiles = await readDirAsync('/etc'); + const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); + if (!distroFile) { + return linuxInfo; + } - // "Key-value pairs of header names and values. Header names are lower-cased." - // https://nodejs.org/api/http.html#http_message_headers - const retryAfterHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['retry-after'], () => ( null)); - const rateLimitsHeader = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._nullishCoalesce)(res.headers['x-sentry-rate-limits'], () => ( null)); + // Once that file is known, load its contents. To make searching in those + // files easier, we lowercase the file contents. Since these files are + // usually quite small, this should not allocate too much memory and we only + // hold on to it for a very short amount of time. + const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); + const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); - resolve({ - statusCode: res.statusCode, - headers: { - 'retry-after': retryAfterHeader, - 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] : rateLimitsHeader, - }, - }); - }, - ); + // Some Linux distributions store their release information in the same file + // (e.g. RHEL and Centos). In those cases, we scan the file for an + // identifier, that basically consists of the first word of the linux + // distribution name (e.g. "red" for Red Hat). In case there is no match, we + // just assume the first distribution in our list. + const { distros } = distroFile; + linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; - req.on('error', reject); - body.pipe(req); - }); - }; + // Based on the found distribution, we can now compute the actual version + // number. This is different for every distribution, so several strategies + // are computed in `LINUX_VERSIONS`. + const id = getLinuxDistroId(linuxInfo.name); + linuxInfo.version = LINUX_VERSIONS[id](contents); + } catch (e) { + // ignore + } + + return linuxInfo; } -//# sourceMappingURL=http.js.map +//# sourceMappingURL=context.js.map /***/ }), -/* 1675 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/* 1665 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "RequestData": () => (/* binding */ RequestData) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1669); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const agent_1 = __importDefault(__webpack_require__(1676)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); -} -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map - -/***/ }), -/* 1676 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +const DEFAULT_OPTIONS = { + include: { + cookies: true, + data: true, + headers: true, + ip: false, + query_string: true, + url: true, + user: { + id: true, + username: true, + email: true, + }, + }, + transactionNamingScheme: 'methodPath', }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__webpack_require__(62)); -const tls_1 = __importDefault(__webpack_require__(145)); -const url_1 = __importDefault(__webpack_require__(63)); -const assert_1 = __importDefault(__webpack_require__(91)); -const debug_1 = __importDefault(__webpack_require__(1677)); -const agent_base_1 = __webpack_require__(1681); -const parse_proxy_response_1 = __importDefault(__webpack_require__(1687)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); - } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); - } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; - } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; - } - if (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; - } - this.proxy = proxy; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); - } -} -exports["default"] = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=agent.js.map -/***/ }), -/* 1677 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` + * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ +class RequestData { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'RequestData';} + + /** + * @inheritDoc + */ + __init() {this.name = RequestData.id;} + + /** + * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but + * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use + * something similar in browser-based SDKs in the future. + */ -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + /** + * @inheritDoc + */ + constructor(options = {}) {;RequestData.prototype.__init.call(this); + this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; + this._options = { + ...DEFAULT_OPTIONS, + ...options, + include: { + // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in + // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) + method: true, + ...DEFAULT_OPTIONS.include, + ...options.include, + user: + options.include && typeof options.include.user === 'boolean' + ? options.include.user + : { + ...DEFAULT_OPTIONS.include.user, + // Unclear why TS still thinks `options.include.user` could be a boolean at this point + ...((options.include || {}).user ), + }, + }, + }; + } -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1678); -} else { - module.exports = __webpack_require__(1680); -} + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + // Note: In the long run, most of the logic here should probably move into the request data utility functions. For + // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. + // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once + // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) + const { transactionNamingScheme } = this._options; + addGlobalEventProcessor(event => { + const hub = getCurrentHub(); + const self = hub.getIntegration(RequestData); -/***/ }), -/* 1678 */ -/***/ ((module, exports, __webpack_require__) => { + const { sdkProcessingMetadata = {} } = event; + const req = sdkProcessingMetadata.request; -/* eslint-env browser */ + // If the globally installed instance of this integration isn't associated with the current hub, `self` will be + // undefined + if (!self || !req) { + return event; + } -/** - * This is the web browser implementation of `debug()`. - */ + // The Express request handler takes a similar `include` option to that which can be passed to this integration. + // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this + // integration, so that all of this passing and conversion isn't necessary + const addRequestDataOptions = + sdkProcessingMetadata.requestDataOptionsFromExpressHandler || + sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || + convertReqDataIntegrationOptsToAddReqDataOpts(this._options); -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + const processedEvent = this._addRequestData(event, req, addRequestDataOptions); - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + // Transaction events already have the right `transaction` value + if (event.type === 'transaction' || transactionNamingScheme === 'handler') { + return processedEvent; + } -/** - * Colors. - */ + // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` + // value with a high-quality one + const reqWithTransaction = req ; + const transaction = reqWithTransaction._sentryTransaction; + if (transaction) { + // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to + // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential + // to break things like alert rules.) + const shouldIncludeMethodInTransactionName = + getSDKName(hub) === 'sentry.javascript.nextjs' + ? transaction.name.startsWith('/api') + : transactionNamingScheme !== 'path'; + + const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { + path: true, + method: shouldIncludeMethodInTransactionName, + customRoute: transaction.name, + }); + + processedEvent.transaction = transactionValue; + } + + return processedEvent; + }); + } +} RequestData.__initStatic(); + +/** Convert this integration's options to match what `addRequestDataToEvent` expects */ +/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ +function convertReqDataIntegrationOptsToAddReqDataOpts( + integrationOptions, +) { + const { + transactionNamingScheme, + include: { ip, user, ...requestOptions }, + } = integrationOptions; + + const requestIncludeKeys = []; + for (const [key, value] of Object.entries(requestOptions)) { + if (value) { + requestIncludeKeys.push(key); + } + } + + let addReqDataUserOpt; + if (user === undefined) { + addReqDataUserOpt = true; + } else if (typeof user === 'boolean') { + addReqDataUserOpt = user; + } else { + const userIncludeKeys = []; + for (const [key, value] of Object.entries(user)) { + if (value) { + userIncludeKeys.push(key); + } + } + addReqDataUserOpt = userIncludeKeys; + } + + return { + include: { + ip, + user: addReqDataUserOpt, + request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, + transaction: transactionNamingScheme, + }, + }; +} + +function getSDKName(hub) { + try { + // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to + // write out a long chain of `a && a.b && a.b.c && ...` + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return hub.getClient().getOptions()._metadata.sdk.name; + } catch (err) { + // In theory we should never get here + return undefined; + } +} -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ +//# sourceMappingURL=requestdata.js.map -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } +/***/ }), +/* 1666 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), +/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), +/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), +/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1668); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1621); +/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1667); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); +/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); -/** - * Colorize log arguments if enabled. - * - * @api public - */ -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +const DEFAULT_INCLUDES = { + ip: false, + request: true, + transaction: true, + user: true, +}; +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; - args.splice(lastC, 0, c); -} +/** + * Options deciding what parts of the request to use when enhancing an event + */ /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public + * Sets parameterized route as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request */ -exports.log = console.debug || console.log || (() => {}); +function addRequestDataToTransaction(transaction, req) { + if (!transaction) return; + if (!transaction.metadata.source || transaction.metadata.source === 'url') { + // Attempt to grab a parameterized route off of the request + transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); + } + transaction.setData('url', req.originalUrl || req.url); + if (req.baseUrl) { + transaction.setData('baseUrl', req.baseUrl); + } + transaction.setData('query', extractQueryParams(req)); +} /** - * Save `namespaces`. + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. * - * @param {String} namespaces - * @api private + * Additionally, this function determines and returns the transaction name source + * + * eg. GET /mountpoint/user/:id + * + * @param req A request object + * @param options What to include in the transaction name (method, path, or a custom route name to be + * used instead of the request's route) + * + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function extractPathForTransaction( + req, + options = {}, +) { + const method = req.method && req.method.toUpperCase(); + + let path = ''; + let source = 'url'; + + // Check to see if there's a parameterized route we can use (as there is in Express) + if (options.customRoute || req.route) { + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; + source = 'route'; + } + + // Otherwise, just take the original URL + else if (req.originalUrl || req.url) { + path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); + } + + let name = ''; + if (options.method && method) { + name += method; + } + if (options.method && options.path) { + name += ' '; + } + if (options.path && path) { + name += path; + } + + return [name, source]; +} + +/** JSDoc */ +function extractTransaction(req, type) { + switch (type) { + case 'path': { + return extractPathForTransaction(req, { path: true })[0]; + } + case 'handler': { + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + } + case 'methodPath': + default: { + return extractPathForTransaction(req, { path: true, method: true })[0]; + } + } +} + +/** JSDoc */ +function extractUserData( + user + +, + keys, +) { + const extractedUser = {}; + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + + attributes.forEach(key => { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + + return extractedUser; } /** - * Load `namespaces`. + * Normalize data from the request object * - * @return {String} returns the previously persisted debug modes - * @api private + * @param req The request object from which to extract data + * @param options.include An optional array of keys to include in the normalized data. Defaults to + * DEFAULT_REQUEST_INCLUDES if not provided. + * @param options.deps Injected, platform-specific dependencies + * + * @returns An object containing normalized request data */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +function extractRequestData( + req, + options + +, +) { + const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; + const requestData = {}; + + // headers: + // node, express, koa, nextjs: req.headers + const headers = (req.headers || {}) + +; + // method: + // node, express, koa, nextjs: req.method + const method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + const host = req.hostname || req.host || headers.host || '<no host>'; + // protocol: + // node, nextjs: <n/a> + // express, koa: req.protocol + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + const originalUrl = req.originalUrl || req.url || ''; + // absolute url + const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; + include.forEach(key => { + switch (key) { + case 'headers': { + requestData.headers = headers; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } + // Remove the Cookie header in case cookie data should not be included in the event + if (!include.includes('cookies')) { + delete (requestData.headers ).cookie; + } - return r; + break; + } + case 'method': { + requestData.method = method; + break; + } + case 'url': { + requestData.url = absoluteUrl; + break; + } + case 'cookies': { + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can + // come off in v8 + req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; + break; + } + case 'query_string': { + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = extractQueryParams(req); + break; + } + case 'data': { + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); + } + break; + } + default: { + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = (req )[key]; + } + } + } + }); + + return requestData; } /** - * Localstorage attempts to return the localstorage. + * Add data from the given request to the given event * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * @param event The event to which the request data will be added + * @param req Request object + * @param options.include Flags to control what data is included * - * @return {LocalStorage} - * @api private + * @returns The mutated `Event` object */ +function addRequestDataToEvent( + event, + req, + options, +) { + const include = { + ...DEFAULT_INCLUDES, + ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), + }; -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} + if (include.request) { + const extractedRequestData = Array.isArray(include.request) + ? extractRequestData(req, { include: include.request }) + : extractRequestData(req); -module.exports = __webpack_require__(1679)(exports); + event.request = { + ...event.request, + ...extractedRequestData, + }; + } -const {formatters} = module.exports; + if (include.user) { + const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (Object.keys(extractedUser).length) { + event.user = { + ...event.user, + ...extractedUser, + }; + } + } -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; + // client ip: + // node, nextjs: req.socket.remoteAddress + // express, koa: req.ip + if (include.ip) { + const ip = req.ip || (req.socket && req.socket.remoteAddress); + if (ip) { + event.user = { + ...event.user, + ip_address: ip, + }; + } + } + if (include.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, include.transaction); + } -/***/ }), -/* 1679 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return event; +} +function extractQueryParams(req) { + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + let originalUrl = req.originalUrl || req.url || ''; -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ + if (!originalUrl) { + return; + } -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1405); - createDebug.destroy = destroy; + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. + if (originalUrl.startsWith('/')) { + originalUrl = `http://dogs.are.great${originalUrl}`; + } - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); + return ( + req.query || + (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node + url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || + undefined + ); +} - /** - * The currently active debug mode names, and names to skip. - */ - createDebug.names = []; - createDebug.skips = []; +//# sourceMappingURL=requestdata.js.map - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +/***/ }), +/* 1667 */ +/***/ ((__unused_webpack_module, exports) => { - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } +/** + * Module exports. + * @public + */ - const self = debug; +exports.parse = parse; +exports.serialize = serialize; - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; - args[0] = createDebug.coerce(args[0]); +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + var obj = {} + var opt = options || {}; + var pairs = str.split(';') + var dec = opt.decode || decode; - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var index = pair.indexOf('=') - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + // skip things that don't look like key=value + if (index < 0) { + continue; + } - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } + var key = pair.substring(0, index).trim() - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); + // only assign once + if (undefined == obj[key]) { + var val = pair.substring(index + 1, pair.length).trim() - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } + // quoted values + if (val[0] === '"') { + val = val.slice(1, -1) + } - return debug; - } + obj[key] = tryDecode(val, dec); + } + } - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + return obj; +} - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ - createDebug.names = []; - createDebug.skips = []; +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } - namespaces = split[i].replace(/\*/g, '.*?'); + var value = enc(val); - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } + var str = name + '=' + value; - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; - let i; - let len; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') + } - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } + str += '; Max-Age=' + Math.floor(maxAge); + } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } - return false; - } + str += '; Domain=' + opt.domain; + } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + str += '; Path=' + opt.path; + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } - createDebug.enable(createDebug.load()); + str += '; Expires=' + opt.expires.toUTCString(); + } - return createDebug; -} + if (opt.httpOnly) { + str += '; HttpOnly'; + } -module.exports = setup; + if (opt.secure) { + str += '; Secure'; + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; -/***/ }), -/* 1680 */ -/***/ ((module, exports, __webpack_require__) => { + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} /** - * Module dependencies. + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private */ -const tty = __webpack_require__(1407); -const util = __webpack_require__(64); +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} -/** - * This is the Node.js implementation of `debug()`. - */ -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +/***/ }), +/* 1668 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), +/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), +/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) +/* harmony export */ }); /** - * Colors. + * Parses string form of URL into an object + * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B + * // intentionally using regex and not <a/> href parsing trick because React Native and other + * // environments where DOM might not be available + * @returns parsed URL object */ +function parseUrl(url) -exports.colors = [6, 2, 3, 4, 5, 1]; + { + if (!url) { + return {}; + } -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1408); + const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. + if (!match) { + return {}; + } + + // coerce to undefined values to empty string so we don't get 'undefined' + const query = match[6] || ''; + const fragment = match[8] || ''; + return { + host: match[4], + path: match[5], + protocol: match[2], + relative: match[5] + query + fragment, // everything minus origin + }; } /** - * Build up the default `inspectOpts` object from the environment variables. + * Strip the query string and fragment off of a given URL or path (if present) * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment */ +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; +} -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +/** + * Returns number of URL segments of a passed string URL. + */ +function getNumberOfUrlSegments(url) { + // split at '/' or at '\/' to split regex urls correctly + return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; +} - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; -}, {}); +//# sourceMappingURL=url.js.map + + +/***/ }), +/* 1669 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), +/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), +/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) +/* harmony export */ }); +/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1624); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1610); +/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1621); +/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1668); + + + + + +const DEFAULT_INCLUDES = { + ip: false, + request: true, + transaction: true, + user: true, +}; +const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Sets parameterized route as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +function addRequestDataToTransaction( + transaction, + req, + deps, +) { + if (!transaction) return; + if (!transaction.metadata.source || transaction.metadata.source === 'url') { + // Attempt to grab a parameterized route off of the request + transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); + } + transaction.setData('url', req.originalUrl || req.url); + if (req.baseUrl) { + transaction.setData('baseUrl', req.baseUrl); + } + transaction.setData('query', extractQueryParams(req, deps)); } /** - * Adds ANSI color escape codes if enabled. + * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. + * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. * - * @api public + * Additionally, this function determines and returns the transaction name source + * + * eg. GET /mountpoint/user/:id + * + * @param req A request object + * @param options What to include in the transaction name (method, path, or a custom route name to be + * used instead of the request's route) + * + * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') */ +function extractPathForTransaction( + req, + options = {}, +) { + const method = req.method && req.method.toUpperCase(); -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + let path = ''; + let source = 'url'; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + // Check to see if there's a parameterized route we can use (as there is in Express) + if (options.customRoute || req.route) { + path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; + source = 'route'; + } -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} + // Otherwise, just take the original URL + else if (req.originalUrl || req.url) { + path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); + } -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + let name = ''; + if (options.method && method) { + name += method; + } + if (options.method && options.path) { + name += ' '; + } + if (options.path && path) { + name += path; + } -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); + return [name, source]; } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } +/** JSDoc */ +function extractTransaction(req, type) { + switch (type) { + case 'path': { + return extractPathForTransaction(req, { path: true })[0]; + } + case 'handler': { + return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + } + case 'methodPath': + default: { + return extractPathForTransaction(req, { path: true, method: true })[0]; + } + } } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +/** JSDoc */ +function extractUserData( + user -function load() { - return process.env.DEBUG; +, + keys, +) { + const extractedUser = {}; + const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + + attributes.forEach(key => { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + + return extractedUser; } /** - * Init logic for `debug` instances. + * Normalize data from the request object, accounting for framework differences. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @param req The request object from which to extract data + * @param options.include An optional array of keys to include in the normalized data. Defaults to + * DEFAULT_REQUEST_INCLUDES if not provided. + * @param options.deps Injected, platform-specific dependencies + * @returns An object containing normalized request data */ +function extractRequestData( + req, + options -function init(debug) { - debug.inspectOpts = {}; +, +) { + const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; + const requestData = {}; - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + // headers: + // node, express, koa, nextjs: req.headers + const headers = (req.headers || {}) -module.exports = __webpack_require__(1679)(exports); +; + // method: + // node, express, koa, nextjs: req.method + const method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node, nextjs: req.headers.host + const host = req.hostname || req.host || headers.host || '<no host>'; + // protocol: + // node, nextjs: <n/a> + // express, koa: req.protocol + const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + const originalUrl = req.originalUrl || req.url || ''; + // absolute url + const absoluteUrl = `${protocol}://${host}${originalUrl}`; + include.forEach(key => { + switch (key) { + case 'headers': { + requestData.headers = headers; + break; + } + case 'method': { + requestData.method = method; + break; + } + case 'url': { + requestData.url = absoluteUrl; + break; + } + case 'cookies': { + // cookies: + // node, express, koa: req.headers.cookie + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = + // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can + // come off in v8 + req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; + break; + } + case 'query_string': { + // query string: + // node: req.url (raw) + // express, koa, nextjs: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = extractQueryParams(req, deps); + break; + } + case 'data': { + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves + if (req.body !== undefined) { + requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); + } + break; + } + default: { + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = (req )[key]; + } + } + } + }); -const {formatters} = module.exports; + return requestData; +} /** - * Map %o to `util.inspect()`, all on a single line. + * Options deciding what parts of the request to use when enhancing an event */ -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * Add data from the given request to the given event + * + * @param event The event to which the request data will be added + * @param req Request object + * @param options.include Flags to control what data is included + * @param options.deps Injected platform-specific dependencies + * @hidden */ +function addRequestDataToEvent( + event, + req, + options, +) { + const include = { + ...DEFAULT_INCLUDES, + ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), + }; -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + if (include.request) { + const extractedRequestData = Array.isArray(include.request) + ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) + : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); + event.request = { + ...event.request, + ...extractedRequestData, + }; + } -/***/ }), -/* 1681 */ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (include.user) { + const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; -"use strict"; + if (Object.keys(extractedUser).length) { + event.user = { + ...event.user, + ...extractedUser, + }; + } + } -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -const events_1 = __webpack_require__(250); -const debug_1 = __importDefault(__webpack_require__(1682)); -const promisify_1 = __importDefault(__webpack_require__(1686)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); -} -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; - } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; - } - return isSecureEndpoint() ? 443 : 80; - } - set defaultPort(v) { - this.explicitDefaultPort = v; - } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; - } - return isSecureEndpoint() ? 'https:' : 'http:'; - } - set protocol(v) { - this.explicitProtocol = v; - } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); - } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; - } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; - } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); - return; - } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; - } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; - } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; - } - } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } - } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); - } - destroy() { - debug('Destroying agent %o', this.constructor.name); - } + // client ip: + // node, nextjs: req.socket.remoteAddress + // express, koa: req.ip + if (include.ip) { + const ip = req.ip || (req.socket && req.socket.remoteAddress); + if (ip) { + event.user = { + ...event.user, + ip_address: ip, + }; } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map + } + + if (include.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, include.transaction); + } + + return event; +} + +function extractQueryParams( + req, + deps, +) { + // url (including path and query string): + // node, express: req.originalUrl + // koa, nextjs: req.url + let originalUrl = req.originalUrl || req.url || ''; + + if (!originalUrl) { + return; + } + + // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and + // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. + if (originalUrl.startsWith('/')) { + originalUrl = `http://dogs.are.great${originalUrl}`; + } + + return ( + req.query || + (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || + // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node + (deps && deps.url && deps.url.parse(originalUrl).query) || + undefined + ); +} + + +//# sourceMappingURL=requestdata.js.map + /***/ }), -/* 1682 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/* 1670 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getModule": () => (/* binding */ getModule) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1671); -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __webpack_require__(1683); -} else { - module.exports = __webpack_require__(1685); + +/** normalizes Windows paths */ +function normalizePath(path) { + return path + .replace(/^[A-Z]:/, '') // remove Windows-style prefix + .replace(/\\/g, '/'); // replace all `\` instances with `/` +} + +/** Gets the module from a filename */ +function getModule(filename) { + if (!filename) { + return; + } + + const normalizedFilename = normalizePath(filename); + + // We could use optional chaining here but webpack does like that mixed with require + const base = normalizePath( + `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, + ); + + // It's specifically a module + const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); + + const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); + let n = path.lastIndexOf('/node_modules/'); + if (n > -1) { + // /node_modules/ is 14 chars + return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; + } + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + n = `${path}/`.lastIndexOf(base, 0); + + if (n === 0) { + let moduleName = path.substr(base.length).replace(/\//g, '.'); + if (moduleName) { + moduleName += ':'; + } + moduleName += file; + return moduleName; + } + return file; } +//# sourceMappingURL=module.js.map + + /***/ }), -/* 1683 */ -/***/ ((module, exports, __webpack_require__) => { +/* 1671 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -/* eslint-env browser */ +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "basename": () => (/* binding */ basename), +/* harmony export */ "dirname": () => (/* binding */ dirname), +/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), +/* harmony export */ "join": () => (/* binding */ join), +/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), +/* harmony export */ "relative": () => (/* binding */ relative), +/* harmony export */ "resolve": () => (/* binding */ resolve) +/* harmony export */ }); +// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript +// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js -/** - * This is the web browser implementation of `debug()`. - */ +/** JSDoc */ +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + let up = 0; + for (let i = parts.length - 1; i >= 0; i--) { + const last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); + return parts; +} -/** - * Colors. - */ +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; +/** JSDoc */ +function splitPath(filename) { + const parts = splitPathRe.exec(filename); + return parts ? parts.slice(1) : []; +} -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +// path.resolve([from ...], to) +// posix version +/** JSDoc */ +function resolve(...args) { + let resolvedPath = ''; + let resolvedAbsolute = false; + + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + // Skip empty entries + if (!path) { + continue; + } -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charAt(0) === '/'; + } - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + // Normalize the path + resolvedPath = normalizeArray( + resolvedPath.split('/').filter(p => !!p), + !resolvedAbsolute, + ).join('/'); + + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; } -/** - * Colorize log arguments if enabled. - * - * @api public - */ +/** JSDoc */ +function trim(arr) { + let start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') { + break; + } + } -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); + let end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') { + break; + } + } - if (!this.useColors) { - return; - } + if (start > end) { + return []; + } + return arr.slice(start, end - start + 1); +} - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); +// path.relative(from, to) +// posix version +/** JSDoc */ +function relative(from, to) { + /* eslint-disable no-param-reassign */ + from = resolve(from).substr(1); + to = resolve(to).substr(1); + /* eslint-enable no-param-reassign */ - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + const fromParts = trim(from.split('/')); + const toParts = trim(to.split('/')); - args.splice(lastC, 0, c); + const length = Math.min(fromParts.length, toParts.length); + let samePartsLength = length; + for (let i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + let outputParts = []; + for (let i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); } -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); +// path.normalize(path) +// posix version +/** JSDoc */ +function normalizePath(path) { + const isPathAbsolute = isAbsolute(path); + const trailingSlash = path.substr(-1) === '/'; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } + // Normalize the path + let normalizedPath = normalizeArray( + path.split('/').filter(p => !!p), + !isPathAbsolute, + ).join('/'); + + if (!normalizedPath && !isPathAbsolute) { + normalizedPath = '.'; + } + if (normalizedPath && trailingSlash) { + normalizedPath += '/'; + } + + return (isPathAbsolute ? '/' : '') + normalizedPath; } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +// posix version +/** JSDoc */ +function isAbsolute(path) { + return path.charAt(0) === '/'; +} - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } +// posix version +/** JSDoc */ +function join(...args) { + return normalizePath(args.join('/')); +} - return r; +/** JSDoc */ +function dirname(path) { + const result = splitPath(path); + const root = result[0]; + let dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; } -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +/** JSDoc */ +function basename(path, ext) { + let f = splitPath(path)[2]; + if (ext && f.substr(ext.length * -1) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +} + + +//# sourceMappingURL=path.js.map + + +/***/ }), +/* 1672 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), +/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), +/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1608); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1609); + + +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} +/** Options for the InboundFilters integration */ -module.exports = __webpack_require__(1684)(exports); +/** Inbound filters configurable by the user */ +class InboundFilters { + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'InboundFilters';} -const {formatters} = module.exports; + /** + * @inheritDoc + */ + __init() {this.name = InboundFilters.id;} -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; + /** + * @inheritDoc + */ + setupOnce(addGlobalEventProcessor, getCurrentHub) { + const eventProcess = (event) => { + const hub = getCurrentHub(); + if (hub) { + const self = hub.getIntegration(InboundFilters); + if (self) { + const client = hub.getClient(); + const clientOptions = client ? client.getOptions() : {}; + const options = _mergeOptions(self._options, clientOptions); + return _shouldDropEvent(event, options) ? null : event; + } + } + return event; + }; + eventProcess.id = this.name; + addGlobalEventProcessor(eventProcess); + } +} InboundFilters.__initStatic(); -/***/ }), -/* 1684 */ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** JSDoc */ +function _mergeOptions( + internalOptions = {}, + clientOptions = {}, +) { + return { + allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], + denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], + ignoreErrors: [ + ...(internalOptions.ignoreErrors || []), + ...(clientOptions.ignoreErrors || []), + ...DEFAULT_IGNORE_ERRORS, + ], + ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, + }; +} +/** JSDoc */ +function _shouldDropEvent(event, options) { + if (options.ignoreInternal && _isSentryError(event)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return true; + } + if (_isIgnoredError(event, options.ignoreErrors)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, + ); + return true; + } + if (_isDeniedUrl(event, options.denyUrls)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + if (!_isAllowedUrl(event, options.allowUrls)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( + `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( + event, + )}.\nUrl: ${_getEventFilterUrl(event)}`, + ); + return true; + } + return false; +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ +function _isIgnoredError(event, ignoreErrors) { + if (!ignoreErrors || !ignoreErrors.length) { + return false; + } -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__(1405); - createDebug.destroy = destroy; + return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); +} - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +function _isDeniedUrl(event, denyUrls) { + // TODO: Use Glob instead? + if (!denyUrls || !denyUrls.length) { + return false; + } + const url = _getEventFilterUrl(event); + return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); +} - /** - * The currently active debug mode names, and names to skip. - */ +function _isAllowedUrl(event, allowUrls) { + // TODO: Use Glob instead? + if (!allowUrls || !allowUrls.length) { + return true; + } + const url = _getEventFilterUrl(event); + return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); +} - createDebug.names = []; - createDebug.skips = []; +function _getPossibleEventMessages(event) { + if (event.message) { + return [event.message]; + } + if (event.exception) { + try { + const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; + return [`${value}`, `${type}: ${value}`]; + } catch (oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return []; + } + } + return []; +} - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +function _isSentryError(event) { + try { + // @ts-ignore can't be a sentry error if undefined + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return event.exception.values[0].type === 'SentryError'; + } catch (e) { + // ignore + } + return false; +} - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +function _getLastValidUrl(frames = []) { + for (let i = frames.length - 1; i >= 0; i--) { + const frame = frames[i]; - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { + return frame.filename || null; + } + } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + return null; +} - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +function _getEventFilterUrl(event) { + try { + let frames; + try { + // @ts-ignore we only care about frames if the whole thing here is defined + frames = event.exception.values[0].stacktrace.frames; + } catch (e) { + // ignore + } + return frames ? _getLastValidUrl(frames) : null; + } catch (oO) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); + return null; + } +} - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - const self = debug; +//# sourceMappingURL=inboundfilters.js.map - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); +/***/ }), +/* 1673 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1611); - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +let originalFunctionToString; - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +/** Patch toString calls to return proper name for wrapped functions */ +class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } + /** + * @inheritDoc + */ + static __initStatic() {this.id = 'FunctionToString';} - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + /** + * @inheritDoc + */ + __init() {this.name = FunctionToString.id;} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } + /** + * @inheritDoc + */ + setupOnce() { + // eslint-disable-next-line @typescript-eslint/unbound-method + originalFunctionToString = Function.prototype.toString; - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Function.prototype.toString = function ( ...args) { + const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; + return originalFunctionToString.apply(context, args); + }; + } +} FunctionToString.__initStatic(); - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); +//# sourceMappingURL=functiontostring.js.map - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - return debug; - } +/***/ }), +/* 1674 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) +/* harmony export */ }); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1614); +/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1601); - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +/** A class object that can instantiate Client objects. */ - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/** + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. + * + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. + */ +function initAndBind( + clientClass, + options, +) { + if (options.debug === true) { + if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { + _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); + } else { + // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped + // eslint-disable-next-line no-console + console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + } + } + const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); + const scope = hub.getScope(); + if (scope) { + scope.update(options.initialScope); + } - namespaces = split[i].replace(/\*/g, '.*?'); + const client = new clientClass(options); + hub.bindClient(client); +} - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +//# sourceMappingURL=sdk.js.map - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - let i; - let len; +/***/ }), +/* 1675 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) +/* harmony export */ }); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); +/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - return false; - } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +/** + * Recursively read the contents of a directory. + * + * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this + * directory. + * @returns Array holding all relative paths + */ +function deepReadDirSync(targetDir) { + const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { + throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); + } - createDebug.enable(createDebug.load()); + // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it + // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve + // the difference between `targetDirAbsPath` and `currentDirAbsPath`. + const deepReadCurrentDir = (currentDirAbsPath) => { + return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { + const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); - return createDebug; -} + if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { + return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; + } -module.exports = setup; + return [...absPaths, itemAbsPath]; + }, []); + }; + return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); +} -/***/ }), -/* 1685 */ -/***/ ((module, exports, __webpack_require__) => { -/** - * Module dependencies. - */ +//# sourceMappingURL=utils.js.map -const tty = __webpack_require__(1407); -const util = __webpack_require__(64); -/** - * This is the Node.js implementation of `debug()`. - */ +/***/ }), +/* 1676 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), +/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), +/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), +/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), +/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) +/* harmony export */ }); +/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1624); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1601); +/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1616); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1614); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1610); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1678); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1656); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1669); +/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1611); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); +/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1666); +/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1650); +/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1677); -/** - * Colors. - */ -exports.colors = [6, 2, 3, 4, 5, 1]; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __webpack_require__(1408); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; -}, {}); +/* eslint-disable @typescript-eslint/no-explicit-any */ /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Express-compatible tracing handler. + * @see Exposed as `Handlers.tracingHandler` */ +function tracingHandler() -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} + { + return function sentryTracingMiddleware( + req, + res, + next, + ) { + const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + if ( + !options || + options.instrumenter !== 'sentry' || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || + (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' + ) { + return next(); + } -function formatArgs(args) { - const {namespace: name, useColors} = this; + // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a + // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. + if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && + _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( + 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + + 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', + ); + return next(); + } - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) + const traceparentData = + req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); + const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); + const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} + const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); + const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( + { + name, + op: 'http.server', + ...traceparentData, + metadata: { + dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, + // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become + // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the + // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to + // be sure + request: req, + source, + }, + }, + // extra context passed to the tracesSampler + { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, + ); -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} + // We put the transaction on the scope so users can attach children to it + hub.configureScope(scope => { + scope.setSpan(transaction); + }); + + // We also set __sentry_transaction on the response so people can grab the transaction there to add + // spans to it later. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).__sentry_transaction = transaction; -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ + res.once('finish', () => { + // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction + // closes + setImmediate(() => { + (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); + transaction.setHttpStatus(res.statusCode); + transaction.finish(); + }); + }); -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); + next(); + }; } /** - * Save `namespaces`. + * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the + * `AddRequestDataToEventOptions` interface. * - * @param {String} namespaces - * @api private + * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} +function convertReqHandlerOptsToAddReqDataOpts( + reqHandlerOptions = {}, +) { + let addRequestDataOptions; -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + if ('include' in reqHandlerOptions) { + addRequestDataOptions = { include: reqHandlerOptions.include }; + } else { + // eslint-disable-next-line deprecation/deprecation + const { ip, request, transaction, user } = reqHandlerOptions ; -function load() { - return process.env.DEBUG; + if (ip || request || transaction || user) { + addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; + } + } + + return addRequestDataOptions; } /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` */ +function requestHandler( + options, +) { + // TODO (v8): Get rid of this + const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); -function init(debug) { - debug.inspectOpts = {}; + const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); + const client = currentHub.getClient(); + // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the + // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode + if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + client.initSessionFlusher(); - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode + const scope = currentHub.getScope(); + if (scope && scope.getSession()) { + scope.setSession(); + } + } -module.exports = __webpack_require__(1684)(exports); + return function sentryRequestMiddleware( + req, + res, + next, + ) { + if (options && options.flushTimeout && options.flushTimeout > 0) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const _end = res.end; + res.end = function (chunk, encoding, cb) { + void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) + .then(() => { + _end.call(this, chunk, encoding, cb); + }) + .then(null, e => { + (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); + _end.call(this, chunk, encoding, cb); + }); + }; + } + const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); + local.add(req); + local.add(res); -const {formatters} = module.exports; + local.run(() => { + const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); -/** - * Map %o to `util.inspect()`, all on a single line. - */ + currentHub.configureScope(scope => { + scope.setSDKProcessingMetadata({ + request: req, + // TODO (v8): Stop passing this + requestDataOptionsFromExpressHandler: requestDataOptions, + }); -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + const client = currentHub.getClient(); + if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + const scope = currentHub.getScope(); + if (scope) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope.setRequestSession({ status: 'ok' }); + } + } + }); -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + res.once('finish', () => { + const client = currentHub.getClient(); + if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + setImmediate(() => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (client && (client )._captureRequestSession) { + // Calling _captureRequestSession to capture request session at the end of the request by incrementing + // the correct SessionAggregates bucket i.e. crashed, errored or exited + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (client )._captureRequestSession(); + } + }); + } + }); + next(); + }); + }; +} -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +/** JSDoc */ +/** JSDoc */ +function getStatusCodeFromResponse(error) { + const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); + return statusCode ? parseInt(statusCode , 10) : 500; +} -/***/ }), -/* 1686 */ -/***/ ((__unused_webpack_module, exports) => { +/** Returns true if response code is internal server error */ +function defaultShouldHandleError(error) { + const status = getStatusCodeFromResponse(error); + return status >= 500; +} -"use strict"; +/** + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` + */ +function errorHandler(options -Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); - } - }); - }); - }; -} -exports["default"] = promisify; -//# sourceMappingURL=promisify.js.map +) -/***/ }), -/* 1687 */ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + { + return function sentryErrorMiddleware( + error, + _req, + res, + next, + ) { + // eslint-disable-next-line @typescript-eslint/unbound-method + const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; -"use strict"; + if (shouldHandleError(error)) { + (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { + // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, + // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't + // hurt to be sure + _scope.setSDKProcessingMetadata({ request: _req }); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__webpack_require__(1677)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); + // For some reason we need to set the transaction on the scope again + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const transaction = (res ).__sentry_transaction ; + if (transaction && _scope.getSpan() === undefined) { + _scope.setSpan(transaction); } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; + + const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); + if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { + // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the + // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only + // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be + // running in SessionAggregates mode + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; + if (isSessionAggregatesMode) { + const requestSession = _scope.getRequestSession(); + // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a + // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within + // the bounds of a request, and if so the status is updated + if (requestSession && requestSession.status !== undefined) { + requestSession.status = 'crashed'; } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); + } } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); + + const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + (res ).sentry = eventId; + next(error); + }); + + return; + } + + next(error); + }; } -exports["default"] = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map + +// TODO (v8 / #5257): Remove this +// eslint-disable-next-line deprecation/deprecation +; + + +//# sourceMappingURL=handlers.js.map + /***/ }), -/* 1688 */ +/* 1677 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "_nullishCoalesce": () => (/* binding */ _nullishCoalesce) +/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), +/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) /* harmony export */ }); +/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); + + /** - * Polyfill for the nullish coalescing operator (`??`). - * - * Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the - * LHS evaluates to a nullish value, to mimic the operator's short-circuiting behavior. + * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. + */ + +/** + * Normalizes data from the request object, accounting for framework differences. * - * Adapted from Sucrase (https://github.com/alangpierce/sucrase) + * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. * - * @param lhs The value of the expression to the left of the `??` - * @param rhsFn A function returning the value of the expression to the right of the `??` - * @returns The LHS value, unless it's `null` or `undefined`, in which case, the RHS value + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. + * @returns An object containing normalized request data */ -function _nullishCoalesce(lhs, rhsFn) { - // by checking for loose equality to `null`, we catch both `null` and `undefined` - return lhs != null ? lhs : rhsFn(); +function extractRequestData(req, keys) { + return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); } -// Sucrase version: -// function _nullishCoalesce(lhs, rhsFn) { -// if (lhs != null) { -// return lhs; -// } else { -// return rhsFn(); -// } -// } +/** + * Options deciding what parts of the request to use when enhancing an event + * + * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use + * `AddRequestDataToEventOptions` in `@sentry/utils` instead. + */ + +/** + * Enriches passed event with request data. + * + * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. + * + * @param event Will be mutated and enriched with req data + * @param req Request object + * @param options object containing flags to enable functionality + * @hidden + */ +function parseRequest(event, req, options = {}) { + return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); +} -//# sourceMappingURL=_nullishCoalesce.js.map +//# sourceMappingURL=requestDataDeprecated.js.map /***/ }), -/* 1689 */ +/* 1678 */ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "close": () => (/* binding */ close), -/* harmony export */ "defaultIntegrations": () => (/* binding */ defaultIntegrations), -/* harmony export */ "defaultStackParser": () => (/* binding */ defaultStackParser), -/* harmony export */ "flush": () => (/* binding */ flush), -/* harmony export */ "getSentryRelease": () => (/* binding */ getSentryRelease), -/* harmony export */ "init": () => (/* binding */ init), -/* harmony export */ "isAutoSessionTrackingEnabled": () => (/* binding */ isAutoSessionTrackingEnabled), -/* harmony export */ "lastEventId": () => (/* binding */ lastEventId) +/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), +/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) /* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(1711); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(1712); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(1670); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1713); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(1662); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(1644); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1665); -/* harmony import */ var _integrations_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1690); -/* harmony import */ var _module_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1709); -/* harmony import */ var _transports_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1673); -/* harmony import */ var _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1691); -/* harmony import */ var _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1693); -/* harmony import */ var _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1696); -/* harmony import */ var _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1698); -/* harmony import */ var _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1700); -/* harmony import */ var _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1703); -/* harmony import */ var _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1702); -/* harmony import */ var _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1704); -/* harmony import */ var _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1699); -/* harmony import */ var _transports_http_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1674); - - - - - - - - - - - - - - - - - - - -/* eslint-disable max-lines */ - -const defaultIntegrations = [ - // Common - new _sentry_core__WEBPACK_IMPORTED_MODULE_15__.InboundFilters(), - new _sentry_core__WEBPACK_IMPORTED_MODULE_16__.FunctionToString(), - // Native Wrappers - new _integrations_console_js__WEBPACK_IMPORTED_MODULE_5__.Console(), - new _integrations_http_js__WEBPACK_IMPORTED_MODULE_6__.Http(), - // Global Handlers - new _integrations_onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_7__.OnUncaughtException(), - new _integrations_onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_8__.OnUnhandledRejection(), - // Event Info - new _integrations_contextlines_js__WEBPACK_IMPORTED_MODULE_9__.ContextLines(), - new _integrations_context_js__WEBPACK_IMPORTED_MODULE_10__.Context(), - new _integrations_modules_js__WEBPACK_IMPORTED_MODULE_11__.Modules(), - new _integrations_requestdata_js__WEBPACK_IMPORTED_MODULE_12__.RequestData(), - // Misc - new _integrations_linkederrors_js__WEBPACK_IMPORTED_MODULE_13__.LinkedErrors(), -]; +const TRACEPARENT_REGEXP = new RegExp( + '^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$', // whitespace +); /** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` + * Extract transaction context data from a `sentry-trace` header. * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` + * @param traceparent Traceparent string * - * @see {@link NodeOptions} for documentation on configuration options. + * @returns Object containing data from the header, or undefined if traceparent string is malformed */ -function init(options = {}) { - const carrier = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getMainCarrier)(); - const autoloadedIntegrations = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([carrier, 'access', _ => _.__SENTRY__, 'optionalAccess', _2 => _2.integrations]) || []; - - options.defaultIntegrations = - options.defaultIntegrations === false - ? [] - : [ - ...(Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : defaultIntegrations), - ...autoloadedIntegrations, - ]; +function extractTraceparentData(traceparent) { + const matches = traceparent.match(TRACEPARENT_REGEXP); - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; + if (!traceparent || !matches) { + // empty string or no matches is invalid traceparent data + return undefined; } - if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { - const tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); - if (isFinite(tracesSampleRate)) { - options.tracesSampleRate = tracesSampleRate; - } + let parentSampled; + if (matches[3] === '1') { + parentSampled = true; + } else if (matches[3] === '0') { + parentSampled = false; } - if (options.release === undefined) { - const detectedRelease = getSentryRelease(); - if (detectedRelease !== undefined) { - options.release = detectedRelease; - } else { - // If release is not provided, then we should disable autoSessionTracking - options.autoSessionTracking = false; - } - } + return { + traceId: matches[1], + parentSampled, + parentSpanId: matches[2], + }; +} - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; - } - if (options.autoSessionTracking === undefined && options.dsn !== undefined) { - options.autoSessionTracking = true; - } +//# sourceMappingURL=tracing.js.map - if (options.instrumenter === undefined) { - options.instrumenter = 'sentry'; - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain__WEBPACK_IMPORTED_MODULE_0__.active) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.setHubOnCarrier)(carrier, (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)()); - } +/***/ }), +/* 1679 */ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - // TODO(v7): Refactor this to reduce the logic above - const clientOptions = { - ...options, - stackParser: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.stackParserFromStackParserOptions)(options.stackParser || defaultStackParser), - integrations: (0,_sentry_core__WEBPACK_IMPORTED_MODULE_20__.getIntegrationsToSetup)(options), - transport: options.transport || _transports_http_js__WEBPACK_IMPORTED_MODULE_14__.makeNodeTransport, - }; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), +/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) +/* harmony export */ }); +/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1673); +/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1672); - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_21__.initAndBind)(_client_js__WEBPACK_IMPORTED_MODULE_1__.NodeClient, clientOptions); - if (options.autoSessionTracking) { - startSessionTracking(); - } -} +//# sourceMappingURL=index.js.map -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().lastEventId(); -} -/** - * Call `flush()` on the current client, if there is one. See {@link Client.flush}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause - * the client to wait until all events are sent before resolving the promise. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). - */ -async function flush(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.flush(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events. No client defined.'); - return Promise.resolve(false); -} +/***/ }), +/* 1680 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// @ts-check +const { log } = __webpack_require__(1) /** - * Call `close()` on the current client, if there is one. See {@link Client.close}. - * - * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this - * parameter will cause the client to wait until all events are sent before disabling itself. - * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it - * doesn't (or if there's no client defined). + * Get daily data up to 36 months & P max + * @param {string} pointId + * @param {string} appLogin + * @param {string} startDate + * @param {string} endDate + * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType + * @param {'EA' | 'PA' | 'PMA'} unit + * @returns {string} */ -async function close(timeout) { - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)().getClient(); - if (client) { - return client.close(timeout); - } - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_22__.logger.warn('Cannot flush events and disable SDK. No client defined.'); - return Promise.resolve(false); +function consultationMesuresDetaillees( + pointId, + appLogin, + startDate, + endDate, + mesureType = 'ENERGIE', + unit = 'EA' +) { + log( + 'info', + `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterMesuresDetaillees> + <demande> + <initiateurLogin>${appLogin}</initiateurLogin> + <pointId>${pointId}</pointId> + <mesuresTypeCode>${mesureType}</mesuresTypeCode> + <grandeurPhysique>${unit}</grandeurPhysique> + <soutirage>true</soutirage> + <injection>false</injection> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <mesuresCorrigees>false</mesuresCorrigees> + <accordClient>true</accordClient> + </demande> + </v2:consulterMesuresDetaillees> + </soapenv:Body> + </soapenv:Envelope> + ` } /** - * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client + * Get user max power + * @param {string} pointId + * @param {string} appLogin + * @param {string} startDate + * @param {string} endDate + * @param {'COURBE' | 'ENERGIE' | 'PMAX'} mesureType + * @param {'EA' | 'PA' | 'PMA'} unit + * @returns {string} */ -function isAutoSessionTrackingEnabled(client) { - if (client === undefined) { - return false; - } - const clientOptions = client && client.getOptions(); - if (clientOptions && clientOptions.autoSessionTracking !== undefined) { - return clientOptions.autoSessionTracking; - } - return false; +function consultationMesuresDetailleesMaxPower( + pointId, + appLogin, + startDate, + endDate, + mesureType = 'PMAX', + unit = 'PMA' +) { + log( + 'info', + `Query consultationMesuresDetaillees - ${mesureType}/${unit} between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterMesuresDetaillees> + <demande> + <initiateurLogin>${appLogin}</initiateurLogin> + <pointId>${pointId}</pointId> + <mesuresTypeCode>${mesureType}</mesuresTypeCode> + <grandeurPhysique>${unit}</grandeurPhysique> + <soutirage>true</soutirage> + <injection>false</injection> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <mesuresPas>P1D</mesuresPas> + <mesuresCorrigees>false</mesuresCorrigees> + <accordClient>true</accordClient> + </demande> + </v2:consulterMesuresDetaillees> + </soapenv:Body> + </soapenv:Envelope> + ` } /** - * Returns a release dynamically from environment variables. + * Get user technical data (contract start date) + * @param {string} pointId + * @param {string} appLogin + * @returns {string} */ -function getSentryRelease(fallback) { - // Always read first as Sentry takes this as precedence - if (process.env.SENTRY_RELEASE) { - return process.env.SENTRY_RELEASE; - } - - // This supports the variable that sentry-webpack-plugin injects - if (_sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE && _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id) { - return _sentry_utils__WEBPACK_IMPORTED_MODULE_23__.GLOBAL_OBJ.SENTRY_RELEASE.id; - } - - return ( - // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables - process.env.GITHUB_SHA || - // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata - process.env.COMMIT_REF || - // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables - process.env.VERCEL_GIT_COMMIT_SHA || - process.env.VERCEL_GITHUB_COMMIT_SHA || - process.env.VERCEL_GITLAB_COMMIT_SHA || - process.env.VERCEL_BITBUCKET_COMMIT_SHA || - // Zeit (now known as Vercel) - process.env.ZEIT_GITHUB_COMMIT_SHA || - process.env.ZEIT_GITLAB_COMMIT_SHA || - process.env.ZEIT_BITBUCKET_COMMIT_SHA || - fallback - ); -} - -/** Node.js stack parser */ -const defaultStackParser = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.createStackParser)((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_19__.nodeStackLineParser)(_module_js__WEBPACK_IMPORTED_MODULE_3__.getModule)); +function consulterDonneesTechniquesContractuelles( + pointId, + appLogin, + consent = true +) { + log('info', `Query consulterDonneesTechniquesContractuelles`) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/consulterdonneestechniquescontractuelles/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:consulterDonneesTechniquesContractuelles> + <pointId>${pointId}</pointId> + <loginUtilisateur>${appLogin}</loginUtilisateur> + <autorisationClient>${consent}</autorisationClient> + </v2:consulterDonneesTechniquesContractuelles> + </soapenv:Body> + </soapenv:Envelope> + ` +} /** - * Enable automatic Session Tracking for the node process. + * Use rechercherPoint to find user PDL if exist + * @param {string} lastname + * @param {string} postalCode + * @param {string} inseeCode + * @param {string} address + * @param {string} [escalierEtEtageEtAppartement] + * @returns {string} PDL */ -function startSessionTracking() { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_17__.getCurrentHub)(); - hub.startSession(); - // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because - // The 'beforeExit' event is not emitted for conditions causing explicit termination, - // such as calling process.exit() or uncaught exceptions. - // Ref: https://nodejs.org/api/process.html#process_event_beforeexit - process.on('beforeExit', () => { - const session = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_18__._optionalChain)([hub, 'access', _3 => _3.getScope, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getSession, 'call', _6 => _6()]); - const terminalStates = ['exited', 'crashed']; - // Only call endSession, if the Session exists on Scope and SessionStatus is not a - // Terminal Status i.e. Exited or Crashed because - // "When a session is moved away from ok it must not be updated anymore." - // Ref: https://develop.sentry.dev/sdk/sessions/ - if (session && !terminalStates.includes(session.status)) hub.endSession(); - }); -} - - -//# sourceMappingURL=sdk.js.map - - -/***/ }), -/* 1690 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* reexport safe */ _console_js__WEBPACK_IMPORTED_MODULE_0__.Console), -/* harmony export */ "Http": () => (/* reexport safe */ _http_js__WEBPACK_IMPORTED_MODULE_1__.Http), -/* harmony export */ "OnUncaughtException": () => (/* reexport safe */ _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__.OnUncaughtException), -/* harmony export */ "OnUnhandledRejection": () => (/* reexport safe */ _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__.OnUnhandledRejection), -/* harmony export */ "LinkedErrors": () => (/* reexport safe */ _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__.LinkedErrors), -/* harmony export */ "Modules": () => (/* reexport safe */ _modules_js__WEBPACK_IMPORTED_MODULE_5__.Modules), -/* harmony export */ "ContextLines": () => (/* reexport safe */ _contextlines_js__WEBPACK_IMPORTED_MODULE_6__.ContextLines), -/* harmony export */ "Context": () => (/* reexport safe */ _context_js__WEBPACK_IMPORTED_MODULE_7__.Context), -/* harmony export */ "RequestData": () => (/* reexport safe */ _requestdata_js__WEBPACK_IMPORTED_MODULE_8__.RequestData) -/* harmony export */ }); -/* harmony import */ var _console_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1691); -/* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1693); -/* harmony import */ var _onuncaughtexception_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1696); -/* harmony import */ var _onunhandledrejection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1698); -/* harmony import */ var _linkederrors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1699); -/* harmony import */ var _modules_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1702); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1700); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1703); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1704); - - - - - - - - - -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 1691 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Console": () => (/* binding */ Console) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1692); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); - - - - -/** Console module integration */ -class Console {constructor() { Console.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Console';} - - /** - * @inheritDoc - */ - __init() {this.name = Console.id;} - - /** - * @inheritDoc - */ - setupOnce() { - for (const level of ['debug', 'info', 'warn', 'error', 'log']) { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.fill)(console, level, createConsoleWrapper(level)); - } +function rechercherPoint( + appLogin, + lastname, + postalCode, + inseeCode, + address, + escalierEtEtageEtAppartement +) { + log( + 'info', + `Query rechercherPoint - postal code : ${postalCode} / insee code: ${inseeCode}` + ) + if (escalierEtEtageEtAppartement) { + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherPoint> + <criteres> + <adresseInstallation> + <escalierEtEtageEtAppartement>${escalierEtEtageEtAppartement}</escalierEtEtageEtAppartement> + <numeroEtNomVoie>${address}</numeroEtNomVoie> + <codePostal>${postalCode}</codePostal> + <codeInseeCommune>${inseeCode}</codeInseeCommune> + </adresseInstallation> + <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> + <rechercheHorsPerimetre>true</rechercheHorsPerimetre> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherPoint> + </soapenv:Body> + </soapenv:Envelope>` } -} Console.__initStatic(); + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherPoint> + <criteres> + <adresseInstallation> + <numeroEtNomVoie>${address}</numeroEtNomVoie> + <codePostal>${postalCode}</codePostal> + <codeInseeCommune>${inseeCode}</codeInseeCommune> + </adresseInstallation> + <nomClientFinalOuDenominationSociale>${lastname}</nomClientFinalOuDenominationSociale> + <rechercheHorsPerimetre>true</rechercheHorsPerimetre> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherPoint> + </soapenv:Body> + </soapenv:Envelope>` +} /** - * Wrapper function that'll be used for every console level + * Search if user as a service + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @returns {*} */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - const sentryLevel = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.severityLevelFromString)(level); - - /* eslint-disable prefer-rest-params */ - return function () { - if ((0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(Console)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().addBreadcrumb( - { - category: 'console', - level: sentryLevel, - message: util__WEBPACK_IMPORTED_MODULE_0__.format.apply(undefined, arguments), - }, - { - input: [...arguments], - level, - }, - ); - } - - originalConsoleMethod.apply(this, arguments); - }; - /* eslint-enable prefer-rest-params */ - }; +function rechercherServicesSouscritsMesures(appLogin, contractId, pointId) { + log('info', `Query rechercherServicesSouscritsMesures`) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/rechercherservicessouscritsmesures/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:rechercherServicesSouscritsMesures> + <criteres> + <pointId>${pointId}</pointId> + <contratId>${contractId}</contratId> + </criteres> + <loginUtilisateur>${appLogin}</loginUtilisateur> + </v2:rechercherServicesSouscritsMesures> + </soapenv:Body> + </soapenv:Envelope>` } - -//# sourceMappingURL=console.js.map - - -/***/ }), -/* 1692 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "severityFromString": () => (/* binding */ severityFromString), -/* harmony export */ "severityLevelFromString": () => (/* binding */ severityLevelFromString), -/* harmony export */ "validSeverityLevels": () => (/* binding */ validSeverityLevels) -/* harmony export */ }); -// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either -// -// a) moving `validSeverityLevels` to `@sentry/types`, -// b) moving the`SeverityLevel` type here, or -// c) importing `validSeverityLevels` from here into `@sentry/types`. -// -// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would -// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the -// type, reminding anyone who changes it to change this list also, will have to do. - -const validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug']; - /** - * Converts a string-based level into a member of the deprecated {@link Severity} enum. - * - * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead. - * - * @param level String representation of Severity - * @returns Severity + * Activate half hour data collect for user + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @param {string} lastname + * @param {string} startDate + * @param {string} endDate + * @returns {*} */ -function severityFromString(level) { - return severityLevelFromString(level) ; +function commanderCollectePublicationMesures( + appLogin, + contractId, + pointId, + lastname, + startDate, + endDate +) { + log( + 'info', + `Query commanderCollectePublicationMesures - between ${startDate} and ${endDate}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/commandercollectepublicationmesures/v3.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:commanderCollectePublicationMesures> + <demande> + <donneesGenerales> + <objetCode>AME</objetCode> + <pointId>${pointId}</pointId> + <initiateurLogin>${appLogin}</initiateurLogin> + <contratId>${contractId}</contratId> + </donneesGenerales> + <accesMesures> + <dateDebut>${startDate}</dateDebut> + <dateFin>${endDate}</dateFin> + <declarationAccordClient> + <accord>true</accord> + <personnePhysique> + <nom>${lastname}</nom> + </personnePhysique> + </declarationAccordClient> + <mesuresTypeCode>CDC</mesuresTypeCode> + <soutirage>true</soutirage> + <injection>false</injection> + <mesuresPas>PT30M</mesuresPas> + <mesuresCorrigees>false</mesuresCorrigees> + <transmissionRecurrente>false</transmissionRecurrente> + <periodiciteTransmission>P1D</periodiciteTransmission> + </accesMesures> + </demande> + </v2:commanderCollectePublicationMesures> + </soapenv:Body> + </soapenv:Envelope>` } /** - * Converts a string-based level into a `SeverityLevel`, normalizing it along the way. - * - * @param level String representation of desired `SeverityLevel`. - * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level. + * Stop the user consent + * @param {string} appLogin + * @param {string} contractId + * @param {string} pointId + * @param {number} serviceSouscritId + * @returns {*} */ -function severityLevelFromString(level) { - return (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ; +function commanderArretServiceSouscritMesures( + appLogin, + contractId, + pointId, + serviceSouscritId +) { + log( + 'info', + `Query commanderArretServiceSouscritMesures - serviceSouscritId: ${serviceSouscritId}` + ) + return `<?xml version='1.0' encoding='utf-8'?> + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:v2="http://www.enedis.fr/sge/b2b/commanderarretservicesouscritmesures/v1.0" + xmlns:v1="http://www.enedis.fr/sge/b2b/technique/v1.0"> + <soapenv:Header/> + <soapenv:Body> + <v2:commanderArretServiceSouscritMesures> + <demande> + <donneesGenerales> + <objetCode>ASS</objetCode> + <pointId>${pointId}</pointId> + <initiateurLogin>${appLogin}</initiateurLogin> + <contratId>${contractId}</contratId> + </donneesGenerales> + <arretServiceSouscrit> + <serviceSouscritId>${serviceSouscritId}</serviceSouscritId> + </arretServiceSouscrit> + </demande> + </v2:commanderArretServiceSouscritMesures> + </soapenv:Body> + </soapenv:Envelope>` } - -//# sourceMappingURL=severity.js.map +module.exports = { + consulterDonneesTechniquesContractuelles, + consultationMesuresDetailleesMaxPower, + consultationMesuresDetaillees, + rechercherPoint, + rechercherServicesSouscritsMesures, + commanderCollectePublicationMesures, + commanderArretServiceSouscritMesures, +} /***/ }), -/* 1693 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Http": () => (/* binding */ Http) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1650); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1648); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1695); -/* harmony import */ var _utils_http_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1694); +/* 1681 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// @ts-check +const { log, errors } = __webpack_require__(1) +const { default: axios } = __webpack_require__(1682) +const Sentry = __webpack_require__(1600) +/** + * @param {string} pointID + * @param {string} lastname + * @param {string} firstname + * @param {string} address + * @param {string} postalCode + * @param {string} inseeCode + * @param {string} city + * @param {boolean} safetyOnBoarding + * @returns {Promise<Consent>} + */ +async function createBoConsent( + url, + token, + pointID, + lastname, + firstname, + address, + postalCode, + inseeCode, + city, + safetyOnBoarding +) { + log('info', `Query createBoConsent`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } + try { + const { data } = await axios.post( + `${url}/consent`, + { + pointID, + lastname, + firstname, + address, + postalCode, + inseeCode, + city, + safetyOnBoarding, + }, + headers + ) + return data + } catch (err) { + const errorMessage = 'Error while creating BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'createBoConsent', + }, + extra: { + pointID: pointID, + safetyOnBoarding: safetyOnBoarding, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} +/** + * @param {string} url + * @param {string} token + * @param {Consent} consent + * @param {string} serviceId + * @returns {Promise<Consent>} + */ +async function updateBoConsent(url, token, consent, serviceId) { + log('info', `Query updateBoConsent`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); + let consentId = '' + if (consent.ID) { + consentId = consent.ID.toString() + } + try { + const { data } = await axios.put( + `${url}/consent/${consentId}`, + { + ...consent, + serviceId: parseInt(serviceId), + }, + headers + ) + return data + } catch (err) { + const errorMessage = 'Error while updating BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'updateBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} /** - * The http module integration instruments Node's internal http module. It creates breadcrumbs, transactions for outgoing - * http requests and attaches trace data when tracing is enabled via its `tracing` option. + * @param {number} consentId + * @returns {Promise<Consent>} */ -class Http { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Http';} - - /** - * @inheritDoc - */ - __init() {this.name = Http.id;} +async function getBoConsent(url, token, consentId) { + log('info', `Query getBoConsent ${consentId}`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } + try { + const { data } = await axios.get(`${url}/consent/${consentId}`, headers) + return data + } catch (err) { + const errorMessage = 'Error while getting BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'getBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) + } +} - /** - * @inheritDoc - */ - constructor(options = {}) {;Http.prototype.__init.call(this); - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = !options.tracing ? undefined : options.tracing === true ? {} : options.tracing; +/** + * Delete BO consent + * @param {string} url + * @param {string} token + * @param {number} consentId + * @returns + */ +async function deleteBoConsent(url, token, consentId) { + log('info', `Query deleteBoConsent ${consentId}`) + const headers = { + headers: { + Authorization: `Bearer ${token}`, + }, + } + try { + const { data } = await axios.delete(`${url}/consent/${consentId}`, headers) + return data + } catch (err) { + const errorMessage = 'Error while deleting BO consent : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'deleteBoConsent', + }, + extra: { + consentId: consentId, + }, + }) + throw new Error(errors.MAINTENANCE) } +} - /** - * @inheritDoc - */ - setupOnce( - _addGlobalEventProcessor, - setupOnceGetCurrentHub, - ) { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } +module.exports = { + createBoConsent, + updateBoConsent, + getBoConsent, + deleteBoConsent, +} - const clientOptions = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([setupOnceGetCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getOptions, 'call', _5 => _5()]); - // Do not auto-instrument for other instrumenter - if (clientOptions && clientOptions.instrumenter !== 'sentry') { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log('HTTP Integration is skipped because of instrumenter configuration.'); - return; - } +/***/ }), +/* 1682 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // TODO (v8): `tracePropagationTargets` and `shouldCreateSpanForRequest` will be removed from clientOptions - // and we will no longer have to do this optional merge, we can just pass `this._tracing` directly. - const tracingOptions = this._tracing ? { ...clientOptions, ...this._tracing } : undefined; +module.exports = __webpack_require__(1683); - const wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, tracingOptions); +/***/ }), +/* 1683 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpModule = __webpack_require__(80); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpModule, 'request', wrappedHandlerMaker); +"use strict"; - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const httpsModule = __webpack_require__(81); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'get', wrappedHandlerMaker); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.fill)(httpsModule, 'request', wrappedHandlerMaker); - } - } -}Http.__initStatic(); -// for ease of reading below +var utils = __webpack_require__(1684); +var bind = __webpack_require__(1685); +var Axios = __webpack_require__(1686); +var mergeConfig = __webpack_require__(1714); +var defaults = __webpack_require__(1691); /** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * Create an instance of Axios * - * @returns A function which accepts the exiting handler and returns a wrapped handler + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios */ -function _createWrappedRequestMethodFactory( - breadcrumbsEnabled, - tracingOptions, -) { - // We're caching results so we don't have to recompute regexp every time we create a request. - const createSpanUrlMap = {}; - const headersUrlMap = {}; - - const shouldCreateSpan = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _6 => _6.shouldCreateSpanForRequest]) === undefined) { - return true; - } +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); - if (createSpanUrlMap[url]) { - return createSpanUrlMap[url]; - } + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); - createSpanUrlMap[url] = tracingOptions.shouldCreateSpanForRequest(url); + // Copy context to instance + utils.extend(instance, context); - return createSpanUrlMap[url]; + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; - const shouldAttachTraceData = (url) => { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([tracingOptions, 'optionalAccess', _7 => _7.tracePropagationTargets]) === undefined) { - return true; - } + return instance; +} - if (headersUrlMap[url]) { - return headersUrlMap[url]; - } +// Create the default instance to be exported +var axios = createInstance(defaults); - headersUrlMap[url] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.stringMatchesSomePattern)(url, tracingOptions.tracePropagationTargets); +// Expose Axios class to allow class inheritance +axios.Axios = Axios; - return headersUrlMap[url]; - }; +// Expose Cancel & CancelToken +axios.CanceledError = __webpack_require__(1704); +axios.CancelToken = __webpack_require__(1716); +axios.isCancel = __webpack_require__(1713); +axios.VERSION = (__webpack_require__(1709).version); +axios.toFormData = __webpack_require__(1695); - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod( ...args) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const httpModule = this; +// Expose AxiosError class +axios.AxiosError = __webpack_require__(1693); - const requestArgs = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.normalizeRequestArgs)(this, args); - const requestOptions = requestArgs[0]; - const requestUrl = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.extractUrl)(requestOptions); +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if ((0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.isSentryRequest)(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __webpack_require__(1717); - let requestSpan; - let parentSpan; +// Expose isAxiosError +axios.isAxiosError = __webpack_require__(1718); - const scope = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getScope(); +module.exports = axios; - if (scope && tracingOptions && shouldCreateSpan(requestUrl)) { - parentSpan = scope.getSpan(); +// Allow use of default import syntax in TypeScript +module.exports["default"] = axios; - if (parentSpan) { - requestSpan = parentSpan.startChild({ - description: `${requestOptions.method || 'GET'} ${requestUrl}`, - op: 'http.client', - }); - if (shouldAttachTraceData(requestUrl)) { - const sentryTraceHeader = requestSpan.toTraceparent(); - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to "${requestUrl}": `, - ); +/***/ }), +/* 1684 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - requestOptions.headers = { - ...requestOptions.headers, - 'sentry-trace': sentryTraceHeader, - }; +"use strict"; - if (parentSpan.transaction) { - const dynamicSamplingContext = parentSpan.transaction.getDynamicSamplingContext(); - const sentryBaggageHeader = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.dynamicSamplingContextToSentryBaggageHeader)(dynamicSamplingContext); - let newBaggageHeaderField; - if (!requestOptions.headers || !requestOptions.headers.baggage) { - newBaggageHeaderField = sentryBaggageHeader; - } else if (!sentryBaggageHeader) { - newBaggageHeaderField = requestOptions.headers.baggage; - } else if (Array.isArray(requestOptions.headers.baggage)) { - newBaggageHeaderField = [...requestOptions.headers.baggage, sentryBaggageHeader]; - } else { - // Type-cast explanation: - // Technically this the following could be of type `(number | string)[]` but for the sake of simplicity - // we say this is undefined behaviour, since it would not be baggage spec conform if the user did this. - newBaggageHeaderField = [requestOptions.headers.baggage, sentryBaggageHeader] ; - } +var bind = __webpack_require__(1685); - requestOptions.headers = { - ...requestOptions.headers, - // Setting a hader to `undefined` will crash in node so we only set the baggage header when it's defined - ...(newBaggageHeaderField && { baggage: newBaggageHeaderField }), - }; - } - } else { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_3__.logger.log( - `[Tracing] Not adding sentry-trace header to outgoing request (${requestUrl}) due to mismatching tracePropagationTargets option.`, - ); - } +// utils is a library of generic helper functions non-specific to axios - const transaction = parentSpan.transaction; - if (transaction) { - transaction.metadata.propagations++; - } - } - } +var toString = Object.prototype.toString; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function ( res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (requestSpan) { - if (res.statusCode) { - requestSpan.setHttpStatus(res.statusCode); - } - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const req = this; +// eslint-disable-next-line func-names +var kindOf = (function(cache) { + // eslint-disable-next-line func-names + return function(thing) { + var str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + }; +})(Object.create(null)); - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (requestSpan) { - requestSpan.setHttpStatus(500); - requestSpan.description = (0,_utils_http_js__WEBPACK_IMPORTED_MODULE_0__.cleanSpanDescription)(requestSpan.description, requestOptions, req); - requestSpan.finish(); - } - }); - }; +function kindOfTest(type) { + type = type.toLowerCase(); + return function isKindOf(thing) { + return kindOf(thing) === type; }; } /** - * Captures Breadcrumb based on provided request/response pair + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return Array.isArray(val); +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +var isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false */ -function addRequestBreadcrumb(event, url, req, res) { - if (!(0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().getIntegration(Http)) { - return; - } - - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_6__.getCurrentHub)().addBreadcrumb( - { - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url, - }, - type: 'http', - }, - { - event, - request: req, - response: res, - }, - ); +function isString(val) { + return typeof val === 'string'; } +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1694 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "cleanSpanDescription": () => (/* binding */ cleanSpanDescription), -/* harmony export */ "extractUrl": () => (/* binding */ extractUrl), -/* harmony export */ "isSentryRequest": () => (/* binding */ isSentryRequest), -/* harmony export */ "normalizeRequestArgs": () => (/* binding */ normalizeRequestArgs), -/* harmony export */ "urlToOptions": () => (/* binding */ urlToOptions) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_0__); +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (kindOf(val) !== 'object') { + return false; + } + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} +/** + * Determine if a value is a Date + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +var isDate = kindOfTest('Date'); +/** + * Determine if a value is a File + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFile = kindOfTest('File'); +/** + * Determine if a value is a Blob + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +var isBlob = kindOfTest('Blob'); -const NODE_VERSION = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.parseSemver)(process.versions.node); +/** + * Determine if a value is a FileList + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFileList = kindOfTest('FileList'); /** - * Checks whether given url points to Sentry server - * @param url url to verify + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false */ -function isSentryRequest(url) { - const dsn = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub, 'call', _ => _(), 'access', _2 => _2.getClient, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getDsn, 'call', _5 => _5()]); - return dsn ? url.includes(dsn.host) : false; +function isFunction(val) { + return toString.call(val) === '[object Function]'; } /** - * Assemble a URL to be used for breadcrumbs and spans. + * Determine if a value is a Stream * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false */ -function extractUrl(requestOptions) { - const protocol = requestOptions.protocol || ''; - const hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - const port = - !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : `:${requestOptions.port}`; - const path = requestOptions.path ? requestOptions.path : '/'; - - return `${protocol}//${hostname}${port}${path}`; +function isStream(val) { + return isObject(val) && isFunction(val.pipe); } /** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object + * Determine if a value is a FormData * - * @returns The cleaned description + * @param {Object} thing The value to test + * @returns {boolean} True if value is an FormData, otherwise false */ -function cleanSpanDescription( - description, - requestOptions, - request, -) { - // nothing to clean - if (!description) { - return description; - } - - // eslint-disable-next-line prefer-const - let [method, requestUrl] = description.split(' '); - - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(request ), 'optionalAccess', _6 => _6.agent, 'optionalAccess', _7 => _7.protocol]); // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); - } +function isFormData(thing) { + var pattern = '[object FormData]'; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || + toString.call(thing) === pattern || + (isFunction(thing.toString) && thing.toString() === pattern) + ); +} - // internal routes can end up starting with a triple slash rather than a single one - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([requestUrl, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9('///')])) { - requestUrl = requestUrl.slice(2); - } +/** + * Determine if a value is a URLSearchParams object + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +var isURLSearchParams = kindOfTest('URLSearchParams'); - return `${method} ${requestUrl}`; +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } -// the node types are missing a few properties which node's `urlToOptions` function spits out - /** - * Convert a URL object into a RequestOptions object. + * Determine if we're running in a standard browser environment * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' */ -function urlToOptions(url) { - const options = { - protocol: url.protocol, - hostname: - typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: `${url.pathname || ''}${url.search || ''}`, - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${url.username}:${url.password}`; +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; } - return options; + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); } /** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. + * Iterate over an Array or an Object invoking a function for each item. * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item */ -function normalizeRequestArgs( - httpModule, - requestArgs, -) { - let callback, requestOptions; - - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop() ; +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; } - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url__WEBPACK_IMPORTED_MODULE_0__.URL(requestArgs[0])); - } else if (requestArgs[0] instanceof url__WEBPACK_IMPORTED_MODULE_0__.URL) { - requestOptions = urlToOptions(requestArgs[0]); - } else { - requestOptions = requestArgs[0]; + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; } - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = { ...requestOptions, ...requestArgs[1] }; + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } } +} - // Figure out the protocol if it's currently missing - if (requestOptions.protocol === undefined) { - // Worst case we end up populating protocol with undefined, which it already is - /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ - - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // Because of that, we cannot rely on `httpModule` to provide us with valid protocol, - // as it will always return `http`, even when using `https` module. - // - // See test/integrations/http.test.ts for more details on Node <=v8 protocol issue. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _10 => _10.globalAgent]) ), 'optionalAccess', _11 => _11.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _12 => _12.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _13 => _13.protocol]); +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); } else { - requestOptions.protocol = - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions.agent ), 'optionalAccess', _14 => _14.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([(requestOptions._defaultAgent ), 'optionalAccess', _15 => _15.protocol]) || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([httpModule, 'optionalAccess', _16 => _16.globalAgent]) ), 'optionalAccess', _17 => _17.protocol]); + result[key] = val; } - /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any */ } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; - } else { - return [requestOptions]; + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); } + return result; } - -//# sourceMappingURL=http.js.map - - -/***/ }), -/* 1695 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BAGGAGE_HEADER_NAME": () => (/* binding */ BAGGAGE_HEADER_NAME), -/* harmony export */ "MAX_BAGGAGE_STRING_LENGTH": () => (/* binding */ MAX_BAGGAGE_STRING_LENGTH), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX), -/* harmony export */ "SENTRY_BAGGAGE_KEY_PREFIX_REGEX": () => (/* binding */ SENTRY_BAGGAGE_KEY_PREFIX_REGEX), -/* harmony export */ "baggageHeaderToDynamicSamplingContext": () => (/* binding */ baggageHeaderToDynamicSamplingContext), -/* harmony export */ "dynamicSamplingContextToSentryBaggageHeader": () => (/* binding */ dynamicSamplingContextToSentryBaggageHeader) -/* harmony export */ }); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1649); -/* harmony import */ var _logger_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); - - - -const BAGGAGE_HEADER_NAME = 'baggage'; - -const SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-'; - -const SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; - /** - * Max length of a serialized baggage string + * Extends object a by mutably adding to it the properties of object b. * - * https://www.w3.org/TR/baggage/#limits + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a */ -const MAX_BAGGAGE_STRING_LENGTH = 8192; +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} /** - * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values - * from it. + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * - * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks. - * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise. + * @param {string} content with BOM + * @return {string} content value without BOM */ -function baggageHeaderToDynamicSamplingContext( - // Very liberal definition of what any incoming header might look like - baggageHeader, -) { - if (!(0,_is_js__WEBPACK_IMPORTED_MODULE_0__.isString)(baggageHeader) && !Array.isArray(baggageHeader)) { - return undefined; - } - - // Intermediary object to store baggage key value pairs of incoming baggage headers on. - // It is later used to read Sentry-DSC-values from. - let baggageObject = {}; - - if (Array.isArray(baggageHeader)) { - // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it - baggageObject = baggageHeader.reduce((acc, curr) => { - const currBaggageObject = baggageHeaderToObject(curr); - return { - ...acc, - ...currBaggageObject, - }; - }, {}); - } else { - // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but - // this is how we choose to handle it) - if (!baggageHeader) { - return undefined; - } - - baggageObject = baggageHeaderToObject(baggageHeader); +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); } + return content; +} - // Read all "sentry-" prefixed values out of the baggage object and put it onto a dynamic sampling context object. - const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => { - if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { - const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); - acc[nonPrefixedKey] = value; - } - return acc; - }, {}); +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + */ - // Only return a dynamic sampling context object if there are keys in it. - // A keyless object means there were no sentry values on the header, which means that there is no DSC. - if (Object.keys(dynamicSamplingContext).length > 0) { - return dynamicSamplingContext ; - } else { - return undefined; - } +function inherits(constructor, superConstructor, props, descriptors) { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + props && Object.assign(constructor.prototype, props); } /** - * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-". - * - * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility - * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is - * `undefined` the function will return `undefined`. - * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext` - * was `undefined`, or if `dynamicSamplingContext` didn't contain any values. + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function} [filter] + * @returns {Object} */ -function dynamicSamplingContextToSentryBaggageHeader( - // this also takes undefined for convenience and bundle size in other places - dynamicSamplingContext, -) { - // Prefix all DSC keys with "sentry-" and put them into a new object - const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce( - (acc, [dscKey, dscValue]) => { - if (dscValue) { - acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue; + +function toFlatObject(sourceObj, destObj, filter) { + var props; + var i; + var prop; + var merged = {}; + + destObj = destObj || {}; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if (!merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; } - return acc; - }, - {}, - ); + } + sourceObj = Object.getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - return objectToBaggageHeader(sentryPrefixedDSC); + return destObj; } -/** - * Will parse a baggage header, which is a simple key-value map, into a flat object. - * - * @param baggageHeader The baggage header to parse. - * @returns a flat object containing all the key-value pairs from `baggageHeader`. +/* + * determines whether a string ends with the characters of a specified string + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * @returns {boolean} */ -function baggageHeaderToObject(baggageHeader) { - return baggageHeader - .split(',') - .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim()))) - .reduce((acc, [key, value]) => { - acc[key] = value; - return acc; - }, {}); +function endsWith(str, searchString, position) { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + var lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; } + /** - * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs. - * - * @param object The object to turn into a baggage header. - * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header - * is not spec compliant. + * Returns new array from array like object + * @param {*} [thing] + * @returns {Array} */ -function objectToBaggageHeader(object) { - if (Object.keys(object).length === 0) { - // An empty baggage header is not spec compliant: We return undefined. - return undefined; +function toArray(thing) { + if (!thing) return null; + var i = thing.length; + if (isUndefined(i)) return null; + var arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; } - - return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => { - const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`; - const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`; - if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _logger_js__WEBPACK_IMPORTED_MODULE_1__.logger.warn( - `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`, - ); - return baggageHeader; - } else { - return newBaggageHeader; - } - }, ''); + return arr; } +// eslint-disable-next-line func-names +var isTypedArray = (function(TypedArray) { + // eslint-disable-next-line func-names + return function(thing) { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); -//# sourceMappingURL=baggage.js.map +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM, + inherits: inherits, + toFlatObject: toFlatObject, + kindOf: kindOf, + kindOfTest: kindOfTest, + endsWith: endsWith, + toArray: toArray, + isTypedArray: isTypedArray, + isFileList: isFileList +}; /***/ }), -/* 1696 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1685 */ +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUncaughtException": () => (/* binding */ OnUncaughtException) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + +/***/ }), +/* 1686 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** Global Exception handler */ -class OnUncaughtException { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUncaughtException';} +"use strict"; - /** - * @inheritDoc - */ - __init() {this.name = OnUncaughtException.id;} - /** - * @inheritDoc - */ - __init2() {this.handler = this._makeErrorHandler();} +var utils = __webpack_require__(1684); +var buildURL = __webpack_require__(1687); +var InterceptorManager = __webpack_require__(1688); +var dispatchRequest = __webpack_require__(1689); +var mergeConfig = __webpack_require__(1714); +var buildFullPath = __webpack_require__(1699); +var validator = __webpack_require__(1715); - // CAREFUL: Please think twice before updating the way _options looks because the Next.js SDK depends on it in `index.server.ts` +var validators = validator.validators; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} - /** - * @inheritDoc - */ - constructor(options = {}) {;OnUncaughtException.prototype.__init.call(this);OnUncaughtException.prototype.__init2.call(this); - this._options = { - exitEvenIfOtherHandlersAreRegistered: true, - ...options, - }; +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; } - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('uncaughtException', this.handler); + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; } - /** - * @hidden - */ - _makeErrorHandler() { - const timeout = 2000; - let caughtFirstError = false; - let caughtSecondError = false; - let calledFatalError = false; - let firstError; + var transitional = config.transitional; - return (error) => { - let onFatalError = _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess; - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)().getClient(); + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } - if (this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = this._options.onFatalError; - } else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError ; - } + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } - // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not - // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust - // exit behaviour of the SDK accordingly: - // - If other listeners are attached, do not exit. - // - If the only listener attached is ours, exit. - const userProvidedListenersCount = global.process - .listeners('uncaughtException') - .reduce((acc, listener) => { - if ( - listener.name === 'domainUncaughtExceptionClear' || // as soon as we're using domains this listener is attached by node itself - listener === this.handler // filter the handler we registered ourselves) - ) { - return acc; - } else { - return acc + 1; - } - }, 0); + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - const processWouldExit = userProvidedListenersCount === 0; - const shouldApplyFatalHandlingLogic = this._options.exitEvenIfOtherHandlersAreRegistered || processWouldExit; + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); - if (!caughtFirstError) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); + var promise; - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; - if (hub.getIntegration(OnUncaughtException)) { - hub.withScope((scope) => { - scope.setLevel('fatal'); - hub.captureException(error, { - originalException: error, - data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, - }); - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - }); - } else { - if (!calledFatalError && shouldApplyFatalHandlingLogic) { - calledFatalError = true; - onFatalError(error); - } - } - } else { - if (shouldApplyFatalHandlingLogic) { - if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_2__.logger.warn( - 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown', - ); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(error); - } else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(() => { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - } - } - }; - } -} OnUncaughtException.__initStatic(); + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } -//# sourceMappingURL=onuncaughtexception.js.map + return promise; + } -/***/ }), -/* 1697 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "logAndExitProcess": () => (/* binding */ logAndExitProcess) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1653); + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + } + return promise; +}; -const DEFAULT_SHUTDOWN_TIMEOUT = 2000; +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + var fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); +}; -/** - * @hidden - */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_0__.getCurrentHub)().getClient(); +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ - if (client === undefined) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url: url, + data: data + })); + }; } - const options = client.getOptions(); - const timeout = - (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - client.close(timeout).then( - (result) => { - if (!result) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - }, - error => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_1__.logger.error(error); - }, - ); -} + Axios.prototype[method] = generateHTTPMethod(); + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); -//# sourceMappingURL=errorhandling.js.map +module.exports = Axios; /***/ }), -/* 1698 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1687 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "OnUnhandledRejection": () => (/* binding */ OnUnhandledRejection) -/* harmony export */ }); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1653); -/* harmony import */ var _utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1697); +var utils = __webpack_require__(1684); +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} -/** Global Promise Rejection handler */ -class OnUnhandledRejection { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'OnUnhandledRejection';} - - /** - * @inheritDoc - */ - __init() {this.name = OnUnhandledRejection.id;} +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } - /** - * @inheritDoc - */ - constructor( - _options + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; - = { mode: 'warn' }, - ) {;this._options = _options;OnUnhandledRejection.prototype.__init.call(this);} + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } - /** - * @inheritDoc - */ - setupOnce() { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - } + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - sendUnhandledPromise(reason, promise) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - if (hub.getIntegration(OnUnhandledRejection)) { - hub.withScope((scope) => { - scope.setExtra('unhandledPromiseRejection', true); - hub.captureException(reason, { - originalException: promise, - data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, - }); + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); }); - } - this._handleRejection(reason); - } + }); - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _handleRejection(reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - const rejectionWarning = - 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; + serializedParams = parts.join('&'); + } - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); - } else if (this._options.mode === 'strict') { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.consoleSandbox)(() => { - console.warn(rejectionWarning); - }); - (0,_utils_errorhandling_js__WEBPACK_IMPORTED_MODULE_0__.logAndExitProcess)(reason); + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); } - /* eslint-enable no-console */ - } -} OnUnhandledRejection.__initStatic(); + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } -//# sourceMappingURL=onunhandledrejection.js.map + return url; +}; /***/ }), -/* 1699 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1688 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "LinkedErrors": () => (/* binding */ LinkedErrors) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1641); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1640); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1652); -/* harmony import */ var _eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1666); -/* harmony import */ var _contextlines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1700); +var utils = __webpack_require__(1684); +function InterceptorManager() { + this.handlers = []; +} +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; +}; +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; -const DEFAULT_KEY = 'cause'; -const DEFAULT_LIMIT = 5; +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; -/** Adds SDK info to an event. */ -class LinkedErrors { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'LinkedErrors';} +module.exports = InterceptorManager; - /** - * @inheritDoc - */ - __init() {this.name = LinkedErrors.id;} - /** - * @inheritDoc - */ +/***/ }), +/* 1689 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - /** - * @inheritDoc - */ +"use strict"; - /** - * @inheritDoc - */ - constructor(options = {}) {;LinkedErrors.prototype.__init.call(this); - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; + +var utils = __webpack_require__(1684); +var transformData = __webpack_require__(1690); +var isCancel = __webpack_require__(1713); +var defaults = __webpack_require__(1691); +var CanceledError = __webpack_require__(1704); + +/** + * Throws a `CanceledError` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); } - /** - * @inheritDoc - */ - setupOnce() { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_2__.addGlobalEventProcessor)(async (event, hint) => { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)(); - const self = hub.getIntegration(LinkedErrors); - const client = hub.getClient(); - if (client && self && self._handler && typeof self._handler === 'function') { - await self._handler(client.getOptions().stackParser, event, hint); - } - return event; - }); + if (config.signal && config.signal.aborted) { + throw new CanceledError(); } +} - /** - * @inheritDoc - */ - _handler(stackParser, event, hint) { - if (!event.exception || !event.exception.values || !(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(hint.originalException, Error)) { - return (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_5__.resolvedSyncPromise)(event); - } +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); - return new _sentry_utils__WEBPACK_IMPORTED_MODULE_5__.SyncPromise(resolve => { - void this._walkErrorTree(stackParser, hint.originalException , this._key) - .then((linkedErrors) => { - if (event && event.exception && event.exception.values) { - event.exception.values = [...linkedErrors, ...event.exception.values]; - } - resolve(event); - }) - .then(null, () => { - resolve(event); - }); - }); - } + // Ensure headers exist + config.headers = config.headers || {}; - /** - * @inheritDoc - */ - async _walkErrorTree( - stackParser, - error, - key, - stack = [], - ) { - if (!(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.isInstanceOf)(error[key], Error) || stack.length + 1 >= this._limit) { - return Promise.resolve(stack); - } + // Transform request data + config.data = transformData.call( + config, + config.data, + config.headers, + config.transformRequest + ); - const exception = (0,_eventbuilder_js__WEBPACK_IMPORTED_MODULE_0__.exceptionFromError)(stackParser, error[key]); + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); - // If the ContextLines integration is enabled, we add source code context to linked errors - // because we can't guarantee the order that integrations are run. - const contextLines = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_3__.getCurrentHub)().getIntegration(_contextlines_js__WEBPACK_IMPORTED_MODULE_1__.ContextLines); - if (contextLines && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_6__._optionalChain)([exception, 'access', _ => _.stacktrace, 'optionalAccess', _2 => _2.frames])) { - await contextLines.addSourceContextToFrames(exception.stacktrace.frames); + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; } + ); - return new Promise((resolve, reject) => { - void this._walkErrorTree(stackParser, error[key], key, [exception, ...stack]) - .then(resolve) - .then(null, () => { - reject(); - }); - }); - } -}LinkedErrors.__initStatic(); + var adapter = config.adapter || defaults.adapter; + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); -//# sourceMappingURL=linkederrors.js.map + // Transform response data + response.data = transformData.call( + config, + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; /***/ }), -/* 1700 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1690 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "ContextLines": () => (/* binding */ ContextLines), -/* harmony export */ "resetFileContentCache": () => (/* binding */ resetFileContentCache) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1647); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1701); -/* harmony import */ var lru_map__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lru_map__WEBPACK_IMPORTED_MODULE_1__); +var utils = __webpack_require__(1684); +var defaults = __webpack_require__(1691); +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + var context = this || defaults; + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); + return data; +}; -const FILE_CONTENT_CACHE = new lru_map__WEBPACK_IMPORTED_MODULE_1__.LRUMap(100); -const DEFAULT_LINES_OF_CONTEXT = 7; -// TODO: Replace with promisify when minimum supported node >= v8 -function readTextFileAsync(path) { - return new Promise((resolve, reject) => { - (0,fs__WEBPACK_IMPORTED_MODULE_0__.readFile)(path, 'utf8', (err, data) => { - if (err) reject(err); - else resolve(data); - }); - }); -} +/***/ }), +/* 1691 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Resets the file cache. Exists for testing purposes. - * @hidden - */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} +"use strict"; -/** Add node modules / packages to the event */ -class ContextLines { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'ContextLines';} - /** - * @inheritDoc - */ - __init() {this.name = ContextLines.id;} +var utils = __webpack_require__(1684); +var normalizeHeaderName = __webpack_require__(1692); +var AxiosError = __webpack_require__(1693); +var transitionalDefaults = __webpack_require__(1694); +var toFormData = __webpack_require__(1695); - constructor( _options = {}) {;this._options = _options;ContextLines.prototype.__init.call(this);} +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; - /** Get's the number of context lines to add */ - get _contextLines() { - return this._options.frameContextLines !== undefined ? this._options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; } +} - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addSourceContext(event)); +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __webpack_require__(1696); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __webpack_require__(1706); } + return adapter; +} - /** Processes an event and adds context lines */ - async addSourceContext(event) { - if (this._contextLines > 0 && (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) { - for (const exception of event.exception.values) { - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_2__._optionalChain)([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) { - await this.addSourceContextToFrames(exception.stacktrace.frames); - } +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; } } - - return event; } - /** Adds context lines to frames */ - async addSourceContextToFrames(frames) { - const contextLines = this._contextLines; + return (encoder || JSON.stringify)(rawValue); +} - for (const frame of frames) { - // Only add context if we have a filename and it hasn't already been added - if (frame.filename && frame.context_line === undefined) { - const sourceFile = await _readSourceFile(frame.filename); +var defaults = { - if (sourceFile) { - try { - const lines = sourceFile.split('\n'); - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.addContextToFrame)(lines, frame, contextLines); - } catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - } - } - } -}ContextLines.__initStatic(); + transitional: transitionalDefaults, -/** - * Reads file contents and caches them in a global LRU cache. - * - * @param filename filepath to read content from. - */ -async function _readSourceFile(filename) { - const cachedFile = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cachedFile !== undefined) { - return cachedFile; - } + adapter: getDefaultAdapter(), - let content = null; - try { - content = await readTextFileAsync(filename); - } catch (_) { - // - } + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); - FILE_CONTENT_CACHE.set(filename, content); - return content; -} + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + var isObjectPayload = utils.isObject(data); + var contentType = headers && headers['Content-Type']; -//# sourceMappingURL=contextlines.js.map + var isFileList; + if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { + var _FormData = this.env && this.env.FormData; + return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); + } else if (isObjectPayload || contentType === 'application/json') { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } -/***/ }), -/* 1701 */ -/***/ (function(module, exports, __webpack_require__) { + return data; + }], -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/** - * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most - * recently used items while discarding least recently used items when its limit - * is reached. - * - * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/> - * See README.md for details. - * - * Illustration of the design: - * - * entry entry entry entry - * ______ ______ ______ ______ - * | head |.newer => | |.newer => | |.newer => | tail | - * | A | | B | | C | | D | - * |______| <= older.|______| <= older.|______| <= older.|______| - * - * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added - */ -(function(g,f){ - const e = true ? exports : 0; - f(e); - if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (e), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } -})(this, function(exports) { + transformResponse: [function transformResponse(data) { + var transitional = this.transitional || defaults.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; -const NEWER = Symbol('newer'); -const OLDER = Symbol('older'); + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } -function LRUMap(limit, entries) { - if (typeof limit !== 'number') { - // called as (entries) - entries = limit; - limit = 0; - } + return data; + }], - this.size = 0; - this.limit = limit; - this.oldest = this.newest = undefined; - this._keymap = new Map(); + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, - if (entries) { - this.assign(entries); - if (limit < 1) { - this.limit = this.size; - } - } -} + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', -exports.LRUMap = LRUMap; + maxContentLength: -1, + maxBodyLength: -1, -function Entry(key, value) { - this.key = key; - this.value = value; - this[NEWER] = undefined; - this[OLDER] = undefined; -} + env: { + FormData: __webpack_require__(1710) + }, + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, -LRUMap.prototype._markEntryAsUsed = function(entry) { - if (entry === this.newest) { - // Already the most recenlty used entry, so no need to update the list - return; - } - // HEAD--------------TAIL - // <.older .newer> - // <--- add direction -- - // A B C <D> E - if (entry[NEWER]) { - if (entry === this.oldest) { - this.oldest = entry[NEWER]; + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' } - entry[NEWER][OLDER] = entry[OLDER]; // C <-- E. - } - if (entry[OLDER]) { - entry[OLDER][NEWER] = entry[NEWER]; // C. --> E } - entry[NEWER] = undefined; // D --x - entry[OLDER] = this.newest; // D. --> E - if (this.newest) { - this.newest[NEWER] = entry; // E. <-- D - } - this.newest = entry; }; -LRUMap.prototype.assign = function(entries) { - let entry, limit = this.limit || Number.MAX_VALUE; - this._keymap.clear(); - let it = entries[Symbol.iterator](); - for (let itv = it.next(); !itv.done; itv = it.next()) { - let e = new Entry(itv.value[0], itv.value[1]); - this._keymap.set(e.key, e); - if (!entry) { - this.oldest = e; - } else { - entry[NEWER] = e; - e[OLDER] = entry; - } - entry = e; - if (limit-- == 0) { - throw new Error('overflow'); - } - } - this.newest = entry; - this.size = this._keymap.size; -}; +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); -LRUMap.prototype.get = function(key) { - // First, find our cache entry - var entry = this._keymap.get(key); - if (!entry) return; // Not cached. Sorry. - // As <key> was found in the cache, register it as being requested recently - this._markEntryAsUsed(entry); - return entry.value; -}; +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); -LRUMap.prototype.set = function(key, value) { - var entry = this._keymap.get(key); +module.exports = defaults; - if (entry) { - // update existing - entry.value = value; - this._markEntryAsUsed(entry); - return this; - } - // new entry - this._keymap.set(key, (entry = new Entry(key, value))); +/***/ }), +/* 1692 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (this.newest) { - // link previous tail to the new tail (entry) - this.newest[NEWER] = entry; - entry[OLDER] = this.newest; - } else { - // we're first in -- yay - this.oldest = entry; - } +"use strict"; - // add new entry to the end of the linked list -- it's now the freshest entry. - this.newest = entry; - ++this.size; - if (this.size > this.limit) { - // we hit the limit -- remove the head - this.shift(); - } - return this; -}; +var utils = __webpack_require__(1684); -LRUMap.prototype.shift = function() { - // todo: handle special case when limit == 1 - var entry = this.oldest; - if (entry) { - if (this.oldest[NEWER]) { - // advance the list - this.oldest = this.oldest[NEWER]; - this.oldest[OLDER] = undefined; - } else { - // the cache is exhausted - this.oldest = undefined; - this.newest = undefined; +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; } - // Remove last strong reference to <entry> and remove links from the purged - // entry being returned: - entry[NEWER] = entry[OLDER] = undefined; - this._keymap.delete(entry.key); - --this.size; - return [entry.key, entry.value]; - } -}; - -// ---------------------------------------------------------------------------- -// Following code is optional and can be removed without breaking the core -// functionality. - -LRUMap.prototype.find = function(key) { - let e = this._keymap.get(key); - return e ? e.value : undefined; -}; - -LRUMap.prototype.has = function(key) { - return this._keymap.has(key); + }); }; -LRUMap.prototype['delete'] = function(key) { - var entry = this._keymap.get(key); - if (!entry) return; - this._keymap.delete(entry.key); - if (entry[NEWER] && entry[OLDER]) { - // relink the older entry with the newer entry - entry[OLDER][NEWER] = entry[NEWER]; - entry[NEWER][OLDER] = entry[OLDER]; - } else if (entry[NEWER]) { - // remove the link to us - entry[NEWER][OLDER] = undefined; - // link the newer entry to head - this.oldest = entry[NEWER]; - } else if (entry[OLDER]) { - // remove the link to us - entry[OLDER][NEWER] = undefined; - // link the newer entry to head - this.newest = entry[OLDER]; - } else {// if(entry[OLDER] === undefined && entry.newer === undefined) { - this.oldest = this.newest = undefined; - } - this.size--; - return entry.value; -}; +/***/ }), +/* 1693 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -LRUMap.prototype.clear = function() { - // Not clearing links should be safe, as we don't expose live links to user - this.oldest = this.newest = undefined; - this.size = 0; - this._keymap.clear(); -}; +"use strict"; -function EntryIterator(oldestEntry) { this.entry = oldestEntry; } -EntryIterator.prototype[Symbol.iterator] = function() { return this; } -EntryIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: [ent.key, ent.value] }; - } else { - return { done: true, value: undefined }; - } -}; +var utils = __webpack_require__(1684); +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); +} -function KeyIterator(oldestEntry) { this.entry = oldestEntry; } -KeyIterator.prototype[Symbol.iterator] = function() { return this; } -KeyIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.key }; - } else { - return { done: true, value: undefined }; +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; } -}; +}); -function ValueIterator(oldestEntry) { this.entry = oldestEntry; } -ValueIterator.prototype[Symbol.iterator] = function() { return this; } -ValueIterator.prototype.next = function() { - let ent = this.entry; - if (ent) { - this.entry = ent[NEWER]; - return { done: false, value: ent.value }; - } else { - return { done: true, value: undefined }; - } -}; +var prototype = AxiosError.prototype; +var descriptors = {}; +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED' +// eslint-disable-next-line func-names +].forEach(function(code) { + descriptors[code] = {value: code}; +}); -LRUMap.prototype.keys = function() { - return new KeyIterator(this.oldest); -}; +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, 'isAxiosError', {value: true}); -LRUMap.prototype.values = function() { - return new ValueIterator(this.oldest); -}; +// eslint-disable-next-line func-names +AxiosError.from = function(error, code, config, request, response, customProps) { + var axiosError = Object.create(prototype); -LRUMap.prototype.entries = function() { - return this; -}; + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }); -LRUMap.prototype[Symbol.iterator] = function() { - return new EntryIterator(this.oldest); -}; + AxiosError.call(axiosError, error.message, code, config, request, response); -LRUMap.prototype.forEach = function(fun, thisObj) { - if (typeof thisObj !== 'object') { - thisObj = this; - } - let entry = this.oldest; - while (entry) { - fun.call(thisObj, entry.value, entry.key, this); - entry = entry[NEWER]; - } -}; + axiosError.name = error.name; -/** Returns a JSON (array) representation */ -LRUMap.prototype.toJSON = function() { - var s = new Array(this.size), i = 0, entry = this.oldest; - while (entry) { - s[i++] = { key: entry.key, value: entry.value }; - entry = entry[NEWER]; - } - return s; -}; + customProps && Object.assign(axiosError, customProps); -/** Returns a String representation */ -LRUMap.prototype.toString = function() { - var s = '', entry = this.oldest; - while (entry) { - s += String(entry.key)+':'+entry.value; - entry = entry[NEWER]; - if (entry) { - s += ' < '; - } - } - return s; + return axiosError; }; -}); +module.exports = AxiosError; /***/ }), -/* 1702 */ -/***/ ((module, __webpack_exports__, __webpack_require__) => { +/* 1694 */ +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Modules": () => (/* binding */ Modules) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); +module.exports = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; -let moduleCache; -/** Extract information about paths */ -function getPaths() { - try { - return __webpack_require__.c ? Object.keys(__webpack_require__.c ) : []; - } catch (e) { - return []; - } -} +/***/ }), +/* 1695 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** Extract information about package.json modules */ -function collectModules() +"use strict"; - { - const mainPaths = (__webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].paths) || []; - const paths = getPaths(); - const infos - = {}; - const seen +var utils = __webpack_require__(1684); - = {}; +/** + * Convert a data object to FormData + * @param {Object} obj + * @param {?Object} [formData] + * @returns {Object} + **/ - paths.forEach(path => { - let dir = path; +function toFormData(obj, formData) { + // eslint-disable-next-line no-param-reassign + formData = formData || new FormData(); - /** Traverse directories upward in the search of package.json file */ - const updir = () => { - const orig = dir; - dir = (0,path__WEBPACK_IMPORTED_MODULE_1__.dirname)(orig); + var stack = []; - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } + function convertValue(value) { + if (value === null) return ''; - const pkgfile = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(orig, 'package.json'); - seen[orig] = true; + if (utils.isDate(value)) { + return value.toISOString(); + } - if (!(0,fs__WEBPACK_IMPORTED_MODULE_0__.existsSync)(pkgfile)) { - return updir(); - } + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } - try { - const info = JSON.parse((0,fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync)(pkgfile, 'utf8')) + return value; + } -; - infos[info.name] = info.version; - } catch (_oO) { - // no-empty + function build(data, parentKey) { + if (utils.isPlainObject(data) || utils.isArray(data)) { + if (stack.indexOf(data) !== -1) { + throw Error('Circular reference detected in ' + parentKey); } - }; - updir(); - }); - - return infos; -} + stack.push(data); -/** Add node modules / packages to the event */ -class Modules {constructor() { Modules.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Modules';} + utils.forEach(data, function each(value, key) { + if (utils.isUndefined(value)) return; + var fullKey = parentKey ? parentKey + '.' + key : key; + var arr; - /** - * @inheritDoc - */ - __init() {this.name = Modules.id;} + if (value && !parentKey && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { + // eslint-disable-next-line func-names + arr.forEach(function(el) { + !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); + }); + return; + } + } - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - addGlobalEventProcessor(event => { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return { - ...event, - modules: { - ...event.modules, - ...this._getModules(), - }, - }; - }); - } + build(value, fullKey); + }); - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - _getModules() { - if (!moduleCache) { - moduleCache = collectModules(); + stack.pop(); + } else { + formData.append(parentKey, convertValue(data)); } - return moduleCache; } -} Modules.__initStatic(); - - -//# sourceMappingURL=modules.js.map - - -/***/ }), -/* 1703 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Context": () => (/* binding */ Context), -/* harmony export */ "getDeviceContext": () => (/* binding */ getDeviceContext), -/* harmony export */ "readDirAsync": () => (/* binding */ readDirAsync), -/* harmony export */ "readFileAsync": () => (/* binding */ readFileAsync) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(846); -/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(253); -/* harmony import */ var os__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(os__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(64); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); - + build(obj); + return formData; +} +module.exports = toFormData; +/***/ }), +/* 1696 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// TODO: Required until we drop support for Node v8 -const readFileAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readFile); -const readDirAsync = (0,util__WEBPACK_IMPORTED_MODULE_4__.promisify)(fs__WEBPACK_IMPORTED_MODULE_1__.readdir); - -/** Add node modules / packages to the event */ -class Context { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'Context';} - - /** - * @inheritDoc - */ - __init() {this.name = Context.id;} - - /** - * Caches context so it's only evaluated once - */ - - constructor( _options = { app: true, os: true, device: true, culture: true }) {;this._options = _options;Context.prototype.__init.call(this); - // - } - - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor) { - addGlobalEventProcessor(event => this.addContext(event)); - } +"use strict"; - /** Processes an event and adds context */ - async addContext(event) { - if (this._cachedContext === undefined) { - this._cachedContext = this._getContexts(); - } - const updatedContext = this._updateContext(await this._cachedContext); +var utils = __webpack_require__(1684); +var settle = __webpack_require__(1697); +var cookies = __webpack_require__(1698); +var buildURL = __webpack_require__(1687); +var buildFullPath = __webpack_require__(1699); +var parseHeaders = __webpack_require__(1702); +var isURLSameOrigin = __webpack_require__(1703); +var transitionalDefaults = __webpack_require__(1694); +var AxiosError = __webpack_require__(1693); +var CanceledError = __webpack_require__(1704); +var parseProtocol = __webpack_require__(1705); - event.contexts = { - ...event.contexts, - app: { ...updatedContext.app, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _ => _.contexts, 'optionalAccess', _2 => _2.app]) }, - os: { ...updatedContext.os, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _3 => _3.contexts, 'optionalAccess', _4 => _4.os]) }, - device: { ...updatedContext.device, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _5 => _5.contexts, 'optionalAccess', _6 => _6.device]) }, - culture: { ...updatedContext.culture, ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([event, 'access', _7 => _7.contexts, 'optionalAccess', _8 => _8.culture]) }, - }; +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + var responseType = config.responseType; + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } - return event; - } + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } - /** - * Updates the context with dynamic values that can change - */ - _updateContext(contexts) { - // Only update properties if they exist - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _9 => _9.app, 'optionalAccess', _10 => _10.app_memory])) { - contexts.app.app_memory = process.memoryUsage().rss; + if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { + delete requestHeaders['Content-Type']; // Let the browser set it } - if ((0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([contexts, 'optionalAccess', _11 => _11.device, 'optionalAccess', _12 => _12.free_memory])) { - contexts.device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } - return contexts; - } + var fullPath = buildFullPath(config.baseURL, config.url); - /** - * Gets the contexts for the current environment - */ - async _getContexts() { - const contexts = {}; + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - if (this._options.os) { - contexts.os = await getOsContext(); - } + // Set the request timeout in MS + request.timeout = config.timeout; - if (this._options.app) { - contexts.app = getAppContext(); + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; } - if (this._options.device) { - contexts.device = getDeviceContext(this._options.device); + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; } - if (this._options.culture) { - const culture = getCultureContext(); + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } - if (culture) { - contexts.culture = culture; + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + var transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; } - } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); - return contexts; - } -}Context.__initStatic(); + // Clean up request + request = null; + }; -/** - * Returns the operating system context. - * - * Based on the current platform, this uses a different strategy to provide the - * most accurate OS information. Since this might involve spawning subprocesses - * or accessing the file system, this should only be executed lazily and cached. - * - * - On macOS (Darwin), this will execute the `sw_vers` utility. The context - * has a `name`, `version`, `build` and `kernel_version` set. - * - On Linux, this will try to load a distribution release from `/etc` and set - * the `name`, `version` and `kernel_version` fields. - * - On all other platforms, only a `name` and `version` will be returned. Note - * that `version` might actually be the kernel version. - */ -async function getOsContext() { - const platformId = os__WEBPACK_IMPORTED_MODULE_2__.platform(); - switch (platformId) { - case 'darwin': - return getDarwinInfo(); - case 'linux': - return getLinuxInfo(); - default: - return { - name: PLATFORM_NAMES[platformId] || platformId, - version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - }; - } -} + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; -function getCultureContext() { - try { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (typeof (process.versions ).icu !== 'string') { - // Node was built without ICU support - return; + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } } - // Check that node was built with full Intl support. Its possible it was built without support for non-English - // locales which will make resolvedOptions inaccurate - // - // https://nodejs.org/api/intl.html#detecting-internationalization-support - const january = new Date(9e8); - const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); - if (spanish.format(january) === 'enero') { - const options = Intl.DateTimeFormat().resolvedOptions(); - - return { - locale: options.locale, - timezone: options.timeZone, - }; + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); } - } catch (err) { - // - } - return; -} + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } -function getAppContext() { - const app_memory = process.memoryUsage().rss; - const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString(); + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } - return { app_start_time, app_memory }; -} + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } -/** - * Gets device information from os - */ -function getDeviceContext(deviceOpt) { - const device = {}; + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } - // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions). - // Hence, we only set boot time, if we get a valid uptime value. - // @see https://github.com/getsentry/sentry-javascript/issues/5856 - const uptime = os__WEBPACK_IMPORTED_MODULE_2__.uptime && os__WEBPACK_IMPORTED_MODULE_2__.uptime(); - if (typeof uptime === 'number') { - device.boot_time = new Date(Date.now() - uptime * 1000).toISOString(); - } + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (!request) { + return; + } + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + request.abort(); + request = null; + }; - device.arch = os__WEBPACK_IMPORTED_MODULE_2__.arch(); + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } + } - if (deviceOpt === true || deviceOpt.memory) { - device.memory_size = os__WEBPACK_IMPORTED_MODULE_2__.totalmem(); - device.free_memory = os__WEBPACK_IMPORTED_MODULE_2__.freemem(); - } + if (!requestData) { + requestData = null; + } - if (deviceOpt === true || deviceOpt.cpu) { - const cpuInfo = os__WEBPACK_IMPORTED_MODULE_2__.cpus(); - if (cpuInfo && cpuInfo.length) { - const firstCpu = cpuInfo[0]; + var protocol = parseProtocol(fullPath); - device.processor_count = cpuInfo.length; - device.cpu_description = firstCpu.model; - device.processor_frequency = firstCpu.speed; + if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; } - } - return device; -} -/** Mapping of Node's platform names to actual OS names. */ -const PLATFORM_NAMES = { - aix: 'IBM AIX', - freebsd: 'FreeBSD', - openbsd: 'OpenBSD', - sunos: 'SunOS', - win32: 'Windows', + // Send the request + request.send(requestData); + }); }; -/** Linux version file to check for a distribution. */ -/** Mapping of linux release files located in /etc to distributions. */ -const LINUX_DISTROS = [ - { name: 'fedora-release', distros: ['Fedora'] }, - { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] }, - { name: 'redhat_version', distros: ['Red Hat Linux'] }, - { name: 'SuSE-release', distros: ['SUSE Linux'] }, - { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] }, - { name: 'debian_version', distros: ['Debian'] }, - { name: 'debian_release', distros: ['Debian'] }, - { name: 'arch-release', distros: ['Arch Linux'] }, - { name: 'gentoo-release', distros: ['Gentoo Linux'] }, - { name: 'novell-release', distros: ['SUSE Linux'] }, - { name: 'alpine-release', distros: ['Alpine Linux'] }, -]; +/***/ }), +/* 1697 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** Functions to extract the OS version from Linux release files. */ -const LINUX_VERSIONS +"use strict"; - = { - alpine: content => content, - arch: content => matchFirst(/distrib_release=(.*)/, content), - centos: content => matchFirst(/release ([^ ]+)/, content), - debian: content => content, - fedora: content => matchFirst(/release (..)/, content), - mint: content => matchFirst(/distrib_release=(.*)/, content), - red: content => matchFirst(/release ([^ ]+)/, content), - suse: content => matchFirst(/VERSION = (.*)\n/, content), - ubuntu: content => matchFirst(/distrib_release=(.*)/, content), -}; + +var AxiosError = __webpack_require__(1693); /** - * Executes a regular expression with one capture group. + * Resolve or reject a Promise based on response status. * - * @param regex A regular expression to execute. - * @param text Content to execute the RegEx on. - * @returns The captured string if matched; otherwise undefined. + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. */ -function matchFirst(regex, text) { - const match = regex.exec(text); - return match ? match[1] : undefined; -} +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +}; -/** Loads the macOS operating system context. */ -async function getDarwinInfo() { - // Default values that will be used in case no operating system information - // can be loaded. The default version is computed via heuristics from the - // kernel version, but the build ID is missing. - const darwinInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Mac OS X', - version: `10.${Number(os__WEBPACK_IMPORTED_MODULE_2__.release().split('.')[0]) - 4}`, - }; - try { - // We try to load the actual macOS version by executing the `sw_vers` tool. - // This tool should be available on every standard macOS installation. In - // case this fails, we stick with the values computed above. +/***/ }), +/* 1698 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - const output = await new Promise((resolve, reject) => { - (0,child_process__WEBPACK_IMPORTED_MODULE_0__.execFile)('/usr/bin/sw_vers', (error, stdout) => { - if (error) { - reject(error); - return; - } - resolve(stdout); - }); - }); +"use strict"; - darwinInfo.name = matchFirst(/^ProductName:\s+(.*)$/m, output); - darwinInfo.version = matchFirst(/^ProductVersion:\s+(.*)$/m, output); - darwinInfo.build = matchFirst(/^BuildVersion:\s+(.*)$/m, output); - } catch (e) { - // ignore - } - return darwinInfo; -} +var utils = __webpack_require__(1684); -/** Returns a distribution identifier to look up version callbacks. */ -function getLinuxDistroId(name) { - return name.split(' ')[0].toLowerCase(); -} +module.exports = ( + utils.isStandardBrowserEnv() ? -/** Loads the Linux operating system context. */ -async function getLinuxInfo() { - // By default, we cannot assume anything about the distribution or Linux - // version. `os.release()` returns the kernel version and we assume a generic - // "Linux" name, which will be replaced down below. - const linuxInfo = { - kernel_version: os__WEBPACK_IMPORTED_MODULE_2__.release(), - name: 'Linux', - }; + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); - try { - // We start guessing the distribution by listing files in the /etc - // directory. This is were most Linux distributions (except Knoppix) store - // release files with certain distribution-dependent meta data. We search - // for exactly one known file defined in `LINUX_DISTROS` and exit if none - // are found. In case there are more than one file, we just stick with the - // first one. - const etcFiles = await readDirAsync('/etc'); - const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name)); - if (!distroFile) { - return linuxInfo; - } + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } - // Once that file is known, load its contents. To make searching in those - // files easier, we lowercase the file contents. Since these files are - // usually quite small, this should not allocate too much memory and we only - // hold on to it for a very short amount of time. - const distroPath = (0,path__WEBPACK_IMPORTED_MODULE_3__.join)('/etc', distroFile.name); - const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) ).toLowerCase(); + if (utils.isString(path)) { + cookie.push('path=' + path); + } - // Some Linux distributions store their release information in the same file - // (e.g. RHEL and Centos). In those cases, we scan the file for an - // identifier, that basically consists of the first word of the linux - // distribution name (e.g. "red" for Red Hat). In case there is no match, we - // just assume the first distribution in our list. - const { distros } = distroFile; - linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0]; + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } - // Based on the found distribution, we can now compute the actual version - // number. This is different for every distribution, so several strategies - // are computed in `LINUX_VERSIONS`. - const id = getLinuxDistroId(linuxInfo.name); - linuxInfo.version = LINUX_VERSIONS[id](contents); - } catch (e) { - // ignore - } + if (secure === true) { + cookie.push('secure'); + } - return linuxInfo; -} + document.cookie = cookie.join('; '); + }, + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, -//# sourceMappingURL=context.js.map + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); /***/ }), -/* 1704 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1699 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "RequestData": () => (/* binding */ RequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1708); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1705); +var isAbsoluteURL = __webpack_require__(1700); +var combineURLs = __webpack_require__(1701); -const DEFAULT_OPTIONS = { - include: { - cookies: true, - data: true, - headers: true, - ip: false, - query_string: true, - url: true, - user: { - id: true, - username: true, - email: true, - }, - }, - transactionNamingScheme: 'methodPath', +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; }; -/** Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/integrations` - * so it can be used in cross-platform SDKs like `@sentry/nextjs`. */ -class RequestData { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'RequestData';} - - /** - * @inheritDoc - */ - __init() {this.name = RequestData.id;} - /** - * Function for adding request data to event. Defaults to `addRequestDataToEvent` from `@sentry/node` for now, but - * left as a property so this integration can be moved to `@sentry/core` as a base class in case we decide to use - * something similar in browser-based SDKs in the future. - */ +/***/ }), +/* 1700 */ +/***/ ((module) => { - /** - * @inheritDoc - */ - constructor(options = {}) {;RequestData.prototype.__init.call(this); - this._addRequestData = _requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent; - this._options = { - ...DEFAULT_OPTIONS, - ...options, - include: { - // @ts-ignore It's mad because `method` isn't a known `include` key. (It's only here and not set by default in - // `addRequestDataToEvent` for legacy reasons. TODO (v8): Change that.) - method: true, - ...DEFAULT_OPTIONS.include, - ...options.include, - user: - options.include && typeof options.include.user === 'boolean' - ? options.include.user - : { - ...DEFAULT_OPTIONS.include.user, - // Unclear why TS still thinks `options.include.user` could be a boolean at this point - ...((options.include || {}).user ), - }, - }, - }; - } +"use strict"; - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - // Note: In the long run, most of the logic here should probably move into the request data utility functions. For - // the moment it lives here, though, until https://github.com/getsentry/sentry-javascript/issues/5718 is addressed. - // (TL;DR: Those functions touch many parts of the repo in many different ways, and need to be clened up. Once - // that's happened, it will be easier to add this logic in without worrying about unexpected side effects.) - const { transactionNamingScheme } = this._options; - addGlobalEventProcessor(event => { - const hub = getCurrentHub(); - const self = hub.getIntegration(RequestData); +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +}; - const { sdkProcessingMetadata = {} } = event; - const req = sdkProcessingMetadata.request; - // If the globally installed instance of this integration isn't associated with the current hub, `self` will be - // undefined - if (!self || !req) { - return event; - } +/***/ }), +/* 1701 */ +/***/ ((module) => { - // The Express request handler takes a similar `include` option to that which can be passed to this integration. - // If passed there, we store it in `sdkProcessingMetadata`. TODO(v8): Force express and GCP people to use this - // integration, so that all of this passing and conversion isn't necessary - const addRequestDataOptions = - sdkProcessingMetadata.requestDataOptionsFromExpressHandler || - sdkProcessingMetadata.requestDataOptionsFromGCPWrapper || - convertReqDataIntegrationOptsToAddReqDataOpts(this._options); +"use strict"; - const processedEvent = this._addRequestData(event, req, addRequestDataOptions); - // Transaction events already have the right `transaction` value - if (event.type === 'transaction' || transactionNamingScheme === 'handler') { - return processedEvent; - } +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; - // In all other cases, use the request's associated transaction (if any) to overwrite the event's `transaction` - // value with a high-quality one - const reqWithTransaction = req ; - const transaction = reqWithTransaction._sentryTransaction; - if (transaction) { - // TODO (v8): Remove the nextjs check and just base it on `transactionNamingScheme` for all SDKs. (We have to - // keep it the way it is for the moment, because changing the names of transactions in Sentry has the potential - // to break things like alert rules.) - const shouldIncludeMethodInTransactionName = - getSDKName(hub) === 'sentry.javascript.nextjs' - ? transaction.name.startsWith('/api') - : transactionNamingScheme !== 'path'; - const [transactionValue] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.extractPathForTransaction)(req, { - path: true, - method: shouldIncludeMethodInTransactionName, - customRoute: transaction.name, - }); +/***/ }), +/* 1702 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - processedEvent.transaction = transactionValue; - } +"use strict"; - return processedEvent; - }); - } -} RequestData.__initStatic(); -/** Convert this integration's options to match what `addRequestDataToEvent` expects */ -/** TODO: Can possibly be deleted once https://github.com/getsentry/sentry-javascript/issues/5718 is fixed */ -function convertReqDataIntegrationOptsToAddReqDataOpts( - integrationOptions, -) { - const { - transactionNamingScheme, - include: { ip, user, ...requestOptions }, - } = integrationOptions; +var utils = __webpack_require__(1684); - const requestIncludeKeys = []; - for (const [key, value] of Object.entries(requestOptions)) { - if (value) { - requestIncludeKeys.push(key); - } - } +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; - let addReqDataUserOpt; - if (user === undefined) { - addReqDataUserOpt = true; - } else if (typeof user === 'boolean') { - addReqDataUserOpt = user; - } else { - const userIncludeKeys = []; - for (const [key, value] of Object.entries(user)) { - if (value) { - userIncludeKeys.push(key); - } - } - addReqDataUserOpt = userIncludeKeys; - } +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; - return { - include: { - ip, - user: addReqDataUserOpt, - request: requestIncludeKeys.length !== 0 ? requestIncludeKeys : undefined, - transaction: transactionNamingScheme, - }, - }; -} + if (!headers) { return parsed; } -function getSDKName(hub) { - try { - // For a long chain like this, it's fewer bytes to combine a try-catch with assuming everything is there than to - // write out a long chain of `a && a.b && a.b.c && ...` - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return hub.getClient().getOptions()._metadata.sdk.name; - } catch (err) { - // In theory we should never get here - return undefined; - } -} + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); -//# sourceMappingURL=requestdata.js.map + return parsed; +}; /***/ }), -/* 1705 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1703 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DEFAULT_USER_INCLUDES": () => (/* binding */ DEFAULT_USER_INCLUDES), -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1707); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1660); -/* harmony import */ var cookie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1706); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(63); -/* harmony import */ var url__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url__WEBPACK_IMPORTED_MODULE_1__); - - +var utils = __webpack_require__(1684); -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, -}; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; +module.exports = ( + utils.isStandardBrowserEnv() ? -/** - * Options deciding what parts of the request to use when enhancing an event - */ + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction(transaction, req) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); - } - transaction.setData('query', extractQueryParams(req)); -} + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } - let path = ''; - let source = 'url'; + urlParsingNode.setAttribute('href', href); - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; - } + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); - } + originURL = resolveURL(window.location.href); - let name = ''; - if (options.method && method) { - name += method; - } - if (options.method && options.path) { - name += ' '; - } - if (options.path && path) { - name += path; - } + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : - return [name, source]; -} + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; - } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; - } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; - } - } -} -/** JSDoc */ -function extractUserData( - user +/***/ }), +/* 1704 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; +"use strict"; - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - return extractedUser; -} +var AxiosError = __webpack_require__(1693); +var utils = __webpack_require__(1684); /** - * Normalize data from the request object - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies + * A `CanceledError` is an object that is thrown when an operation is canceled. * - * @returns An object containing normalized request data + * @class + * @param {string=} message The message. */ -function extractRequestData( - req, - options +function CanceledError(message) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); + this.name = 'CanceledError'; +} -, -) { - const { include = DEFAULT_REQUEST_INCLUDES } = options || {}; - const requestData = {}; +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) +module.exports = CanceledError; -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = originalUrl.startsWith(protocol) ? originalUrl : `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - // Remove the Cookie header in case cookie data should not be included in the event - if (!include.includes('cookies')) { - delete (requestData.headers ).cookie; - } +/***/ }), +/* 1705 */ +/***/ ((module) => { + +"use strict"; + + +module.exports = function parseProtocol(url) { + var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +}; + + +/***/ }), +/* 1706 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && cookie__WEBPACK_IMPORTED_MODULE_0__.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isString)(req.body) ? req.body : JSON.stringify((0,_sentry_utils__WEBPACK_IMPORTED_MODULE_4__.normalize)(req.body)); - } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; - } - } - } - }); - return requestData; -} +var utils = __webpack_require__(1684); +var settle = __webpack_require__(1697); +var buildFullPath = __webpack_require__(1699); +var buildURL = __webpack_require__(1687); +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var httpFollow = (__webpack_require__(1707).http); +var httpsFollow = (__webpack_require__(1707).https); +var url = __webpack_require__(63); +var zlib = __webpack_require__(83); +var VERSION = (__webpack_require__(1709).version); +var transitionalDefaults = __webpack_require__(1694); +var AxiosError = __webpack_require__(1693); +var CanceledError = __webpack_require__(1704); + +var isHttps = /https:?/; + +var supportedProtocols = [ 'http:', 'https:', 'file:' ]; /** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included * - * @returns The mutated `Event` object + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([options, 'optionalAccess', _ => _.include]), +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; + + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); }; +} - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request }) - : extractRequestData(req); +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } - event.request = { - ...event.request, - ...extractedRequestData, + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } + var resolve = function resolve(value) { + done(); + resolvePromise(value); }; - } + var rejected = false; + var reject = function reject(value) { + done(); + rejected = true; + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; + var headerNames = {}; - if (include.user) { - const extractedUser = req.user && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_3__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; + Object.keys(headers).forEach(function storeLowerName(name) { + headerNames[name.toLowerCase()] = name; + }); - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + if ('user-agent' in headerNames) { + // User-Agent is specified; handle case where no UA header is desired + if (!headers[headerNames['user-agent']]) { + delete headers[headerNames['user-agent']]; + } + // Otherwise, use specified value + } else { + // Only set header if it hasn't been set in config + headers['User-Agent'] = 'axios/' + VERSION; } - } - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } - } + // support for https://www.npmjs.com/package/form-data api + if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + Object.assign(headers, data.getHeaders()); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); - } + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } - return event; -} + // Add Content-Length header if data exists + if (!headerNames['content-length']) { + headers['Content-Length'] = data.length; + } + } -function extractQueryParams(req) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } - if (!originalUrl) { - return; - } + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || supportedProtocols[0]; - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; - } + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); + } - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - url__WEBPACK_IMPORTED_MODULE_1__.parse(originalUrl).query || - undefined - ); -} + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } + if (auth && headerNames.authorization) { + delete headers[headerNames.authorization]; + } -//# sourceMappingURL=requestdata.js.map + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + try { + buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''); + } catch (err) { + var customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + reject(customErr); + } -/***/ }), -/* 1706 */ -/***/ ((__unused_webpack_module, exports) => { + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); -/** - * Module exports. - * @public - */ + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } -exports.parse = parse; -exports.serialize = serialize; + return parsed.hostname === proxyElement; + }); + } -/** - * Module variables. - * @private - */ + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; -var decode = decodeURIComponent; -var encode = encodeURIComponent; + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } + } + } + } -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirect = config.beforeRedirect; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; + } -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } - var obj = {} - var opt = options || {}; - var pairs = str.split(';') - var dec = opt.decode || decode; + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var index = pair.indexOf('=') + // uncompress the response body transparently if required + var stream = res; - // skip things that don't look like key=value - if (index < 0) { - continue; - } + // return the last request in case of redirects + var lastRequest = res.req || req; - var key = pair.substring(0, index).trim() - // only assign once - if (undefined == obj[key]) { - var val = pair.substring(index + 1, pair.length).trim() + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); - // quoted values - if (val[0] === '"') { - val = val.slice(1, -1) + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + } } - obj[key] = tryDecode(val, dec); - } - } - - return obj; -} + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest + }; -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + var totalResponseBytes = 0; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destoy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + stream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } + stream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + stream.destroy(); + reject(new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + )); + }); - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); - var value = enc(val); + stream.on('end', function handleStreamEnd() { + try { + var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + }); - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); - var str = name + '=' + value; + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + var timeout = parseInt(config.timeout, 10); - if (isNaN(maxAge) || !isFinite(maxAge)) { - throw new TypeError('option maxAge is invalid') - } + if (isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); - str += '; Max-Age=' + Math.floor(maxAge); - } + return; + } - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + req.abort(); + var transitional = config.transitional || transitionalDefaults; + reject(new AxiosError( + 'timeout of ' + timeout + 'ms exceeded', + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + }); } - str += '; Domain=' + opt.domain; - } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (req.aborted) return; - str += '; Path=' + opt.path; - } + req.abort(); + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + }; - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } } - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; - } - - if (opt.secure) { - str += '; Secure'; - } - - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(AxiosError.from(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); } - } - - return str; -} - -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ - -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} + }); +}; /***/ }), /* 1707 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getNumberOfUrlSegments": () => (/* binding */ getNumberOfUrlSegments), -/* harmony export */ "parseUrl": () => (/* binding */ parseUrl), -/* harmony export */ "stripUrlQueryAndFragment": () => (/* binding */ stripUrlQueryAndFragment) -/* harmony export */ }); -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not <a/> href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) - - { - if (!url) { - return {}; - } - - const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (!match) { - return {}; - } +var url = __webpack_require__(63); +var URL = url.URL; +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var Writable = (__webpack_require__(82).Writable); +var assert = __webpack_require__(91); +var debug = __webpack_require__(1708); - // coerce to undefined values to empty string so we don't get 'undefined' - const query = match[6] || ''; - const fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, // everything minus origin +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); }; -} - -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} - -/** - * Returns number of URL segments of a passed string URL. - */ -function getNumberOfUrlSegments(url) { - // split at '/' or at '\/' to split regex urls correctly - return url.split(/\\?\//).filter(s => s.length > 0 && s !== ',').length; -} - - -//# sourceMappingURL=url.js.map - - -/***/ }), -/* 1708 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +}); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "addRequestDataToEvent": () => (/* binding */ addRequestDataToEvent), -/* harmony export */ "addRequestDataToTransaction": () => (/* binding */ addRequestDataToTransaction), -/* harmony export */ "extractPathForTransaction": () => (/* binding */ extractPathForTransaction), -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData) -/* harmony export */ }); -/* harmony import */ var _buildPolyfills__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1663); -/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1649); -/* harmony import */ var _normalize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1660); -/* harmony import */ var _url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1707); +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); -const DEFAULT_INCLUDES = { - ip: false, - request: true, - transaction: true, - user: true, +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); }; -const DEFAULT_REQUEST_INCLUDES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; -const DEFAULT_USER_INCLUDES = ['id', 'username', 'email']; -/** - * Sets parameterized route as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addRequestDataToTransaction( - transaction, - req, - deps, -) { - if (!transaction) return; - if (!transaction.metadata.source || transaction.metadata.source === 'url') { - // Attempt to grab a parameterized route off of the request - transaction.setName(...extractPathForTransaction(req, { path: true, method: true })); - } - transaction.setData('url', req.originalUrl || req.url); - if (req.baseUrl) { - transaction.setData('baseUrl', req.baseUrl); +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); } - transaction.setData('query', extractQueryParams(req, deps)); -} - -/** - * Extracts a complete and parameterized path from the request object and uses it to construct transaction name. - * If the parameterized transaction name cannot be extracted, we fall back to the raw URL. - * - * Additionally, this function determines and returns the transaction name source - * - * eg. GET /mountpoint/user/:id - * - * @param req A request object - * @param options What to include in the transaction name (method, path, or a custom route name to be - * used instead of the request's route) - * - * @returns A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url') - */ -function extractPathForTransaction( - req, - options = {}, -) { - const method = req.method && req.method.toUpperCase(); - let path = ''; - let source = 'url'; + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } - // Check to see if there's a parameterized route we can use (as there is in Express) - if (options.customRoute || req.route) { - path = options.customRoute || `${req.baseUrl || ''}${req.route && req.route.path}`; - source = 'route'; + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); } +}; - // Otherwise, just take the original URL - else if (req.originalUrl || req.url) { - path = (0,_url_js__WEBPACK_IMPORTED_MODULE_0__.stripUrlQueryAndFragment)(req.originalUrl || req.url || ''); +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; } - let name = ''; - if (options.method && method) { - name += method; + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); } - if (options.method && options.path) { - name += ' '; + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; } - if (options.path && path) { - name += path; +}; + +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; + +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; + +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); } - return [name, source]; -} + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } -/** JSDoc */ -function extractTransaction(req, type) { - switch (type) { - case 'path': { - return extractPathForTransaction(req, { path: true })[0]; + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; } - case 'handler': { - return (req.route && req.route.stack && req.route.stack[0] && req.route.stack[0].name) || '<anonymous>'; + + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + if (callback) { + self.removeListener("timeout", callback); } - case 'methodPath': - default: { - return extractPathForTransaction(req, { path: true, method: true })[0]; + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); } } -} -/** JSDoc */ -function extractUserData( - user + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } -, - keys, -) { - const extractedUser = {}; - const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_INCLUDES; + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } - attributes.forEach(key => { - if (user && key in user) { - extractedUser[key] = user[key]; + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + + return this; +}; + +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; } - }); + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; - return extractedUser; -} -/** - * Normalize data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param options.include An optional array of keys to include in the normalized data. Defaults to - * DEFAULT_REQUEST_INCLUDES if not provided. - * @param options.deps Injected, platform-specific dependencies - * @returns An object containing normalized request data - */ -function extractRequestData( - req, - options +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } -, -) { - const { include = DEFAULT_REQUEST_INCLUDES, deps } = options || {}; - const requestData = {}; + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } - // headers: - // node, express, koa, nextjs: req.headers - const headers = (req.headers || {}) + // Create the native request and set up its event handlers + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + request._redirectable = this; + for (var event of events) { + request.on(event, eventHandlers[event]); + } -; - // method: - // node, express, koa, nextjs: req.method - const method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node, nextjs: req.headers.host - const host = req.hostname || req.host || headers.host || '<no host>'; - // protocol: - // node, nextjs: <n/a> - // express, koa: req.protocol - const protocol = req.protocol === 'https' || (req.socket && req.socket.encrypted) ? 'https' : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - const originalUrl = req.originalUrl || req.url || ''; - // absolute url - const absoluteUrl = `${protocol}://${host}${originalUrl}`; - include.forEach(key => { - switch (key) { - case 'headers': { - requestData.headers = headers; - break; - } - case 'method': { - requestData.method = method; - break; - } - case 'url': { - requestData.url = absoluteUrl; - break; - } - case 'cookies': { - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = - // TODO (v8 / #5257): We're only sending the empty object for backwards compatibility, so the last bit can - // come off in v8 - req.cookies || (headers.cookie && deps && deps.cookie && deps.cookie.parse(headers.cookie)) || {}; - break; - } - case 'query_string': { - // query string: - // node: req.url (raw) - // express, koa, nextjs: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = extractQueryParams(req, deps); - break; - } - case 'data': { - if (method === 'GET' || method === 'HEAD') { - break; + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._currentUrl = this._options.path; + + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); } - // body data: - // express, koa, nextjs: req.body - // - // when using node by itself, you have to read the incoming stream(see - // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know - // where they're going to store the final result, so they'll have to capture this data themselves - if (req.body !== undefined) { - requestData.data = (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isString)(req.body) ? req.body : JSON.stringify((0,_normalize_js__WEBPACK_IMPORTED_MODULE_2__.normalize)(req.body)); + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } } - break; - } - default: { - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = (req )[key]; + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); } } - } - }); + }()); + } +}; - return requestData; -} +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } -/** - * Options deciding what parts of the request to use when enhancing an event - */ + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. -/** - * Add data from the given request to the given event - * - * @param event The event to which the request data will be added - * @param req Request object - * @param options.include Flags to control what data is included - * @param options.deps Injected platform-specific dependencies - * @hidden - */ -function addRequestDataToEvent( - event, - req, - options, -) { - const include = { - ...DEFAULT_INCLUDES, - ...(0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _ => _.include]), - }; + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); - if (include.request) { - const extractedRequestData = Array.isArray(include.request) - ? extractRequestData(req, { include: include.request, deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _2 => _2.deps]) }) - : extractRequestData(req, { deps: (0,_buildPolyfills__WEBPACK_IMPORTED_MODULE_3__._optionalChain)([options, 'optionalAccess', _3 => _3.deps]) }); + // Clean up + this._requestBodyBuffers = []; + return; + } - event.request = { - ...event.request, - ...extractedRequestData, - }; + // The response is a redirect, so abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; + } + + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); } - if (include.user) { - const extractedUser = req.user && (0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isPlainObject)(req.user) ? extractUserData(req.user, include.user) : {}; + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - if (Object.keys(extractedUser).length) { - event.user = { - ...event.user, - ...extractedUser, - }; - } - } + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = url.parse(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); - // client ip: - // node, nextjs: req.socket.remoteAddress - // express, koa: req.ip - if (include.ip) { - const ip = req.ip || (req.socket && req.socket.remoteAddress); - if (ip) { - event.user = { - ...event.user, - ip_address: ip, - }; - } + // Determine the URL of the redirection + var redirectUrl; + try { + redirectUrl = url.resolve(currentUrl, location); } - - if (include.transaction && !event.transaction) { - // TODO do we even need this anymore? - // TODO make this work for nextjs - event.transaction = extractTransaction(req, include.transaction); + catch (cause) { + this.emit("error", new RedirectionError(cause)); + return; } - return event; -} - -function extractQueryParams( - req, - deps, -) { - // url (including path and query string): - // node, express: req.originalUrl - // koa, nextjs: req.url - let originalUrl = req.originalUrl || req.url || ''; + // Create the redirected request + debug("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); - if (!originalUrl) { - return; + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrlParts.protocol !== currentUrlParts.protocol && + redirectUrlParts.protocol !== "https:" || + redirectUrlParts.host !== currentHost && + !isSubdomain(redirectUrlParts.host, currentHost)) { + removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); } - // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and - // hostname on the beginning. Since the point here is just to grab the query string, it doesn't matter what we use. - if (originalUrl.startsWith('/')) { - originalUrl = `http://dogs.are.great${originalUrl}`; + // Evaluate the beforeRedirect callback + if (typeof beforeRedirect === "function") { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + try { + beforeRedirect(this._options, responseDetails, requestDetails); + } + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); } - return ( - req.query || - (typeof URL !== undefined && new URL(originalUrl).search.replace('?', '')) || - // In Node 8, `URL` isn't in the global scope, so we have to use the built-in module from Node - (deps && deps.url && deps.url.parse(originalUrl).query) || - undefined - ); -} + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + } +}; +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; -//# sourceMappingURL=requestdata.js.map + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); + } + } + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } -/***/ }), -/* 1709 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "getModule": () => (/* binding */ getModule) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1710); + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } -/** normalizes Windows paths */ -function normalizePath(path) { - return path - .replace(/^[A-Z]:/, '') // remove Windows-style prefix - .replace(/\\/g, '/'); // replace all `\` instances with `/` + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; } -/** Gets the module from a filename */ -function getModule(filename) { - if (!filename) { - return; - } - - const normalizedFilename = normalizePath(filename); - - // We could use optional chaining here but webpack does like that mixed with require - const base = normalizePath( - `${( true && __webpack_require__.c[__webpack_require__.s] && __webpack_require__.c[__webpack_require__.s].filename && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(__webpack_require__.c[__webpack_require__.s].filename)) || global.process.cwd()}/`, - ); +/* istanbul ignore next */ +function noop() { /* empty */ } - // It's specifically a module - const file = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.basename)(normalizedFilename, '.js'); +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); + } + return options; +} - const path = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.dirname)(normalizedFilename); - let n = path.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return `${path.substr(n + 14).replace(/\//g, '.')}:${file}`; +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = `${path}/`.lastIndexOf(base, 0); + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} - if (n === 0) { - let moduleName = path.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; +function createErrorType(code, defaultMessage) { + function CustomError(cause) { + Error.captureStackTrace(this, this.constructor); + if (!cause) { + this.message = defaultMessage; } - moduleName += file; - return moduleName; + else { + this.message = defaultMessage + ": " + cause.message; + this.cause = cause; + } + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; +} + +function abortRequest(request) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); } - return file; + request.on("error", noop); + request.abort(); } +function isSubdomain(subdomain, domain) { + const dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} -//# sourceMappingURL=module.js.map +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; /***/ }), -/* 1710 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1708 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "basename": () => (/* binding */ basename), -/* harmony export */ "dirname": () => (/* binding */ dirname), -/* harmony export */ "isAbsolute": () => (/* binding */ isAbsolute), -/* harmony export */ "join": () => (/* binding */ join), -/* harmony export */ "normalizePath": () => (/* binding */ normalizePath), -/* harmony export */ "relative": () => (/* binding */ relative), -/* harmony export */ "resolve": () => (/* binding */ resolve) -/* harmony export */ }); -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js +var debug; -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - let up = 0; - for (let i = parts.length - 1; i >= 0; i--) { - const last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __webpack_require__(1402)("follow-redirects"); } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; } } + debug.apply(null, arguments); +}; - return parts; -} -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - const parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} +/***/ }), +/* 1709 */ +/***/ ((module) => { -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve(...args) { - let resolvedPath = ''; - let resolvedAbsolute = false; +module.exports = { + "version": "0.27.2" +}; - for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - const path = i >= 0 ? args[i] : '/'; +/***/ }), +/* 1710 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // Skip empty entries - if (!path) { - continue; - } +// eslint-disable-next-line strict +module.exports = __webpack_require__(1711); - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charAt(0) === '/'; + +/***/ }), +/* 1711 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +var CombinedStream = __webpack_require__(147); +var util = __webpack_require__(64); +var path = __webpack_require__(142); +var http = __webpack_require__(80); +var https = __webpack_require__(81); +var parseUrl = (__webpack_require__(63).parse); +var fs = __webpack_require__(149); +var Stream = (__webpack_require__(82).Stream); +var mime = __webpack_require__(139); +var asynckit = __webpack_require__(150); +var populate = __webpack_require__(1712); + +// Public API +module.exports = FormData; + +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; - // Normalize the path - resolvedPath = normalizeArray( - resolvedPath.split('/').filter(p => !!p), - !resolvedAbsolute, - ).join('/'); + CombinedStream.call(this); - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } } -/** JSDoc */ -function trim(arr) { - let start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; } - let end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; - } + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; } - if (start > end) { - return []; + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; } - return arr.slice(start, end - start + 1); -} -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - const fromParts = trim(from.split('/')); - const toParts = trim(to.split('/')); + append(header); + append(value); + append(footer); - const length = Math.min(fromParts.length, toParts.length); - let samePartsLength = length; - for (let i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); } - let outputParts = []; - for (let i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; - return outputParts.join('/'); -} +FormData.prototype._lengthRetriever = function(value, callback) { -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - const isPathAbsolute = isAbsolute(path); - const trailingSlash = path.substr(-1) === '/'; + if (value.hasOwnProperty('fd')) { + + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // Normalize the path - let normalizedPath = normalizeArray( - path.split('/').filter(p => !!p), - !isPathAbsolute, - ).join('/'); + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - return (isPathAbsolute ? '/' : '') + normalizedPath; -} + var fileSize; -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} + if (err) { + callback(err); + return; + } -// posix version -/** JSDoc */ -function join(...args) { - return normalizePath(args.join('/')); -} + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } -/** JSDoc */ -function dirname(path) { - const result = splitPath(path); - const root = result[0]; - let dir = result[1]; + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - if (!root && !dir) { - // No dirname whatsoever - return '.'; + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); } +}; - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; } - return root + dir; -} + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); -/** JSDoc */ -function basename(path, ext) { - let f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); } - return f; -} + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; -//# sourceMappingURL=path.js.map + // skip nullish headers. + if (header == null) { + continue; + } + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } -/***/ }), -/* 1711 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "InboundFilters": () => (/* binding */ InboundFilters), -/* harmony export */ "_mergeOptions": () => (/* binding */ _mergeOptions), -/* harmony export */ "_shouldDropEvent": () => (/* binding */ _shouldDropEvent) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1647); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1648); + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; +FormData.prototype._getContentDisposition = function(value, options) { -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -const DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; + var filename + , contentDisposition + ; -/** Options for the InboundFilters integration */ + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } -/** Inbound filters configurable by the user */ -class InboundFilters { - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'InboundFilters';} + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - /** - * @inheritDoc - */ - __init() {this.name = InboundFilters.id;} + return contentDisposition; +}; - constructor( _options = {}) {;this._options = _options;InboundFilters.prototype.__init.call(this);} +FormData.prototype._getContentType = function(value, options) { - /** - * @inheritDoc - */ - setupOnce(addGlobalEventProcessor, getCurrentHub) { - const eventProcess = (event) => { - const hub = getCurrentHub(); - if (hub) { - const self = hub.getIntegration(InboundFilters); - if (self) { - const client = hub.getClient(); - const clientOptions = client ? client.getOptions() : {}; - const options = _mergeOptions(self._options, clientOptions); - return _shouldDropEvent(event, options) ? null : event; - } - } - return event; - }; + // use custom content-type above all + var contentType = options.contentType; - eventProcess.id = this.name; - addGlobalEventProcessor(eventProcess); + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } -} InboundFilters.__initStatic(); - -/** JSDoc */ -function _mergeOptions( - internalOptions = {}, - clientOptions = {}, -) { - return { - allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])], - denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])], - ignoreErrors: [ - ...(internalOptions.ignoreErrors || []), - ...(clientOptions.ignoreErrors || []), - ...DEFAULT_IGNORE_ERRORS, - ], - ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true, - }; -} -/** JSDoc */ -function _shouldDropEvent(event, options) { - if (options.ignoreInternal && _isSentryError(event)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return true; + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); } - if (_isIgnoredError(event, options.ignoreErrors)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`, - ); - return true; + + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; } - if (_isDeniedUrl(event, options.denyUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); } - if (!_isAllowedUrl(event, options.allowUrls)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.warn( - `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)( - event, - )}.\nUrl: ${_getEventFilterUrl(event)}`, - ); - return true; + + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; } - return false; -} -function _isIgnoredError(event, ignoreErrors) { - if (!ignoreErrors || !ignoreErrors.length) { - return false; - } + return contentType; +}; + +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - return _getPossibleEventMessages(event).some(message => (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(message, ignoreErrors)); -} + next(footer); + }.bind(this); +}; -function _isDeniedUrl(event, denyUrls) { - // TODO: Use Glob instead? - if (!denyUrls || !denyUrls.length) { - return false; - } - const url = _getEventFilterUrl(event); - return !url ? false : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, denyUrls); -} +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; -function _isAllowedUrl(event, allowUrls) { - // TODO: Use Glob instead? - if (!allowUrls || !allowUrls.length) { - return true; - } - const url = _getEventFilterUrl(event); - return !url ? true : (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_2__.stringMatchesSomePattern)(url, allowUrls); -} +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; -function _getPossibleEventMessages(event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; - return [`${value}`, `${type}: ${value}`]; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract message for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return []; + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; } } - return []; -} -function _isSentryError(event) { - try { - // @ts-ignore can't be a sentry error if undefined - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return event.exception.values[0].type === 'SentryError'; - } catch (e) { - // ignore - } - return false; -} + return formHeaders; +}; -function _getLastValidUrl(frames = []) { - for (let i = frames.length - 1; i >= 0; i--) { - const frame = frames[i]; +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; - if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') { - return frame.filename || null; - } +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - return null; -} + return this._boundary; +}; -function _getEventFilterUrl(event) { - try { - let frames; - try { - // @ts-ignore we only care about frames if the whole thing here is defined - frames = event.exception.values[0].stacktrace.frames; - } catch (e) { - // ignore +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } } - return frames ? _getLastValidUrl(frames) : null; - } catch (oO) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.error(`Cannot extract url for event ${(0,_sentry_utils__WEBPACK_IMPORTED_MODULE_1__.getEventDescription)(event)}`); - return null; } -} + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; -//# sourceMappingURL=inboundfilters.js.map +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + + this._boundary = boundary; +}; +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; -/***/ }), -/* 1712 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* binding */ FunctionToString) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1650); + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + return knownLength; +}; -let originalFunctionToString; +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -/** Patch toString calls to return proper name for wrapped functions */ -class FunctionToString {constructor() { FunctionToString.prototype.__init.call(this); } - /** - * @inheritDoc - */ - static __initStatic() {this.id = 'FunctionToString';} + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - /** - * @inheritDoc - */ - __init() {this.name = FunctionToString.id;} + return hasKnownLength; +}; - /** - * @inheritDoc - */ - setupOnce() { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function ( ...args) { - const context = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_0__.getOriginalFunction)(this) || this; - return originalFunctionToString.apply(context, args); - }; + if (this._streams.length) { + knownLength += this._lastBoundary().length; } -} FunctionToString.__initStatic(); + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } -//# sourceMappingURL=functiontostring.js.map + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); -/***/ }), -/* 1713 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + cb(null, knownLength); + }); +}; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "initAndBind": () => (/* binding */ initAndBind) -/* harmony export */ }); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1653); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1640); +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); -/** A class object that can instantiate Client objects. */ + // use custom params + } else { -/** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. - * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. - */ -function initAndBind( - clientClass, - options, -) { - if (options.debug === true) { - if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) { - _sentry_utils__WEBPACK_IMPORTED_MODULE_0__.logger.enable(); - } else { - // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped - // eslint-disable-next-line no-console - console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; } } - const hub = (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getCurrentHub)(); - const scope = hub.getScope(); - if (scope) { - scope.update(options.initialScope); - } - const client = new clientClass(options); - hub.bindClient(client); -} + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } -//# sourceMappingURL=sdk.js.map + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } + // add content length + if (length) { + request.setHeader('Content-Length', length); + } -/***/ }), -/* 1714 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + this.pipe(request); + if (cb) { + var onResponse; -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "deepReadDirSync": () => (/* binding */ deepReadDirSync) -/* harmony export */ }); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(149); -/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(142); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__); + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + return cb.call(this, error, responce); + }; + onResponse = callback.bind(this, null); -/** - * Recursively read the contents of a directory. - * - * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this - * directory. - * @returns Array holding all relative paths - */ -function deepReadDirSync(targetDir) { - const targetDirAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.resolve(targetDir); + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); - if (!fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(targetDirAbsPath)) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}. Directory does not exist.`); - } + return request; +}; - if (!fs__WEBPACK_IMPORTED_MODULE_0__.statSync(targetDirAbsPath).isDirectory()) { - throw new Error(`Cannot read contents of ${targetDirAbsPath}, because it is not a directory.`); +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); } +}; - // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it - // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve - // the difference between `targetDirAbsPath` and `currentDirAbsPath`. - const deepReadCurrentDir = (currentDirAbsPath) => { - return fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(currentDirAbsPath).reduce((absPaths, itemName) => { - const itemAbsPath = path__WEBPACK_IMPORTED_MODULE_1__.join(currentDirAbsPath, itemName); +FormData.prototype.toString = function () { + return '[object FormData]'; +}; - if (fs__WEBPACK_IMPORTED_MODULE_0__.statSync(itemAbsPath).isDirectory()) { - return [...absPaths, ...deepReadCurrentDir(itemAbsPath)]; - } - return [...absPaths, itemAbsPath]; - }, []); - }; +/***/ }), +/* 1712 */ +/***/ ((module) => { - return deepReadCurrentDir(targetDirAbsPath).map(absPath => path__WEBPACK_IMPORTED_MODULE_1__.relative(targetDirAbsPath, absPath)); -} +// populates missing values +module.exports = function(dst, src) { + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); -//# sourceMappingURL=utils.js.map + return dst; +}; /***/ }), -/* 1715 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/* 1713 */ +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.extractRequestData), -/* harmony export */ "parseRequest": () => (/* reexport safe */ _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__.parseRequest), -/* harmony export */ "errorHandler": () => (/* binding */ errorHandler), -/* harmony export */ "requestHandler": () => (/* binding */ requestHandler), -/* harmony export */ "tracingHandler": () => (/* binding */ tracingHandler) -/* harmony export */ }); -/* harmony import */ var _sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1663); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1640); -/* harmony import */ var _sentry_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(1655); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(1653); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(1649); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(1717); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1695); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1708); -/* harmony import */ var _sentry_utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1650); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1352); -/* harmony import */ var domain__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(domain__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1705); -/* harmony import */ var _sdk_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1689); -/* harmony import */ var _requestDataDeprecated_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1716); - +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; +/***/ }), +/* 1714 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ +var utils = __webpack_require__(1684); /** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 */ -function tracingHandler() - - { - return function sentryTracingMiddleware( - req, - res, - next, - ) { - const hub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const options = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([hub, 'access', _ => _.getClient, 'call', _2 => _2(), 'optionalAccess', _3 => _3.getOptions, 'call', _4 => _4()]); +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; - if ( - !options || - options.instrumenter !== 'sentry' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _5 => _5.method, 'optionalAccess', _6 => _6.toUpperCase, 'call', _7 => _7()]) === 'OPTIONS' || - (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _8 => _8.method, 'optionalAccess', _9 => _9.toUpperCase, 'call', _10 => _10()]) === 'HEAD' - ) { - return next(); + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); } + return source; + } - // TODO: This is the `hasTracingEnabled` check, but we're doing it manually since `@sentry/tracing` isn't a - // dependency of `@sentry/node`. Long term, that function should probably move to `@sentry/hub. - if (!('tracesSampleRate' in options) && !('tracesSampler' in options)) { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && - _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.warn( - 'Sentry `tracingHandler` is being used, but tracing is disabled. Please enable tracing by setting ' + - 'either `tracesSampleRate` or `tracesSampler` in your `Sentry.init()` options.', - ); - return next(); + // eslint-disable-next-line consistent-return + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); } + } - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - const traceparentData = - req.headers && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_7__.isString)(req.headers['sentry-trace']) && (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_8__.extractTraceparentData)(req.headers['sentry-trace']); - const incomingBaggageHeaders = (0,_sentry_utils_esm_buildPolyfills__WEBPACK_IMPORTED_MODULE_5__._optionalChain)([req, 'access', _11 => _11.headers, 'optionalAccess', _12 => _12.baggage]); - const dynamicSamplingContext = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_9__.baggageHeaderToDynamicSamplingContext)(incomingBaggageHeaders); - - const [name, source] = (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.extractPathForTransaction)(req, { path: true, method: true }); - const transaction = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.startTransaction)( - { - name, - op: 'http.server', - ...traceparentData, - metadata: { - dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, - // The request should already have been stored in `scope.sdkProcessingMetadata` (which will become - // `event.sdkProcessingMetadata` the same way the metadata here will) by `sentryRequestMiddleware`, but on the - // off chance someone is using `sentryTracingMiddleware` without `sentryRequestMiddleware`, it doesn't hurt to - // be sure - request: req, - source, - }, - }, - // extra context passed to the tracesSampler - { request: (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_1__.extractRequestData)(req) }, - ); - - // We put the transaction on the scope so users can attach children to it - hub.configureScope(scope => { - scope.setSpan(transaction); - }); - - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).__sentry_transaction = transaction; - - res.once('finish', () => { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(() => { - (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_10__.addRequestDataToTransaction)(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - - next(); - }; -} - -/** - * Backwards compatibility shim which can be removed in v8. Forces the given options to follow the - * `AddRequestDataToEventOptions` interface. - * - * TODO (v8): Get rid of this, and stop passing `requestDataOptionsFromExpressHandler` to `setSDKProcessingMetadata`. - */ -function convertReqHandlerOptsToAddReqDataOpts( - reqHandlerOptions = {}, -) { - let addRequestDataOptions; - - if ('include' in reqHandlerOptions) { - addRequestDataOptions = { include: reqHandlerOptions.include }; - } else { - // eslint-disable-next-line deprecation/deprecation - const { ip, request, transaction, user } = reqHandlerOptions ; - - if (ip || request || transaction || user) { - addRequestDataOptions = { include: (0,_sentry_utils__WEBPACK_IMPORTED_MODULE_12__.dropUndefinedKeys)({ ip, request, transaction, user }) }; + // eslint-disable-next-line consistent-return + function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); } } - return addRequestDataOptions; -} + // eslint-disable-next-line consistent-return + function mergeDirectKeys(prop) { + if (prop in config2) { + return getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + return getMergedValue(undefined, config1[prop]); + } + } -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler( - options, -) { - // TODO (v8): Get rid of this - const requestDataOptions = convertReqHandlerOptsToAddReqDataOpts(options); + var mergeMap = { + 'url': valueFromConfig2, + 'method': valueFromConfig2, + 'data': valueFromConfig2, + 'baseURL': defaultToConfig2, + 'transformRequest': defaultToConfig2, + 'transformResponse': defaultToConfig2, + 'paramsSerializer': defaultToConfig2, + 'timeout': defaultToConfig2, + 'timeoutMessage': defaultToConfig2, + 'withCredentials': defaultToConfig2, + 'adapter': defaultToConfig2, + 'responseType': defaultToConfig2, + 'xsrfCookieName': defaultToConfig2, + 'xsrfHeaderName': defaultToConfig2, + 'onUploadProgress': defaultToConfig2, + 'onDownloadProgress': defaultToConfig2, + 'decompress': defaultToConfig2, + 'maxContentLength': defaultToConfig2, + 'maxBodyLength': defaultToConfig2, + 'beforeRedirect': defaultToConfig2, + 'transport': defaultToConfig2, + 'httpAgent': defaultToConfig2, + 'httpsAgent': defaultToConfig2, + 'cancelToken': defaultToConfig2, + 'socketPath': defaultToConfig2, + 'responseEncoding': defaultToConfig2, + 'validateStatus': mergeDirectKeys + }; - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); - const client = currentHub.getClient(); - // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the - // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - client.initSessionFlusher(); + utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { + var merge = mergeMap[prop] || mergeDeepProperties; + var configValue = merge(prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); - // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode - const scope = currentHub.getScope(); - if (scope && scope.getSession()) { - scope.setSession(); - } - } + return config; +}; - return function sentryRequestMiddleware( - req, - res, - next, - ) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const _end = res.end; - res.end = function (chunk, encoding, cb) { - void (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.flush)(options.flushTimeout) - .then(() => { - _end.call(this, chunk, encoding, cb); - }) - .then(null, e => { - (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && _sentry_utils__WEBPACK_IMPORTED_MODULE_6__.logger.error(e); - _end.call(this, chunk, encoding, cb); - }); - }; - } - const local = domain__WEBPACK_IMPORTED_MODULE_0__.create(); - local.add(req); - local.add(res); - local.run(() => { - const currentHub = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)(); +/***/ }), +/* 1715 */ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - currentHub.configureScope(scope => { - scope.setSDKProcessingMetadata({ - request: req, - // TODO (v8): Stop passing this - requestDataOptionsFromExpressHandler: requestDataOptions, - }); +"use strict"; - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - const scope = currentHub.getScope(); - if (scope) { - // Set `status` of `RequestSession` to Ok, at the beginning of the request - scope.setRequestSession({ status: 'ok' }); - } - } - }); - res.once('finish', () => { - const client = currentHub.getClient(); - if ((0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - setImmediate(() => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (client && (client )._captureRequestSession) { - // Calling _captureRequestSession to capture request session at the end of the request by incrementing - // the correct SessionAggregates bucket i.e. crashed, errored or exited - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (client )._captureRequestSession(); - } - }); - } - }); - next(); - }); - }; -} +var VERSION = (__webpack_require__(1709).version); +var AxiosError = __webpack_require__(1693); -/** JSDoc */ +var validators = {}; -/** JSDoc */ -function getStatusCodeFromResponse(error) { - const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode , 10) : 500; -} +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - const status = getStatusCodeFromResponse(error); - return status >= 500; -} +var deprecatedWarnings = {}; /** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` + * Transitional option validator + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * @returns {function} */ -function errorHandler(options - -) - - { - return function sentryErrorMiddleware( - error, - _req, - res, - next, - ) { - // eslint-disable-next-line @typescript-eslint/unbound-method - const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } - if (shouldHandleError(error)) { - (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.withScope)(_scope => { - // The request should already have been stored in `scope.sdkProcessingMetadata` by `sentryRequestMiddleware`, - // but on the off chance someone is using `sentryErrorMiddleware` without `sentryRequestMiddleware`, it doesn't - // hurt to be sure - _scope.setSDKProcessingMetadata({ request: _req }); + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const transaction = (res ).__sentry_transaction ; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } - const client = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_4__.getCurrentHub)().getClient(); - if (client && (0,_sdk_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSessionTrackingEnabled)(client)) { - // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the - // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only - // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be - // running in SessionAggregates mode - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - const isSessionAggregatesMode = (client )._sessionFlusher !== undefined; - if (isSessionAggregatesMode) { - const requestSession = _scope.getRequestSession(); - // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a - // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within - // the bounds of a request, and if so the status is updated - if (requestSession && requestSession.status !== undefined) { - requestSession.status = 'crashed'; - } - } - } + return validator ? validator(value, opt, opts) : true; + }; +}; - const eventId = (0,_sentry_core__WEBPACK_IMPORTED_MODULE_11__.captureException)(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - (res ).sentry = eventId; - next(error); - }); +/** + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + */ - return; +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; } - - next(error); - }; + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } } -// TODO (v8 / #5257): Remove this -// eslint-disable-next-line deprecation/deprecation -; - - -//# sourceMappingURL=handlers.js.map +module.exports = { + assertOptions: assertOptions, + validators: validators +}; /***/ }), /* 1716 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "extractRequestData": () => (/* binding */ extractRequestData), -/* harmony export */ "parseRequest": () => (/* binding */ parseRequest) -/* harmony export */ }); -/* harmony import */ var _requestdata_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1705); -/** - * @deprecated `Handlers.ExpressRequest` is deprecated and will be removed in v8. Use `PolymorphicRequest` instead. - */ +var CanceledError = __webpack_require__(1704); /** - * Normalizes data from the request object, accounting for framework differences. - * - * @deprecated `Handlers.extractRequestData` is deprecated and will be removed in v8. Use `extractRequestData` instead. + * A `CancelToken` is an object that can be used to request cancellation of an operation. * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. - * @returns An object containing normalized request data + * @class + * @param {Function} executor The executor function. */ -function extractRequestData(req, keys) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.extractRequestData)(req, { include: keys }); +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + + // eslint-disable-next-line func-names + this.promise.then(function(cancel) { + if (!token._listeners) return; + + var i; + var l = token._listeners.length; + + for (i = 0; i < l; i++) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = function(onfulfilled) { + var _resolve; + // eslint-disable-next-line func-names + var promise = new Promise(function(resolve) { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message); + resolvePromise(token.reason); + }); } /** - * Options deciding what parts of the request to use when enhancing an event - * - * @deprecated `Handlers.ParseRequestOptions` is deprecated and will be removed in v8. Use - * `AddRequestDataToEventOptions` in `@sentry/utils` instead. + * Throws a `CanceledError` if cancellation has been requested. */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; /** - * Enriches passed event with request data. - * - * @deprecated `Handlers.parseRequest` is deprecated and will be removed in v8. Use `addRequestDataToEvent` instead. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden + * Subscribe to the cancel signal */ -function parseRequest(event, req, options = {}) { - return (0,_requestdata_js__WEBPACK_IMPORTED_MODULE_0__.addRequestDataToEvent)(event, req, { include: options }); -} +CancelToken.prototype.subscribe = function subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } -//# sourceMappingURL=requestDataDeprecated.js.map + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } +}; + +/** + * Unsubscribe from the cancel signal + */ + +CancelToken.prototype.unsubscribe = function unsubscribe(listener) { + if (!this._listeners) { + return; + } + var index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +module.exports = CancelToken; /***/ }), /* 1717 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TRACEPARENT_REGEXP": () => (/* binding */ TRACEPARENT_REGEXP), -/* harmony export */ "extractTraceparentData": () => (/* binding */ extractTraceparentData) -/* harmony export */ }); -const TRACEPARENT_REGEXP = new RegExp( - '^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$', // whitespace -); + /** - * Extract transaction context data from a `sentry-trace` header. + * Syntactic sugar for invoking a function and expanding an array for arguments. * - * @param traceparent Traceparent string + * Common use case would be to use `Function.prototype.apply`. * - * @returns Object containing data from the header, or undefined if traceparent string is malformed + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} */ -function extractTraceparentData(traceparent) { - const matches = traceparent.match(TRACEPARENT_REGEXP); - - if (!traceparent || !matches) { - // empty string or no matches is invalid traceparent data - return undefined; - } - - let parentSampled; - if (matches[3] === '1') { - parentSampled = true; - } else if (matches[3] === '0') { - parentSampled = false; - } - - return { - traceId: matches[1], - parentSampled, - parentSpanId: matches[2], +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); }; -} - - -//# sourceMappingURL=tracing.js.map +}; /***/ }), /* 1718 */ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "FunctionToString": () => (/* reexport safe */ _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__.FunctionToString), -/* harmony export */ "InboundFilters": () => (/* reexport safe */ _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__.InboundFilters) -/* harmony export */ }); -/* harmony import */ var _functiontostring_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1712); -/* harmony import */ var _inboundfilters_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1711); -//# sourceMappingURL=index.js.map +var utils = __webpack_require__(1684); + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +}; /***/ }), @@ -246189,9 +246228,9 @@ __webpack_require__.r(__webpack_exports__); const { log, errors } = __webpack_require__(1) const soapRequest = __webpack_require__(1375) const { parseTags, parseValue } = __webpack_require__(1599) -const { commanderArretServiceSouscritMesures } = __webpack_require__(1600) +const { commanderArretServiceSouscritMesures } = __webpack_require__(1680) const xml2js = __webpack_require__(1557) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) /** * @param {string} url @@ -246225,10 +246264,19 @@ async function terminateContract( serviceId ), }).catch(err => { - log('error', 'commanderArretServiceSouscritMesures') - log('error', err) - Sentry.captureException('commanderArretServiceSouscritMesures', err) - throw errors.VENDOR_DOWN + const errorMessage = 'Error while terminating contract : ' + err + log('error', errorMessage) + Sentry.captureException(errorMessage, { + tags: { + section: 'terminateContract', + }, + extra: { + contractId: contractId, + pointId: pointId, + serviceId: serviceId, + }, + }) + throw new Error(errors.VENDOR_DOWN) }) const parsedReply = await xml2js.parseStringPromise(response.body, { @@ -246251,8 +246299,15 @@ async function terminateContract( 'Error while parsing user contract termination: ' + error log('error', errorMessage) log('error', `Enedis issue ${JSON.stringify(parsedReply.Envelope.Body)}`) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { + section: 'terminateContract', + }, + extra: { + pointId: pointId, + }, + }) + throw new Error(errors.VENDOR_DOWN) } } @@ -246394,7 +246449,13 @@ module.exports = { isLocal, isDev } /* 1766 */, /* 1767 */, /* 1768 */, -/* 1769 */, +/* 1769 */ +/***/ ((module) => { + +"use strict"; +module.exports = JSON.parse('{"name":"enedissgegrandlyon","version":"1.3.2","description":"","repository":{"type":"https","url":"https://forge.grandlyon.com/web-et-numerique/llle_project/enedis-sge-konnector"},"keywords":[],"main":"./src/index.js","author":"Cozy Cloud","license":"AGPL-3.0","eslintConfig":{"extends":["cozy-app"]},"eslintIgnore":["build","data"],"husky":{"hooks":{"pre-commit":"yarn lint"}},"jest":{"setupFiles":["./setupTests.js"]},"scripts":{"build":"webpack","clean":"rm -rf ./data","cozyPublish":"cozy-app-publish --token $REGISTRY_TOKEN --build-commit $(git rev-parse ${DEPLOY_BRANCH:-build})","deploy":"git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build}","deploy-dev":"git-directory-deploy --directory build/ --branch ${DEPLOY_BRANCH:-build-dev}","dev":"cozy-konnector-dev","lint":"eslint --fix .","onDeleteAccount:standalone":"cozy-konnector-standalone src/onDeleteAccount.js","onDeleteAccount":"cozy-konnector-dev src/onDeleteAccount.js","pretest":"npm run clean","release":"standard-version --no-verify","standalone":"cozy-konnector-standalone","standalone-no-data":"NO_DATA=true cozy-konnector-standalone src/index.js","start":"node ./src/index.js","test:cov":"jest --coverage","test":"jest","travisDeployKey":"./bin/generate_travis_deploy_key"},"dependencies":{"@sentry/node":"^7.23.0","@sentry/tracing":"^7.23.0","axios":"^0.27.2","cozy-konnector-libs":"5.0.0","easy-soap-request":"^4.7.0","jest":"^28.1.3","moment":"^2.29.3","moment-timezone":"^0.5.34","xml2js":"^0.4.23"},"devDependencies":{"cozy-jobs-cli":"2.0.0","cozy-konnector-build":"1.4.5","eslint-config-cozy-app":"5.5.0","eslint-plugin-prettier":"^4.2.1","git-directory-deploy":"1.5.1","jest-junit":"^14.0.0","standard-version":"^9.5.0"}}'); + +/***/ }), /* 1770 */ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { @@ -246405,17 +246466,37 @@ const { getAccountSecret, getAccountId, } = __webpack_require__(1771) -const { getBoConsent, deleteBoConsent } = __webpack_require__(1601) +const { getBoConsent, deleteBoConsent } = __webpack_require__(1681) const { terminateContract } = __webpack_require__(1722) const { getAccountForDelete } = __webpack_require__(1730) const moment = __webpack_require__(1417) __webpack_require__(1554) const { isLocal, isDev } = __webpack_require__(1731) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) +const { version } = __webpack_require__(1769) moment.locale('fr') // set the language moment.tz.setDefault('Europe/Paris') // set the timezone +/** + * Sentry + */ +Sentry.init({ + dsn: 'https://18747a93401447f2a81b83cd8c4bbbdf@grandlyon.errors.cozycloud.cc/5', + + // Set tracesSampleRate to 1.0 to capture 100% + // of transactions for performance monitoring. + // We recommend adjusting this value in production + tracesSampleRate: isLocal() ? 0 : 1.0, + release: version, + environment: isDev() ? 'development' : 'production', + debug: isDev(), + integrations: [ + // enable HTTP calls tracing + new Sentry.Integrations.Http({ tracing: true }), + ], +}) + async function onDeleteAccount() { try { log('info', 'Deleting account ...') @@ -246469,8 +246550,7 @@ async function onDeleteAccount() { } else { const errorMessage = `No service id retrieved from BO` log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + throw new Error(errorMessage) } } @@ -246479,8 +246559,7 @@ async function onDeleteAccount() { const errorMessage = 'No account revision was found, something went wrong during the deletion of said account' log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + throw new Error(errorMessage) } } catch (error) { log('debug', 'error catched in onDeleteAccount()', error) @@ -246498,8 +246577,10 @@ onDeleteAccount().then( err => { const errorMessage = `onDeleteAccount: An error occurred during script: ${err.message}` log('error', errorMessage) - Sentry.captureException(errorMessage) - throw errors.VENDOR_DOWN + Sentry.captureException(errorMessage, { + tags: { section: 'onDeleteAccount' }, + }) + throw new Error(errors.VENDOR_DOWN) } ) @@ -246512,7 +246593,7 @@ module.exports = { onDeleteAccount } const { log } = __webpack_require__(1) const { isLocal } = __webpack_require__(1731) -const Sentry = __webpack_require__(1639) +const Sentry = __webpack_require__(1600) function getAccountId() { log('info', `getAccountId`) -- GitLab