/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/helpers.js" /*!**********************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/attribution/helpers.js ***! \**********************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ KNOWN_2LDS: () => (/* binding */ KNOWN_2LDS), /* harmony export */ createCampaignEvent: () => (/* binding */ createCampaignEvent), /* harmony export */ getDefaultExcludedReferrers: () => (/* binding */ getDefaultExcludedReferrers), /* harmony export */ getDomain: () => (/* binding */ getDomain), /* harmony export */ isExcludedReferrer: () => (/* binding */ isExcludedReferrer), /* harmony export */ isNewCampaign: () => (/* binding */ isNewCampaign), /* harmony export */ isSubdomainOf: () => (/* binding */ isSubdomainOf) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/identify.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/event-builder.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); /* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types */ "./node_modules/@amplitude/analytics-core/lib/esm/types/config/browser-config.js"); var domainWithoutSubdomain = function (domain) { var parts = domain.split('.'); if (parts.length <= 2) { return domain; } return parts.slice(parts.length - 2, parts.length).join('.'); }; //Direct traffic mean no external referral, no UTMs, no click-ids, and no other customer identified marketing campaign url params. var isDirectTraffic = function (current) { return Object.values(current).every(function (value) { return !value; }); }; var isEmptyCampaign = function (campaign) { var campaignWithoutReferrer = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, campaign), { referring_domain: undefined, referrer: undefined }); return Object.values(campaignWithoutReferrer).every(function (value) { return !value; }); }; var isNewCampaign = function (current, previous, options, logger, isNewSession, topLevelDomain) { if (isNewSession === void 0) { isNewSession = true; } var referrer = current.referrer, referring_domain = current.referring_domain, currentCampaign = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__rest)(current, ["referrer", "referring_domain"]); var _a = previous || {}, _previous_referrer = _a.referrer, prevReferringDomain = _a.referring_domain, previousCampaign = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__rest)(_a, ["referrer", "referring_domain"]); var excludeInternalReferrers = options.excludeInternalReferrers; if (excludeInternalReferrers) { var condition = getExcludeInternalReferrersCondition(excludeInternalReferrers, logger); if (!(condition instanceof TypeError) && current.referring_domain && isInternalReferrer(current.referring_domain, topLevelDomain)) { if (condition === 'always') { debugLogInternalReferrerExclude(condition, current.referring_domain, logger); return false; } else if (condition === 'ifEmptyCampaign' && isEmptyCampaign(current)) { debugLogInternalReferrerExclude(condition, current.referring_domain, logger); return false; } } } if (isExcludedReferrer(options.excludeReferrers, current.referring_domain)) { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions logger.debug("This is not a new campaign because ".concat(current.referring_domain, " is in the exclude referrer list.")); return false; } //In the same session, direct traffic should not override or unset any persisting query params if (!isNewSession && isDirectTraffic(current) && previous) { logger.debug('This is not a new campaign because this is a direct traffic in the same session.'); return false; } var hasNewCampaign = JSON.stringify(currentCampaign) !== JSON.stringify(previousCampaign); var hasNewDomain = domainWithoutSubdomain(referring_domain || '') !== domainWithoutSubdomain(prevReferringDomain || ''); var result = !previous || hasNewCampaign || hasNewDomain; if (!result) { logger.debug("This is not a new campaign because it's the same as the previous one."); } else { logger.debug("This is a new campaign. An $identify event will be sent."); } return result; }; var isExcludedReferrer = function (excludeReferrers, referringDomain) { if (excludeReferrers === void 0) { excludeReferrers = []; } if (referringDomain === void 0) { referringDomain = ''; } return excludeReferrers.some(function (value) { return value instanceof RegExp ? value.test(referringDomain) : value === referringDomain; }); }; var isSubdomainOf = function (subDomain, domain) { var cookieDomainWithLeadingDot = domain.startsWith('.') ? domain : ".".concat(domain); var subDomainWithLeadingDot = subDomain.startsWith('.') ? subDomain : ".".concat(subDomain); if (subDomainWithLeadingDot.endsWith(cookieDomainWithLeadingDot)) return true; return false; }; var createCampaignEvent = function (campaign, options) { var campaignParameters = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.BASE_CAMPAIGN), campaign); var identifyEvent = Object.entries(campaignParameters).reduce(function (identify, _a) { var _b; var _c = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_a, 2), key = _c[0], value = _c[1]; identify.setOnce("initial_".concat(key), (_b = value !== null && value !== void 0 ? value : options.initialEmptyValue) !== null && _b !== void 0 ? _b : 'EMPTY'); if (value) { return identify.set(key, value); } return identify.unset(key); }, new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.Identify()); return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.createIdentifyEvent)(identifyEvent); }; var getDefaultExcludedReferrers = function (cookieDomain) { var domain = cookieDomain; if (domain) { if (domain.startsWith('.')) { domain = domain.substring(1); } return [new RegExp("".concat(domain.replace('.', '\\.'), "$"))]; } return []; }; /** * Parses the excludeInternalReferrers configuration to determine the condition on which to * exclude internal referrers for campaign attribution. * * If the config is invalid type, log and return a TypeError. * * (this does explicit type checking so don't have to rely on TS compiler to catch invalid types) * * @param excludeInternalReferrers - attribution.excludeInternalReferrers configuration * @param logger - logger instance to log error when TypeError * @returns The condition if the config is valid, TypeError if the config is invalid. */ var getExcludeInternalReferrersCondition = function (excludeInternalReferrers, logger) { if (excludeInternalReferrers === true) { return _types__WEBPACK_IMPORTED_MODULE_5__.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS.always; } if (typeof excludeInternalReferrers === 'object') { var condition = excludeInternalReferrers.condition; if (typeof condition === 'string' && Object.keys(_types__WEBPACK_IMPORTED_MODULE_5__.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS).includes(condition)) { return condition; } else if (typeof condition === 'undefined') { return _types__WEBPACK_IMPORTED_MODULE_5__.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS.always; } } var errorMessage = "Invalid configuration provided for attribution.excludeInternalReferrers: ".concat(JSON.stringify(excludeInternalReferrers)); logger.error(errorMessage); return new TypeError(errorMessage); }; // helper function to log debug message when internal referrer is excluded // (added this to prevent code duplication and improve readability) function debugLogInternalReferrerExclude(condition, referringDomain, logger) { var baseMessage = "This is not a new campaign because referring_domain=".concat(referringDomain, " is on the same domain as the current page and it is configured to exclude internal referrers"); if (condition === 'always') { logger.debug(baseMessage); } else if (condition === 'ifEmptyCampaign') { logger.debug("".concat(baseMessage, " with empty campaign parameters")); } } // list of domains that are known ccTLDs that are commonly used // and are in the Public Suffix List (https://publicsuffix.org/) var KNOWN_2LDS = [ 'ac.in', 'ac.jp', 'ac.kr', 'ac.th', 'ac.uk', 'ac.za', 'appspot.com', 'asn.au', 'azurewebsites.net', 'cloudfront.net', 'myshopify.com', 'blogspot.com', 'co.ca', 'co.in', 'co.jp', 'co.kr', 'co.nz', 'co.th', 'co.uk', 'co.za', 'com.ar', 'com.au', 'com.br', 'com.cn', 'com.hk', 'com.in', 'com.jp', 'com.kr', 'com.mx', 'com.pl', 'com.sg', 'com.tr', 'com.tw', 'ed.jp', 'edu.au', 'edu.br', 'edu.cn', 'edu.hk', 'edu.sg', 'edu.th', 'edu.tr', 'edu.tw', 'firebaseapp.com', 'fly.dev', 'gc.ca', 'geek.nz', 'github.io', 'gitlab.io', 'go.jp', 'go.kr', 'go.th', 'gob.ar', 'gob.mx', 'gov.au', 'gov.br', 'gov.cn', 'gov.hk', 'gov.in', 'gov.pl', 'gov.sg', 'gov.tr', 'gov.tw', 'gov.uk', 'gov.za', 'govt.nz', 'gr.jp', 'herokuapp.com', 'id.au', 'idv.hk', 'iwi.nz', 'lg.jp', 'ltd.uk', 'maori.nz', 'me.uk', 'mil.kr', 'ne.jp', 'ne.kr', 'net.au', 'net.br', 'net.cn', 'net.hk', 'net.in', 'net.nz', 'net.pl', 'net.sg', 'net.tr', 'net.tw', 'net.za', 'onrender.com', 'or.jp', 'or.kr', 'or.th', 'org.ar', 'org.au', 'org.br', 'org.cn', 'org.hk', 'org.in', 'org.mx', 'org.nz', 'org.pl', 'org.sg', 'org.tw', 'org.uk', 'org.za', 'pages.dev', 'pe.kr', 'plc.uk', 're.kr', 'res.in', 'sch.uk', 'vercel.app', 'netlify.app', 'workers.dev', ]; var getDomain = function (hostnameParam) { var _a, _b; /* istanbul ignore next */ var hostname = hostnameParam || ((_b = (_a = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getGlobalScope)()) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.hostname); if (!hostname) { return ''; } var parts = hostname.split('.'); var tld = parts[parts.length - 1]; var name = parts[parts.length - 2]; if (KNOWN_2LDS.find(function (tld) { return hostname.endsWith(".".concat(tld)); })) { tld = parts[parts.length - 2] + '.' + parts[parts.length - 1]; name = parts[parts.length - 3]; } if (!name) return tld; return "".concat(name, ".").concat(tld); }; var isInternalReferrer = function (referringDomain, topLevelDomain) { var globalScope = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getGlobalScope)(); /* istanbul ignore if */ if (!globalScope) return false; // if referring domain is subdomain of config.cookieDomain, return true var internalDomain = (topLevelDomain || '').trim() || getDomain(globalScope.location.hostname); return isSubdomainOf(referringDomain, internalDomain); }; //# sourceMappingURL=helpers.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/tracking-methods.js" /*!*******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/attribution/tracking-methods.js ***! \*******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EVENT_PROPERTY_TRACKING_METHOD: () => (/* binding */ EVENT_PROPERTY_TRACKING_METHOD), /* harmony export */ USER_PROPERTY_TRACKING_METHOD: () => (/* binding */ USER_PROPERTY_TRACKING_METHOD), /* harmony export */ hasTrackingMethod: () => (/* binding */ hasTrackingMethod), /* harmony export */ isEventPropertyAttributionEnabled: () => (/* binding */ isEventPropertyAttributionEnabled), /* harmony export */ isUserPropertyAttributionEnabled: () => (/* binding */ isUserPropertyAttributionEnabled), /* harmony export */ normalizeTrackingMethod: () => (/* binding */ normalizeTrackingMethod) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); var USER_PROPERTY_TRACKING_METHOD = 'userProperty'; var EVENT_PROPERTY_TRACKING_METHOD = 'eventProperty'; var isTrackingMethod = function (value) { return value === USER_PROPERTY_TRACKING_METHOD || value === EVENT_PROPERTY_TRACKING_METHOD; }; /** * Normalizes attribution tracking methods from runtime config, drops unsupported values, * and falls back to the legacy default when nothing valid is provided. */ var normalizeTrackingMethod = function (trackingMethod) { var normalized = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(new Set((Array.isArray(trackingMethod) ? trackingMethod : [trackingMethod]).filter(isTrackingMethod))), false); return normalized.length > 0 ? normalized : [USER_PROPERTY_TRACKING_METHOD]; }; var hasTrackingMethod = function (options, trackingMethod) { return normalizeTrackingMethod(options.trackingMethod).includes(trackingMethod); }; var isUserPropertyAttributionEnabled = function (options) { return hasTrackingMethod(options, USER_PROPERTY_TRACKING_METHOD); }; var isEventPropertyAttributionEnabled = function (options) { return hasTrackingMethod(options, EVENT_PROPERTY_TRACKING_METHOD); }; //# sourceMappingURL=tracking-methods.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/web-attribution.js" /*!******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/attribution/web-attribution.js ***! \******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ WebAttribution: () => (/* binding */ WebAttribution) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/session.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/storage/helpers.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/campaign/campaign-parser.js"); /* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./helpers */ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/helpers.js"); var WebAttribution = /** @class */ (function () { function WebAttribution(options, config) { var _a; this.shouldTrackNewCampaign = false; this.options = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ initialEmptyValue: 'EMPTY', resetSessionOnNewCampaign: false, excludeReferrers: (0,_helpers__WEBPACK_IMPORTED_MODULE_5__.getDefaultExcludedReferrers)(((_a = config.cookieOptions) === null || _a === void 0 ? void 0 : _a.domain) || config.topLevelDomain), optOut: config.optOut }, options); this.storage = config.cookieStorage; this.storageKey = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getStorageKey)(config.apiKey, 'MKTG'); this.webExpStorageKey = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getStorageKey)(config.apiKey, 'MKTG_ORIGINAL'); this.currentCampaign = _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.BASE_CAMPAIGN; this.sessionTimeout = config.sessionTimeout; this.lastEventTime = config.lastEventTime; this.logger = config.loggerProvider; this.topLevelDomain = config.topLevelDomain; config.loggerProvider.log('Installing web attribution tracking.'); } WebAttribution.prototype.init = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var isEventInNewSession; var _a; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: // skip attribution if optOut is true if (this.options.optOut) { return [2 /*return*/]; } return [4 /*yield*/, this.fetchCampaign()]; case 1: _a = tslib__WEBPACK_IMPORTED_MODULE_0__.__read.apply(void 0, [_b.sent(), 2]), this.currentCampaign = _a[0], this.previousCampaign = _a[1]; isEventInNewSession = !this.lastEventTime ? true : (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.isNewSession)(this.sessionTimeout, this.lastEventTime); if (!(0,_helpers__WEBPACK_IMPORTED_MODULE_5__.isNewCampaign)(this.currentCampaign, this.previousCampaign, this.options, this.logger, isEventInNewSession, this.topLevelDomain)) return [3 /*break*/, 3]; this.shouldTrackNewCampaign = true; return [4 /*yield*/, this.storage.set(this.storageKey, this.currentCampaign)]; case 2: _b.sent(); _b.label = 3; case 3: return [2 /*return*/]; } }); }); }; WebAttribution.prototype.fetchCampaign = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var originalCampaign; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.storage.get(this.webExpStorageKey)]; case 1: originalCampaign = _a.sent(); if (!originalCampaign) return [3 /*break*/, 3]; return [4 /*yield*/, this.storage.remove(this.webExpStorageKey)]; case 2: _a.sent(); _a.label = 3; case 3: return [4 /*yield*/, Promise.all([originalCampaign || new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.CampaignParser().parse(), this.storage.get(this.storageKey)])]; case 4: return [2 /*return*/, _a.sent()]; } }); }); }; /** * This can be called when enable web attribution and either * 1. set a new session * 2. has new campaign and enable resetSessionOnNewCampaign */ WebAttribution.prototype.generateCampaignEvent = function (event_id) { // Mark this campaign has been tracked this.shouldTrackNewCampaign = false; var campaignEvent = (0,_helpers__WEBPACK_IMPORTED_MODULE_5__.createCampaignEvent)(this.currentCampaign, this.options); if (event_id) { campaignEvent.event_id = event_id; } return campaignEvent; }; WebAttribution.prototype.shouldSetSessionIdOnNewCampaign = function () { return this.shouldTrackNewCampaign && !!this.options.resetSessionOnNewCampaign; }; return WebAttribution; }()); //# sourceMappingURL=web-attribution.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/browser-client-factory.js" /*!*************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/browser-client-factory.js ***! \*************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ createInstance: () => (/* binding */ createInstance), /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/debug.js"); /* harmony import */ var _browser_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./browser-client */ "./node_modules/@amplitude/analytics-browser/lib/esm/browser-client.js"); var createInstance = function () { var client = new _browser_client__WEBPACK_IMPORTED_MODULE_1__.AmplitudeBrowser(); return { init: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.init.bind(client), 'init', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), add: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.add.bind(client), 'add', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.plugins'])), remove: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.remove.bind(client), 'remove', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.plugins'])), track: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.track.bind(client), 'track', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), logEvent: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.logEvent.bind(client), 'logEvent', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), identify: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.identify.bind(client), 'identify', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), groupIdentify: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.groupIdentify.bind(client), 'groupIdentify', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), setGroup: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setGroup.bind(client), 'setGroup', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), revenue: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.revenue.bind(client), 'revenue', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), flush: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.flush.bind(client), 'flush', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config.apiKey', 'timeline.queue.length'])), getUserId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.getUserId.bind(client), 'getUserId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.userId'])), setUserId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setUserId.bind(client), 'setUserId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.userId'])), getDeviceId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.getDeviceId.bind(client), 'getDeviceId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.deviceId'])), setDeviceId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setDeviceId.bind(client), 'setDeviceId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.deviceId'])), reset: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.reset.bind(client), 'reset', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.userId', 'config.deviceId'])), getSessionId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.getSessionId.bind(client), 'getSessionId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), setSessionId: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setSessionId.bind(client), 'setSessionId', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), extendSession: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.extendSession.bind(client), 'extendSession', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), setOptOut: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setOptOut.bind(client), 'setOptOut', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), setTransport: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setTransport.bind(client), 'setTransport', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), getIdentity: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.getIdentity.bind(client), 'getIdentity', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), setIdentity: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.setIdentity.bind(client), 'setIdentity', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config', 'config.userId', 'config.deviceId'])), getOptOut: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client.getOptOut.bind(client), 'getOptOut', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), _setDiagnosticsSampleRate: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.debugWrapper)(client._setDiagnosticsSampleRate.bind(client), '_setDiagnosticsSampleRate', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientLogConfig)(client), (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.getClientStates)(client, ['config'])), }; }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createInstance()); //# sourceMappingURL=browser-client-factory.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/browser-client.js" /*!*****************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/browser-client.js ***! \*****************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AmplitudeBrowser: () => (/* binding */ AmplitudeBrowser) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/core-client.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/identify.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/revenue.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/plugins/destination.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/plugins/identity.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/logger.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/analytics-connector.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/session.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/query-params.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/return-wrapper.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/uuid.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/event-builder.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-client.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/remote-config/remote-config.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/loglevel.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/offline.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/safe-stringify.js"); /* harmony import */ var _default_tracking__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./default-tracking */ "./node_modules/@amplitude/analytics-browser/lib/esm/default-tracking.js"); /* harmony import */ var _utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./utils/snippet-helper */ "./node_modules/@amplitude/analytics-browser/lib/esm/utils/snippet-helper.js"); /* harmony import */ var _plugins_context__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./plugins/context */ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/context.js"); /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./config */ "./node_modules/@amplitude/analytics-browser/lib/esm/config.js"); /* harmony import */ var _amplitude_plugin_page_view_tracking_browser__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @amplitude/plugin-page-view-tracking-browser */ "./node_modules/@amplitude/plugin-page-view-tracking-browser/lib/esm/page-view-tracking.js"); /* harmony import */ var _plugins_form_interaction_tracking__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./plugins/form-interaction-tracking */ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/form-interaction-tracking.js"); /* harmony import */ var _plugins_file_download_tracking__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./plugins/file-download-tracking */ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/file-download-tracking.js"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./constants */ "./node_modules/@amplitude/analytics-browser/lib/esm/constants.js"); /* harmony import */ var _det_notification__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./det-notification */ "./node_modules/@amplitude/analytics-browser/lib/esm/det-notification.js"); /* harmony import */ var _plugins_network_connectivity_checker__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./plugins/network-connectivity-checker */ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/network-connectivity-checker.js"); /* harmony import */ var _config_joined_config__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./config/joined-config */ "./node_modules/@amplitude/analytics-browser/lib/esm/config/joined-config.js"); /* harmony import */ var _amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! @amplitude/plugin-autocapture-browser */ "./node_modules/@amplitude/plugin-autocapture-browser/lib/esm/autocapture-plugin.js"); /* harmony import */ var _amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! @amplitude/plugin-autocapture-browser */ "./node_modules/@amplitude/plugin-autocapture-browser/lib/esm/frustration-plugin.js"); /* harmony import */ var _amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! @amplitude/plugin-autocapture-browser */ "./node_modules/@amplitude/plugin-autocapture-browser/lib/esm/performance-plugin.js"); /* harmony import */ var _amplitude_plugin_network_capture_browser__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! @amplitude/plugin-network-capture-browser */ "./node_modules/@amplitude/plugin-network-capture-browser/lib/esm/network-capture-plugin.js"); /* harmony import */ var _amplitude_plugin_web_vitals_browser__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @amplitude/plugin-web-vitals-browser */ "./node_modules/@amplitude/plugin-web-vitals-browser/lib/esm/web-vitals-plugin.js"); /* harmony import */ var _attribution_web_attribution__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./attribution/web-attribution */ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/web-attribution.js"); /* harmony import */ var _amplitude_plugin_event_property_attribution_browser__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @amplitude/plugin-event-property-attribution-browser */ "./node_modules/@amplitude/plugin-event-property-attribution-browser/lib/esm/event-property-tracking.js"); /* harmony import */ var _lib_prefix__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./lib-prefix */ "./node_modules/@amplitude/analytics-browser/lib/esm/lib-prefix.js"); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./version */ "./node_modules/@amplitude/analytics-browser/lib/esm/version.js"); /* harmony import */ var _amplitude_plugin_page_url_enrichment_browser__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! @amplitude/plugin-page-url-enrichment-browser */ "./node_modules/@amplitude/plugin-page-url-enrichment-browser/lib/esm/page-url-enrichment.js"); /* harmony import */ var _amplitude_plugin_custom_enrichment_browser__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! @amplitude/plugin-custom-enrichment-browser */ "./node_modules/@amplitude/plugin-custom-enrichment-browser/lib/esm/custom-enrichment.js"); /* harmony import */ var _attribution_tracking_methods__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./attribution/tracking-methods */ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/tracking-methods.js"); var UNSPECIFIED_SESSION_ID = -1; /** * Exported for `@amplitude/unified` or integration with blade plugins. * If you only use `@amplitude/analytics-browser`, use `amplitude.init()` or `amplitude.createInstance()` instead. */ var AmplitudeBrowser = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(AmplitudeBrowser, _super); function AmplitudeBrowser() { var _this = _super !== null && _super.apply(this, arguments) || this; // Backdoor to set diagnostics sample rate // by calling amplitude._setDiagnosticsSampleRate(1); before amplitude.init() _this._diagnosticsSampleRate = 0; return _this; } AmplitudeBrowser.prototype.init = function (apiKey, userIdOrOptions, maybeOptions) { if (apiKey === void 0) { apiKey = ''; } var userId; var options; if (arguments.length > 2) { userId = userIdOrOptions; options = maybeOptions; } else { if (typeof userIdOrOptions === 'string') { userId = userIdOrOptions; options = undefined; } else { userId = userIdOrOptions === null || userIdOrOptions === void 0 ? void 0 : userIdOrOptions.userId; options = userIdOrOptions; } } return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__.returnWrapper)(this._init((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, options), { userId: userId, apiKey: apiKey }))); }; AmplitudeBrowser.prototype._init = function (options) { var _a, _b, _c, _d, _e, _f, _g, _h; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var fetchRemoteConfig, loggerProvider, serverZone, remoteConfigClient, diagnosticsSampleRate, enableDiagnostics, diagnosticsClient, browserOptions, attributionTrackingOptions, queryParams, ampTimestamp, isWithinTimeLimit, querySessionId, deferredSessionId, connector; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_j) { switch (_j.label) { case 0: // Step 1: Block concurrent initialization if (this.initializing) { return [2 /*return*/]; } this.initializing = true; fetchRemoteConfig = (0,_config__WEBPACK_IMPORTED_MODULE_21__.shouldFetchRemoteConfig)(options); loggerProvider = (_a = options.loggerProvider) !== null && _a !== void 0 ? _a : new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__.Logger(); if (!options.loggerProvider) { loggerProvider.enable((_b = options.logLevel) !== null && _b !== void 0 ? _b : _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_15__.LogLevel.Warn); } serverZone = (_c = options.serverZone) !== null && _c !== void 0 ? _c : _constants__WEBPACK_IMPORTED_MODULE_25__.DEFAULT_SERVER_ZONE; diagnosticsSampleRate = this._diagnosticsSampleRate; enableDiagnostics = (_d = options.enableDiagnostics) !== null && _d !== void 0 ? _d : true; if (!fetchRemoteConfig) return [3 /*break*/, 2]; remoteConfigClient = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_14__.RemoteConfigClient(options.apiKey, loggerProvider, serverZone, /* istanbul ignore next */ (_e = options.remoteConfig) === null || _e === void 0 ? void 0 : _e.serverUrl); // Fetch diagnostics config first to get sample rate return [4 /*yield*/, new Promise(function (resolve) { // Disable coverage for this line because remote config client will always be defined in this case. // istanbul ignore next remoteConfigClient === null || remoteConfigClient === void 0 ? void 0 : remoteConfigClient.subscribe('configs.diagnostics.browserSDK', 'all', function (remoteConfig, source, lastFetch) { loggerProvider.debug('Diagnostics remote configuration received:', JSON.stringify({ remoteConfig: remoteConfig, source: source, lastFetch: lastFetch, }, null, 2)); if (remoteConfig) { // Validate and set sampleRate (must be a valid number) var sampleRate = remoteConfig.sampleRate; if (typeof sampleRate === 'number' && !isNaN(sampleRate)) { diagnosticsSampleRate = sampleRate; } // Validate and set enabled (must be a boolean) var enabled = remoteConfig.enabled; if (typeof enabled === 'boolean') { enableDiagnostics = enabled; } } resolve(); }); })]; case 1: // Fetch diagnostics config first to get sample rate _j.sent(); _j.label = 2; case 2: diagnosticsClient = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_13__.DiagnosticsClient(options.apiKey, loggerProvider, serverZone, { enabled: enableDiagnostics, sampleRate: diagnosticsSampleRate, }); diagnosticsClient.setTag('library', "".concat(_lib_prefix__WEBPACK_IMPORTED_MODULE_36__.LIBPREFIX, "/").concat(_version__WEBPACK_IMPORTED_MODULE_37__.VERSION)); if (typeof navigator !== 'undefined') { diagnosticsClient.setTag('user_agent', navigator.userAgent); } return [4 /*yield*/, (0,_config__WEBPACK_IMPORTED_MODULE_21__.useBrowserConfig)(options.apiKey, options, this, diagnosticsClient, { loggerProvider: loggerProvider, serverZone: serverZone, enableDiagnostics: enableDiagnostics, diagnosticsSampleRate: diagnosticsSampleRate, })]; case 3: browserOptions = _j.sent(); if (!(fetchRemoteConfig && remoteConfigClient)) return [3 /*break*/, 5]; return [4 /*yield*/, new Promise(function (resolve) { // Disable coverage for this line because remote config client will always be defined in this case. // istanbul ignore next remoteConfigClient === null || remoteConfigClient === void 0 ? void 0 : remoteConfigClient.subscribe('configs.analyticsSDK.browserSDK', 'all', function (remoteConfig, source, lastFetch) { browserOptions.loggerProvider.debug('Remote configuration received:', JSON.stringify({ remoteConfig: remoteConfig, source: source, lastFetch: lastFetch, }, null, 2)); if (remoteConfig) { (0,_config_joined_config__WEBPACK_IMPORTED_MODULE_28__.updateBrowserConfigWithRemoteConfig)(remoteConfig, browserOptions); } // Resolve the promise on first callback (initial config) resolve(); }); })]; case 4: _j.sent(); _j.label = 5; case 5: return [4 /*yield*/, _super.prototype._init.call(this, browserOptions)]; case 6: _j.sent(); this.logBrowserOptions(browserOptions); this.config.remoteConfigClient = remoteConfigClient; attributionTrackingOptions = (0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getAttributionTrackingConfig)(this.config); if (!((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isAttributionTrackingEnabled)(this.config.defaultTracking) && (0,_attribution_tracking_methods__WEBPACK_IMPORTED_MODULE_40__.isUserPropertyAttributionEnabled)(attributionTrackingOptions))) return [3 /*break*/, 8]; if (this.config.optOut) { this.timeline.addOptOutListener(function (optOut) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(_this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (!!optOut) return [3 /*break*/, 2]; this.webAttribution = new _attribution_web_attribution__WEBPACK_IMPORTED_MODULE_34__.WebAttribution(attributionTrackingOptions, this.config); return [4 /*yield*/, this.webAttribution.init()]; case 1: _a.sent(); _a.label = 2; case 2: return [2 /*return*/]; } }); }); }); } this.webAttribution = new _attribution_web_attribution__WEBPACK_IMPORTED_MODULE_34__.WebAttribution(attributionTrackingOptions, this.config); // Fetch the current campaign, check if need to track web attribution later return [4 /*yield*/, this.webAttribution.init()]; case 7: // Fetch the current campaign, check if need to track web attribution later _j.sent(); _j.label = 8; case 8: queryParams = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_9__.getQueryParams)(); ampTimestamp = queryParams.ampTimestamp ? Number(queryParams.ampTimestamp) : undefined; isWithinTimeLimit = ampTimestamp ? Date.now() < ampTimestamp : true; querySessionId = isWithinTimeLimit && !Number.isNaN(Number(queryParams.ampSessionId)) ? Number(queryParams.ampSessionId) : undefined; deferredSessionId = this.config.deferredSessionId; if (deferredSessionId === UNSPECIFIED_SESSION_ID && !this.config.optOut) { deferredSessionId = Date.now(); } this.setSessionId((_h = (_g = (_f = options.sessionId) !== null && _f !== void 0 ? _f : querySessionId) !== null && _g !== void 0 ? _g : deferredSessionId) !== null && _h !== void 0 ? _h : this.config.sessionId); if (this.config.optOut) { this.timeline.addOptOutListener(function (optOut) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(_this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { if (!optOut && this.config.deferredSessionId) { if (this.config.deferredSessionId === UNSPECIFIED_SESSION_ID) { this.setSessionId(undefined); } else { this.setSessionId(this.config.deferredSessionId); } } return [2 /*return*/]; }); }); }); } connector = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.getAnalyticsConnector)(options.instanceName); connector.identityStore.setIdentity({ userId: this.config.userId, deviceId: this.config.deviceId, }); if (!(this.config.offline !== _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_16__.OfflineDisabled)) return [3 /*break*/, 10]; return [4 /*yield*/, this.add((0,_plugins_network_connectivity_checker__WEBPACK_IMPORTED_MODULE_27__.networkConnectivityCheckerPlugin)()).promise]; case 9: _j.sent(); _j.label = 10; case 10: return [4 /*yield*/, this.add(new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.Destination({ diagnosticsClient: diagnosticsClient })).promise]; case 11: _j.sent(); return [4 /*yield*/, this.add(new _plugins_context__WEBPACK_IMPORTED_MODULE_20__.Context()).promise]; case 12: _j.sent(); return [4 /*yield*/, this.add(new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__.IdentityEventSender()).promise]; case 13: _j.sent(); // Notify if DET is enabled (0,_det_notification__WEBPACK_IMPORTED_MODULE_26__.detNotify)(this.config); if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isFileDownloadTrackingEnabled)(this.config.defaultTracking)) return [3 /*break*/, 15]; this.config.loggerProvider.debug('Adding file download tracking plugin'); return [4 /*yield*/, this.add((0,_plugins_file_download_tracking__WEBPACK_IMPORTED_MODULE_24__.fileDownloadTracking)()).promise]; case 14: _j.sent(); _j.label = 15; case 15: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isFormInteractionTrackingEnabled)(this.config.defaultTracking)) return [3 /*break*/, 17]; this.config.loggerProvider.debug('Adding form interaction plugin'); return [4 /*yield*/, this.add((0,_plugins_form_interaction_tracking__WEBPACK_IMPORTED_MODULE_23__.formInteractionTracking)()).promise]; case 16: _j.sent(); _j.label = 17; case 17: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isPageViewTrackingEnabled)(this.config.defaultTracking)) return [3 /*break*/, 20]; if (!!this.config.optOut) return [3 /*break*/, 19]; this.config.loggerProvider.debug('Adding page view tracking plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_page_view_tracking_browser__WEBPACK_IMPORTED_MODULE_22__.pageViewTrackingPlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getPageViewTrackingConfig)(this.config))).promise]; case 18: _j.sent(); return [3 /*break*/, 20]; case 19: this.timeline.addOptOutListener(function (optOut) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(_this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: /* istanbul ignore if */ if (optOut) { return [2 /*return*/]; } this.config.loggerProvider.debug('Adding page view tracking plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_page_view_tracking_browser__WEBPACK_IMPORTED_MODULE_22__.pageViewTrackingPlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getPageViewTrackingConfig)(this.config))).promise]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }); _j.label = 20; case 20: if (!((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isAttributionTrackingEnabled)(this.config.defaultTracking) && (0,_attribution_tracking_methods__WEBPACK_IMPORTED_MODULE_40__.isEventPropertyAttributionEnabled)(attributionTrackingOptions))) return [3 /*break*/, 22]; this.config.loggerProvider.debug('Adding event property attribution plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_event_property_attribution_browser__WEBPACK_IMPORTED_MODULE_35__.eventPropertyTrackingPlugin)(attributionTrackingOptions)).promise]; case 21: _j.sent(); _j.label = 22; case 22: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isElementInteractionsEnabled)(this.config.autocapture)) return [3 /*break*/, 24]; this.config.loggerProvider.debug('Adding user interactions plugin (autocapture plugin)'); return [4 /*yield*/, this.add((0,_amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_29__.autocapturePlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getElementInteractionsConfig)(this.config), { diagnosticsClient: diagnosticsClient })).promise]; case 23: _j.sent(); _j.label = 24; case 24: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isFrustrationInteractionsEnabled)(this.config.autocapture)) return [3 /*break*/, 26]; this.config.loggerProvider.debug('Adding frustration interactions plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_30__.frustrationPlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getFrustrationInteractionsConfig)(this.config))).promise]; case 25: _j.sent(); _j.label = 26; case 26: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isNetworkTrackingEnabled)(this.config.autocapture)) return [3 /*break*/, 28]; this.config.loggerProvider.debug('Adding network tracking plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_network_capture_browser__WEBPACK_IMPORTED_MODULE_32__.networkCapturePlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getNetworkTrackingConfig)(this.config))).promise]; case 27: _j.sent(); _j.label = 28; case 28: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isWebVitalsEnabled)(this.config.autocapture)) return [3 /*break*/, 30]; this.config.loggerProvider.debug('Adding web vitals plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_web_vitals_browser__WEBPACK_IMPORTED_MODULE_33__.webVitalsPlugin)()).promise]; case 29: _j.sent(); _j.label = 30; case 30: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isPerformanceTrackingEnabled)(this.config.autocapture)) return [3 /*break*/, 32]; this.config.loggerProvider.debug('Adding performance tracking plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_autocapture_browser__WEBPACK_IMPORTED_MODULE_31__.performancePlugin)((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.getPerformanceTrackingConfig)(this.config))).promise]; case 31: _j.sent(); _j.label = 32; case 32: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isPageUrlEnrichmentEnabled)(this.config.autocapture)) return [3 /*break*/, 34]; this.config.loggerProvider.debug('Adding referrer page url plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_page_url_enrichment_browser__WEBPACK_IMPORTED_MODULE_38__.pageUrlEnrichmentPlugin)()).promise]; case 33: _j.sent(); _j.label = 34; case 34: if (!(0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isCustomEnrichmentEnabled)(this.config.customEnrichment)) return [3 /*break*/, 36]; this.config.loggerProvider.debug('Adding custom enrichment plugin'); return [4 /*yield*/, this.add((0,_amplitude_plugin_custom_enrichment_browser__WEBPACK_IMPORTED_MODULE_39__.customEnrichmentPlugin)()).promise]; case 35: _j.sent(); _j.label = 36; case 36: this.initializing = false; // Step 6: Run queued dispatch functions return [4 /*yield*/, this.runQueuedFunctions('dispatchQ')]; case 37: // Step 6: Run queued dispatch functions _j.sent(); // Step 7: Add the event receiver after running remaining queued functions. connector.eventBridge.setEventReceiver(function (event) { var _a = event.eventProperties || {}, time = _a.time, cleanEventProperties = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__rest)(_a, ["time"]); var eventOptions = typeof time === 'number' ? { time: time } : undefined; void _this.track(event.eventType, cleanEventProperties, eventOptions); }); return [2 /*return*/]; } }); }); }; AmplitudeBrowser.prototype.getUserId = function () { var _a; return (_a = this.config) === null || _a === void 0 ? void 0 : _a.userId; }; AmplitudeBrowser.prototype.setUserId = function (userId) { if (!this.config) { this.q.push(this.setUserId.bind(this, userId)); return; } this.config.loggerProvider.debug('function setUserId: ', userId); if (userId !== this.config.userId || userId === undefined) { this.config.userId = userId; // eslint-disable-next-line @typescript-eslint/no-unsafe-call this.timeline.onIdentityChanged({ userId: userId }); (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.setConnectorUserId)(userId, this.config.instanceName); } }; AmplitudeBrowser.prototype.getDeviceId = function () { var _a; return (_a = this.config) === null || _a === void 0 ? void 0 : _a.deviceId; }; AmplitudeBrowser.prototype.setDeviceId = function (deviceId) { if (!this.config) { this.q.push(this.setDeviceId.bind(this, deviceId)); return; } this.config.loggerProvider.debug('function setDeviceId: ', deviceId); if (deviceId !== this.config.deviceId) { this.config.deviceId = deviceId; // eslint-disable-next-line @typescript-eslint/no-unsafe-call this.timeline.onIdentityChanged({ deviceId: deviceId }); (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.setConnectorDeviceId)(deviceId, this.config.instanceName); } }; AmplitudeBrowser.prototype.reset = function () { this.setDeviceId((0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_11__.UUID)()); this.setUserId(undefined); this.timeline.onReset(); }; AmplitudeBrowser.prototype.getIdentity = function () { var _a, _b; return { deviceId: (_a = this.config) === null || _a === void 0 ? void 0 : _a.deviceId, userId: (_b = this.config) === null || _b === void 0 ? void 0 : _b.userId, userProperties: this.userProperties, }; }; AmplitudeBrowser.prototype.setIdentity = function (identity) { var e_1, _a; var _b; // Handle userId change if ('userId' in identity) { this.setUserId(identity.userId); } // Handle deviceId change if ('deviceId' in identity && identity.deviceId) { this.setDeviceId(identity.deviceId); } // Handle userProperties change - auto-send identify if ('userProperties' in identity) { this.userProperties = identity.userProperties; // Auto-send identify event with $set operations var identifyObj = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.Identify(); // istanbul ignore next var userProperties = (_b = identity.userProperties) !== null && _b !== void 0 ? _b : {}; try { for (var _c = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(Object.entries(userProperties)), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_d.value, 2), key = _e[0], value = _e[1]; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment // eslint-disable-next-line @typescript-eslint/no-unsafe-argument identifyObj.set(key, value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_1) throw e_1.error; } } // The identify event processing in core-client already calls onIdentityChanged, // so we don't need to call it explicitly here to avoid duplicate notifications. this.identify(identifyObj); } }; AmplitudeBrowser.prototype.getOptOut = function () { var _a; return (_a = this.config) === null || _a === void 0 ? void 0 : _a.optOut; }; AmplitudeBrowser.prototype.getSessionId = function () { var _a; return (_a = this.config) === null || _a === void 0 ? void 0 : _a.sessionId; }; AmplitudeBrowser.prototype.setSessionId = function (sessionId) { var _a; var promises = []; if (!this.config) { this.q.push(this.setSessionId.bind(this, sessionId)); return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__.returnWrapper)(Promise.resolve()); } // do not start a new session if optOut is true if (this.config.optOut) { // save the sessionId to storage to be used when optOut is false this.config.deferredSessionId = sessionId !== null && sessionId !== void 0 ? sessionId : UNSPECIFIED_SESSION_ID; return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__.returnWrapper)(Promise.resolve()); } // default sessionId to current time if (sessionId === undefined) { sessionId = Date.now(); } // Prevents starting a new session with the same session ID if (sessionId === this.config.sessionId) { return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__.returnWrapper)(Promise.resolve()); } this.config.loggerProvider.debug('function setSessionId: ', sessionId); var previousSessionId = this.getSessionId(); if (previousSessionId !== sessionId) { // eslint-disable-next-line @typescript-eslint/no-unsafe-call this.timeline.onSessionIdChanged(sessionId); } var lastEventTime = this.config.lastEventTime; var lastEventId = (_a = this.config.lastEventId) !== null && _a !== void 0 ? _a : -1; this.config.sessionId = sessionId; this.config.lastEventTime = undefined; this.config.pageCounter = 0; if ((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isSessionTrackingEnabled)(this.config.defaultTracking)) { if (previousSessionId && lastEventTime) { promises.push(this.track(_constants__WEBPACK_IMPORTED_MODULE_25__.DEFAULT_SESSION_END_EVENT, undefined, { device_id: this.previousSessionDeviceId, event_id: ++lastEventId, session_id: previousSessionId, time: lastEventTime + 1, user_id: this.previousSessionUserId, }).promise); } this.config.lastEventTime = this.config.sessionId; } // Fire web attribution event when enable webAttribution tracking // 1. has new campaign (call setSessionId from init function) // 2. or shouldTrackNewCampaign (call setSessionId from async process(event) when there has new campaign and resetSessionOnNewCampaign = true ) var isCampaignEventTracked = this.trackCampaignEventIfNeeded(++lastEventId, promises); // track the identify event if an Identify object is provided in the config if (this.config.identify) { promises.push(this.track((0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_12__.createIdentifyEvent)(this.config.identify)).promise); } if ((0,_default_tracking__WEBPACK_IMPORTED_MODULE_18__.isSessionTrackingEnabled)(this.config.defaultTracking)) { promises.push(this.track(_constants__WEBPACK_IMPORTED_MODULE_25__.DEFAULT_SESSION_START_EVENT, undefined, { event_id: isCampaignEventTracked ? ++lastEventId : lastEventId, session_id: this.config.sessionId, time: this.config.lastEventTime, }).promise); } this.previousSessionDeviceId = this.config.deviceId; this.previousSessionUserId = this.config.userId; return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_10__.returnWrapper)(Promise.all(promises)); }; AmplitudeBrowser.prototype.extendSession = function () { if (!this.config) { this.q.push(this.extendSession.bind(this)); return; } this.config.lastEventTime = Date.now(); }; AmplitudeBrowser.prototype.setTransport = function (transport) { if (!this.config) { this.q.push(this.setTransport.bind(this, transport)); return; } this.config.transportProvider = (0,_config__WEBPACK_IMPORTED_MODULE_21__.createTransport)(transport); }; AmplitudeBrowser.prototype.identify = function (identify, eventOptions) { if ((0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.isInstanceProxy)(identify)) { var queue = identify._q; identify._q = []; identify = (0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.convertProxyObjectToRealObject)(new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.Identify(), queue); } if (eventOptions === null || eventOptions === void 0 ? void 0 : eventOptions.user_id) { this.setUserId(eventOptions.user_id); } if (eventOptions === null || eventOptions === void 0 ? void 0 : eventOptions.device_id) { this.setDeviceId(eventOptions.device_id); } return _super.prototype.identify.call(this, identify, eventOptions); }; AmplitudeBrowser.prototype.groupIdentify = function (groupType, groupName, identify, eventOptions) { if ((0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.isInstanceProxy)(identify)) { var queue = identify._q; identify._q = []; identify = (0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.convertProxyObjectToRealObject)(new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.Identify(), queue); } return _super.prototype.groupIdentify.call(this, groupType, groupName, identify, eventOptions); }; AmplitudeBrowser.prototype.revenue = function (revenue, eventOptions) { if ((0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.isInstanceProxy)(revenue)) { var queue = revenue._q; revenue._q = []; revenue = (0,_utils_snippet_helper__WEBPACK_IMPORTED_MODULE_19__.convertProxyObjectToRealObject)(new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.Revenue(), queue); } return _super.prototype.revenue.call(this, revenue, eventOptions); }; AmplitudeBrowser.prototype.trackCampaignEventIfNeeded = function (lastEventId, promises) { if (!this.webAttribution || !this.webAttribution.shouldTrackNewCampaign || !(0,_attribution_tracking_methods__WEBPACK_IMPORTED_MODULE_40__.isUserPropertyAttributionEnabled)(this.webAttribution.options)) { return false; } var campaignEvent = this.webAttribution.generateCampaignEvent(lastEventId); if (promises) { promises.push(this.track(campaignEvent).promise); } else { this.track(campaignEvent); } this.config.loggerProvider.log('Tracking attribution.'); return true; }; AmplitudeBrowser.prototype.process = function (event) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var currentTime, isEventInNewSession, shouldSetSessionIdOnNewCampaign; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { currentTime = Date.now(); isEventInNewSession = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_8__.isNewSession)(this.config.sessionTimeout, this.config.lastEventTime); shouldSetSessionIdOnNewCampaign = this.webAttribution && this.webAttribution.shouldSetSessionIdOnNewCampaign(); if (event.event_type !== _constants__WEBPACK_IMPORTED_MODULE_25__.DEFAULT_SESSION_START_EVENT && event.event_type !== _constants__WEBPACK_IMPORTED_MODULE_25__.DEFAULT_SESSION_END_EVENT && (!event.session_id || event.session_id === this.getSessionId())) { if (isEventInNewSession || shouldSetSessionIdOnNewCampaign) { this.setSessionId(currentTime); if (shouldSetSessionIdOnNewCampaign) { this.config.loggerProvider.log('Created a new session for new campaign.'); } } else if (!isEventInNewSession) { // Web attribution should be tracked during the middle of a session // if there has been a chance in the campaign information. this.trackCampaignEventIfNeeded(); } } return [2 /*return*/, _super.prototype.process.call(this, event)]; }); }); }; AmplitudeBrowser.prototype.logBrowserOptions = function (browserConfig) { try { var browserConfigCopy = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, browserConfig), { apiKey: browserConfig.apiKey.substring(0, 10) + '********' }); this.config.loggerProvider.debug('Initialized Amplitude with BrowserConfig:', (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_17__.safeJsonStringify)(browserConfigCopy)); } catch (e) { /* istanbul ignore next */ this.config.loggerProvider.error('Error logging browser config', e); } }; /** * @experimental * WARNING: This method is for internal testing only and is not part of the public API. * It may be changed or removed at any time without notice. * * Sets the diagnostics sample rate before amplitude.init() * @param sampleRate - The sample rate to set */ AmplitudeBrowser.prototype._setDiagnosticsSampleRate = function (sampleRate) { if (sampleRate > 1 || sampleRate < 0) { return; } // Set diagnostics sample rate before initializing the config if (!this.config) { this._diagnosticsSampleRate = sampleRate; return; } }; return AmplitudeBrowser; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.AmplitudeCore)); //# sourceMappingURL=browser-client.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/config.js" /*!*********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/config.js ***! \*********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ BrowserConfig: () => (/* binding */ BrowserConfig), /* harmony export */ createCookieStorage: () => (/* binding */ createCookieStorage), /* harmony export */ createTransport: () => (/* binding */ createTransport), /* harmony export */ getTopLevelDomain: () => (/* binding */ getTopLevelDomain), /* harmony export */ shouldFetchRemoteConfig: () => (/* binding */ shouldFetchRemoteConfig), /* harmony export */ useBrowserConfig: () => (/* binding */ useBrowserConfig) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/config.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/logger.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/cookie-name.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/query-params.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/uuid.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/storage/memory.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/storage/cookie.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/loglevel.js"); /* harmony import */ var _storage_local_storage__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./storage/local-storage */ "./node_modules/@amplitude/analytics-browser/lib/esm/storage/local-storage.js"); /* harmony import */ var _storage_session_storage__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./storage/session-storage */ "./node_modules/@amplitude/analytics-browser/lib/esm/storage/session-storage.js"); /* harmony import */ var _transports_xhr__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./transports/xhr */ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/xhr.js"); /* harmony import */ var _transports_fetch__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./transports/fetch */ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/fetch.js"); /* harmony import */ var _transports_send_beacon__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./transports/send-beacon */ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/send-beacon.js"); /* harmony import */ var _cookie_migration__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./cookie-migration */ "./node_modules/@amplitude/analytics-browser/lib/esm/cookie-migration/index.js"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./constants */ "./node_modules/@amplitude/analytics-browser/lib/esm/constants.js"); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./version */ "./node_modules/@amplitude/analytics-browser/lib/esm/version.js"); /* harmony import */ var _attribution_helpers__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./attribution/helpers */ "./node_modules/@amplitude/analytics-browser/lib/esm/attribution/helpers.js"); // Exported for testing purposes only. Do not expose to public interface. var BrowserConfig = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(BrowserConfig, _super); function BrowserConfig(apiKey, appVersion, cookieStorage, cookieOptions, defaultTracking, autocapture, deviceId, flushIntervalMillis, flushMaxRetries, flushQueueSize, identityStorage, ingestionMetadata, instanceName, lastEventId, lastEventTime, loggerProvider, logLevel, minIdLength, offline, optOut, partnerId, plan, serverUrl, serverZone, sessionId, deferredSessionId, sessionTimeout, storageProvider, trackingOptions, transport, useBatch, fetchRemoteConfig, userId, pageCounter, debugLogsEnabled, networkTrackingOptions, identify, enableDiagnostics, diagnosticsSampleRate, diagnosticsClient, remoteConfig, topLevelDomain, enableRequestBodyCompression, customEnrichment) { if (cookieStorage === void 0) { cookieStorage = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__.MemoryStorage(); } if (cookieOptions === void 0) { cookieOptions = { domain: '', expiration: 365, sameSite: 'Lax', secure: false, upgrade: true, }; } if (flushIntervalMillis === void 0) { flushIntervalMillis = 1000; } if (flushMaxRetries === void 0) { flushMaxRetries = 5; } if (flushQueueSize === void 0) { flushQueueSize = 30; } if (identityStorage === void 0) { identityStorage = _constants__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_IDENTITY_STORAGE; } if (loggerProvider === void 0) { loggerProvider = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.Logger(); } if (logLevel === void 0) { logLevel = _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_8__.LogLevel.Warn; } if (offline === void 0) { offline = false; } if (optOut === void 0) { optOut = false; } if (serverUrl === void 0) { serverUrl = ''; } if (serverZone === void 0) { serverZone = _constants__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_SERVER_ZONE; } if (sessionTimeout === void 0) { sessionTimeout = 30 * 60 * 1000; } if (storageProvider === void 0) { storageProvider = new _storage_local_storage__WEBPACK_IMPORTED_MODULE_9__.LocalStorage({ loggerProvider: loggerProvider }); } if (trackingOptions === void 0) { trackingOptions = { ipAddress: true, language: true, platform: true, }; } if (transport === void 0) { transport = 'fetch'; } if (useBatch === void 0) { useBatch = false; } if (fetchRemoteConfig === void 0) { fetchRemoteConfig = true; } if (enableDiagnostics === void 0) { enableDiagnostics = true; } if (diagnosticsSampleRate === void 0) { diagnosticsSampleRate = 0; } if (enableRequestBodyCompression === void 0) { enableRequestBodyCompression = false; } var _this = this; var _a; _this = _super.call(this, { apiKey: apiKey, storageProvider: storageProvider, transportProvider: createTransport(transport) }) || this; _this.apiKey = apiKey; _this.appVersion = appVersion; _this.cookieOptions = cookieOptions; _this.defaultTracking = defaultTracking; _this.autocapture = autocapture; _this.flushIntervalMillis = flushIntervalMillis; _this.flushMaxRetries = flushMaxRetries; _this.flushQueueSize = flushQueueSize; _this.identityStorage = identityStorage; _this.ingestionMetadata = ingestionMetadata; _this.instanceName = instanceName; _this.loggerProvider = loggerProvider; _this.logLevel = logLevel; _this.minIdLength = minIdLength; _this.offline = offline; _this.partnerId = partnerId; _this.plan = plan; _this.serverUrl = serverUrl; _this.serverZone = serverZone; _this.sessionTimeout = sessionTimeout; _this.storageProvider = storageProvider; _this.trackingOptions = trackingOptions; _this.transport = transport; _this.useBatch = useBatch; _this.fetchRemoteConfig = fetchRemoteConfig; _this.networkTrackingOptions = networkTrackingOptions; _this.identify = identify; _this.enableDiagnostics = enableDiagnostics; _this.diagnosticsSampleRate = diagnosticsSampleRate; _this.diagnosticsClient = diagnosticsClient; _this.remoteConfig = remoteConfig; _this.topLevelDomain = topLevelDomain; _this.enableRequestBodyCompression = enableRequestBodyCompression; _this.customEnrichment = customEnrichment; _this.version = _version__WEBPACK_IMPORTED_MODULE_16__.VERSION; _this._optOut = false; _this._cookieStorage = cookieStorage; _this.deviceId = deviceId; _this.lastEventId = lastEventId; _this.lastEventTime = lastEventTime; _this.optOut = optOut; _this.deferredSessionId = deferredSessionId; _this.sessionId = sessionId; _this.pageCounter = pageCounter; _this.userId = userId; _this.debugLogsEnabled = debugLogsEnabled; _this.loggerProvider.enable(debugLogsEnabled ? _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_8__.LogLevel.Debug : _this.logLevel); _this.networkTrackingOptions = networkTrackingOptions; _this.identify = identify; _this.enableDiagnostics = enableDiagnostics; _this.diagnosticsSampleRate = diagnosticsSampleRate; _this.diagnosticsClient = diagnosticsClient; // Note: The canonical logic for determining fetchRemoteConfig is in shouldFetchRemoteConfig(). // This logic is duplicated here to maintain the BrowserConfig constructor contract and ensure // the config object has the correct fetchRemoteConfig value set on its properties. // The value passed to this constructor should already be computed via shouldFetchRemoteConfig(). var _fetchRemoteConfig = (_a = remoteConfig === null || remoteConfig === void 0 ? void 0 : remoteConfig.fetchRemoteConfig) !== null && _a !== void 0 ? _a : fetchRemoteConfig; _this.remoteConfig = _this.remoteConfig || {}; _this.remoteConfig.fetchRemoteConfig = _fetchRemoteConfig; _this.fetchRemoteConfig = _fetchRemoteConfig; _this.topLevelDomain = topLevelDomain || (0,_attribution_helpers__WEBPACK_IMPORTED_MODULE_17__.getDomain)(); return _this; } Object.defineProperty(BrowserConfig.prototype, "cookieStorage", { get: function () { return this._cookieStorage; }, set: function (cookieStorage) { if (this._cookieStorage !== cookieStorage) { this._cookieStorage = cookieStorage; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "deviceId", { get: function () { return this._deviceId; }, set: function (deviceId) { if (this._deviceId !== deviceId) { this._deviceId = deviceId; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "userId", { get: function () { return this._userId; }, set: function (userId) { if (this._userId !== userId) { this._userId = userId; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "sessionId", { get: function () { return this._sessionId; }, set: function (sessionId) { if (this._sessionId !== sessionId) { this._sessionId = sessionId; // Clear deferredSessionId when sessionId is set to prevent stale values // from overriding legitimate sessionIds on subsequent page loads if (sessionId !== undefined && this._deferredSessionId !== undefined) { this._deferredSessionId = undefined; } this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "deferredSessionId", { get: function () { return this._deferredSessionId; }, set: function (deferredSessionId) { if (this._deferredSessionId !== deferredSessionId && deferredSessionId !== this.sessionId) { this._deferredSessionId = deferredSessionId; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "optOut", { get: function () { return this._optOut; }, set: function (optOut) { if (this._optOut !== optOut) { this._optOut = optOut; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "lastEventTime", { get: function () { return this._lastEventTime; }, set: function (lastEventTime) { if (this._lastEventTime !== lastEventTime) { this._lastEventTime = lastEventTime; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "lastEventId", { get: function () { return this._lastEventId; }, set: function (lastEventId) { if (this._lastEventId !== lastEventId) { this._lastEventId = lastEventId; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "pageCounter", { get: function () { return this._pageCounter; }, set: function (pageCounter) { if (this._pageCounter !== pageCounter) { this._pageCounter = pageCounter; this.updateStorage(); } }, enumerable: false, configurable: true }); Object.defineProperty(BrowserConfig.prototype, "debugLogsEnabled", { set: function (debugLogsEnabled) { if (this._debugLogsEnabled !== debugLogsEnabled) { this._debugLogsEnabled = debugLogsEnabled; this.updateStorage(); } }, enumerable: false, configurable: true }); BrowserConfig.prototype.updateStorage = function () { var cache = { deviceId: this._deviceId, userId: this._userId, sessionId: this._sessionId, deferredSessionId: this._deferredSessionId, optOut: this._optOut, lastEventTime: this._lastEventTime, lastEventId: this._lastEventId, pageCounter: this._pageCounter, debugLogsEnabled: this._debugLogsEnabled, cookieDomain: undefined, }; if (this.cookieStorage instanceof _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.CookieStorage) { cache.cookieDomain = this.cookieStorage.options.domain; } void this.cookieStorage.set((0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.getCookieName)(this.apiKey), cache); }; return BrowserConfig; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.Config)); var useBrowserConfig = function (apiKey, options, amplitudeInstance, diagnosticsClient, earlyConfig) { if (options === void 0) { options = {}; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { var identityStorage, defaultCookieDomain, cookieOptions, cookieConfig, cookieStorage, legacyCookies, previousCookies, queryParams, ampTimestamp, isWithinTimeLimit, deviceId, lastEventId, lastEventTime, optOut, sessionId, deferredSessionId, userId, trackingOptions, pageCounter, debugLogsEnabled, browserConfig; var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_6) { switch (_6.label) { case 0: identityStorage = options.identityStorage || _constants__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_IDENTITY_STORAGE; defaultCookieDomain = ''; if (!(identityStorage === _constants__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_IDENTITY_STORAGE && !((_a = options.cookieOptions) === null || _a === void 0 ? void 0 : _a.domain) && ((_b = options.cookieOptions) === null || _b === void 0 ? void 0 : _b.domain) !== '')) return [3 /*break*/, 2]; return [4 /*yield*/, getTopLevelDomain(undefined, diagnosticsClient)]; case 1: defaultCookieDomain = _6.sent(); _6.label = 2; case 2: cookieOptions = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ domain: (_d = (_c = options.cookieOptions) === null || _c === void 0 ? void 0 : _c.domain) !== null && _d !== void 0 ? _d : defaultCookieDomain, expiration: 365, sameSite: 'Lax', secure: false, upgrade: true }, options.cookieOptions); cookieConfig = { // if more than one cookie with the same key exists, // look for the cookie that has the domain attribute set to cookieOptions.domain duplicateResolverFn: function (value) { var decodedValue = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.decodeCookieValue)(value); if (!decodedValue) { return false; } var parsed = JSON.parse(decodedValue); return (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.isDomainEqual)(parsed.cookieDomain, cookieOptions.domain); }, diagnosticsClient: diagnosticsClient, }; cookieStorage = createCookieStorage(options.identityStorage, cookieOptions, cookieConfig); return [4 /*yield*/, (0,_cookie_migration__WEBPACK_IMPORTED_MODULE_14__.parseLegacyCookies)(apiKey, cookieStorage, (_f = (_e = options.cookieOptions) === null || _e === void 0 ? void 0 : _e.upgrade) !== null && _f !== void 0 ? _f : true)]; case 3: legacyCookies = _6.sent(); return [4 /*yield*/, cookieStorage.get((0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.getCookieName)(apiKey))]; case 4: previousCookies = _6.sent(); queryParams = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.getQueryParams)(); ampTimestamp = queryParams.ampTimestamp ? Number(queryParams.ampTimestamp) : undefined; isWithinTimeLimit = ampTimestamp ? Date.now() < ampTimestamp : true; deviceId = (_l = (_k = (_j = (_g = options.deviceId) !== null && _g !== void 0 ? _g : (isWithinTimeLimit ? (_h = queryParams.ampDeviceId) !== null && _h !== void 0 ? _h : queryParams.deviceId : undefined)) !== null && _j !== void 0 ? _j : previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.deviceId) !== null && _k !== void 0 ? _k : legacyCookies.deviceId) !== null && _l !== void 0 ? _l : (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__.UUID)(); lastEventId = (_m = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.lastEventId) !== null && _m !== void 0 ? _m : legacyCookies.lastEventId; lastEventTime = (_o = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.lastEventTime) !== null && _o !== void 0 ? _o : legacyCookies.lastEventTime; optOut = (_q = (_p = options.optOut) !== null && _p !== void 0 ? _p : previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.optOut) !== null && _q !== void 0 ? _q : legacyCookies.optOut; sessionId = (_r = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.sessionId) !== null && _r !== void 0 ? _r : legacyCookies.sessionId; deferredSessionId = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.deferredSessionId; userId = (_t = (_s = options.userId) !== null && _s !== void 0 ? _s : previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.userId) !== null && _t !== void 0 ? _t : legacyCookies.userId; amplitudeInstance.previousSessionDeviceId = (_u = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.deviceId) !== null && _u !== void 0 ? _u : legacyCookies.deviceId; amplitudeInstance.previousSessionUserId = (_v = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.userId) !== null && _v !== void 0 ? _v : legacyCookies.userId; trackingOptions = { ipAddress: (_x = (_w = options.trackingOptions) === null || _w === void 0 ? void 0 : _w.ipAddress) !== null && _x !== void 0 ? _x : true, language: (_z = (_y = options.trackingOptions) === null || _y === void 0 ? void 0 : _y.language) !== null && _z !== void 0 ? _z : true, platform: (_1 = (_0 = options.trackingOptions) === null || _0 === void 0 ? void 0 : _0.platform) !== null && _1 !== void 0 ? _1 : true, }; pageCounter = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.pageCounter; debugLogsEnabled = previousCookies === null || previousCookies === void 0 ? void 0 : previousCookies.debugLogsEnabled; // Override default tracking options if autocapture is set if (options.autocapture !== undefined) { options.defaultTracking = options.autocapture; } browserConfig = new BrowserConfig(apiKey, options.appVersion, cookieStorage, cookieOptions, options.defaultTracking, options.autocapture, deviceId, options.flushIntervalMillis, options.flushMaxRetries, options.flushQueueSize, identityStorage, options.ingestionMetadata, options.instanceName, lastEventId, lastEventTime, // Use earlyConfig.loggerProvider to ensure consistent logger across DiagnosticsClient/RemoteConfigClient/BrowserConfig (_2 = earlyConfig === null || earlyConfig === void 0 ? void 0 : earlyConfig.loggerProvider) !== null && _2 !== void 0 ? _2 : options.loggerProvider, options.logLevel, options.minIdLength, options.offline, optOut, options.partnerId, options.plan, options.serverUrl, // Use earlyConfig.serverZone to ensure consistent serverZone (_3 = earlyConfig === null || earlyConfig === void 0 ? void 0 : earlyConfig.serverZone) !== null && _3 !== void 0 ? _3 : options.serverZone, sessionId, deferredSessionId, options.sessionTimeout, options.storageProvider, trackingOptions, options.transport, options.useBatch, options.fetchRemoteConfig, userId, pageCounter, debugLogsEnabled, options.networkTrackingOptions, options.identify, // Use earlyConfig values (already has remote config applied), otherwise fall back to options (_4 = earlyConfig === null || earlyConfig === void 0 ? void 0 : earlyConfig.enableDiagnostics) !== null && _4 !== void 0 ? _4 : options.enableDiagnostics, (_5 = earlyConfig === null || earlyConfig === void 0 ? void 0 : earlyConfig.diagnosticsSampleRate) !== null && _5 !== void 0 ? _5 : amplitudeInstance._diagnosticsSampleRate, diagnosticsClient, options.remoteConfig, defaultCookieDomain, options.enableRequestBodyCompression, options.customEnrichment); return [4 /*yield*/, browserConfig.storageProvider.isEnabled()]; case 5: if (!(_6.sent())) { browserConfig.loggerProvider.warn("Storage provider ".concat(browserConfig.storageProvider.constructor.name, " is not enabled. Falling back to MemoryStorage.")); browserConfig.storageProvider = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__.MemoryStorage(); } return [2 /*return*/, browserConfig]; } }); }); }; var createCookieStorage = function (identityStorage, cookieOptions, cookieConfig) { if (identityStorage === void 0) { identityStorage = _constants__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_IDENTITY_STORAGE; } if (cookieOptions === void 0) { cookieOptions = {}; } switch (identityStorage) { case 'localStorage': return new _storage_local_storage__WEBPACK_IMPORTED_MODULE_9__.LocalStorage(); case 'sessionStorage': return new _storage_session_storage__WEBPACK_IMPORTED_MODULE_10__.SessionStorage(); case 'none': return new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__.MemoryStorage(); case 'cookie': default: return new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.CookieStorage((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, cookieOptions), { expirationDays: cookieOptions.expiration }), cookieConfig); } }; /** * Determines whether to fetch remote config based on options. * Extracted to allow early determination before useBrowserConfig is called. */ var shouldFetchRemoteConfig = function (options) { var _a, _b; if (options === void 0) { options = {}; } if (((_a = options.remoteConfig) === null || _a === void 0 ? void 0 : _a.fetchRemoteConfig) === true) { // set to true if remoteConfig explicitly set to true return true; } else if (((_b = options.remoteConfig) === null || _b === void 0 ? void 0 : _b.fetchRemoteConfig) === false || options.fetchRemoteConfig === false) { // set to false if either are set to false explicitly return false; } else { // default to true if both undefined return true; } }; var createTransport = function (transport) { var type = typeof transport === 'object' ? transport.type : transport; var headers = typeof transport === 'object' ? transport.headers : undefined; if (type === 'xhr') { return new _transports_xhr__WEBPACK_IMPORTED_MODULE_11__.XHRTransport(headers); } if (type === 'beacon') { // SendBeacon does not support custom headers return new _transports_send_beacon__WEBPACK_IMPORTED_MODULE_13__.SendBeaconTransport(); } // Keep a browser-local fetch transport for gzip support. // TODO: Merge back to core FetchTransport after React Native supports gzip. return new _transports_fetch__WEBPACK_IMPORTED_MODULE_12__.FetchTransport(headers); }; var getTopLevelDomain = function (url, diagnosticsClient) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { var host, parts, levels, skipLevel, i, i, domain, result, e_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.CookieStorage(undefined, { diagnosticsClient: diagnosticsClient }).isEnabled()]; case 1: if (!(_a.sent()) || (!url && (typeof location === 'undefined' || !location.hostname))) { return [2 /*return*/, '']; } host = url !== null && url !== void 0 ? url : location.hostname; parts = host.split('.'); // if hostname has less than 2 parts, it's not a registrable domain // and the browser won't allow setting domain-scoped cookies for it so return empty string if (parts.length === 1) { return [2 /*return*/, '']; } levels = []; skipLevel = 1; // if the hostname ends with a TLD we know is in the Public Suffix List // then the last two parts are definitely not writable as a domain if (_attribution_helpers__WEBPACK_IMPORTED_MODULE_17__.KNOWN_2LDS.find(function (tld) { return host.endsWith(".".concat(tld)); })) { skipLevel = 2; } for (i = parts.length - skipLevel - 1; i >= 0; --i) { levels.push(parts.slice(i).join('.')); } i = 0; _a.label = 2; case 2: if (!(i < levels.length)) return [3 /*break*/, 7]; domain = levels[i]; _a.label = 3; case 3: _a.trys.push([3, 5, , 6]); return [4 /*yield*/, _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_7__.CookieStorage.isDomainWritable(domain)]; case 4: result = _a.sent(); // if the transaction succeeded, the domain is valid if (result) { return [2 /*return*/, '.' + domain]; } return [3 /*break*/, 6]; case 5: e_1 = _a.sent(); /* istanbul ignore if */ if (diagnosticsClient) { diagnosticsClient.recordEvent('cookies.tld.failure', { reason: "Unexpected exception checking domain is writable: ".concat(domain), error: e_1 instanceof Error ? e_1.message : String(e_1), }); } return [3 /*break*/, 6]; case 6: i++; return [3 /*break*/, 2]; case 7: // if the transaction failed, the domain is invalid // record a diagnostic event if (diagnosticsClient) { diagnosticsClient.recordEvent('cookies.tld.failure', { reason: "Could not determine TLD for host ".concat(host), }); } // return an empty string to indicate that we couldn't determine the TLD // so fallback to host-only cookies (scoped to the current host) return [2 /*return*/, '']; } }); }); }; //# sourceMappingURL=config.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/config/joined-config.js" /*!***********************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/config/joined-config.js ***! \***********************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ translateRemoteConfigToLocal: () => (/* binding */ translateRemoteConfigToLocal), /* harmony export */ updateBrowserConfigWithRemoteConfig: () => (/* binding */ updateBrowserConfigWithRemoteConfig) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); /** * Performs a deep transformation of a remote config object so that * it matches the expected schema of the local config. * * Specifically, it normalizes nested `enabled` flags into concise union types. * * ### Transformation Rules: * - If an object has `enabled: true`, it is replaced by the same object without the `enabled` field. * - If it has only `enabled: true`, it is replaced with `true`. * - If it has `enabled: false`, it is replaced with `false` regardless of other fields. * * ### Examples: * Input: { prop: { enabled: true, hello: 'world' }} * Output: { prop: { hello: 'world' } } * * Input: { prop: { enabled: true }} * Output: { prop: true } * * Input: { prop: { enabled: false, hello: 'world' }} * Output: { prop: false } * * Input: { prop: { hello: 'world' }} * Output: { prop: { hello: 'world' } } // No change * * @param config Remote config object to be transformed * @returns Transformed config object compatible with local schema */ function translateRemoteConfigToLocal(config) { var e_1, _a, e_2, _b, e_3, _c; var _d, _e, _f, _g, _h, _j; // Disabling type checking rules because remote config comes from a remote source // and this function needs to handle any unexpected values /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument */ if (typeof config !== 'object' || config === null) { return; } // translations are not applied on array properties if (Array.isArray(config)) { return; } var propertyNames = Object.keys(config); try { for (var propertyNames_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(propertyNames), propertyNames_1_1 = propertyNames_1.next(); !propertyNames_1_1.done; propertyNames_1_1 = propertyNames_1.next()) { var propertyName = propertyNames_1_1.value; try { var value = config[propertyName]; // transform objects with { enabled } property to boolean | object if (typeof (value === null || value === void 0 ? void 0 : value.enabled) === 'boolean') { if (value.enabled) { // if enabled is true, set the value to the rest of the object // or true if the object has no other properties delete value.enabled; if (Object.keys(value).length === 0) { config[propertyName] = true; } } else { // If enabled is false, set the value to false config[propertyName] = false; } } // recursively translate properties of the value translateRemoteConfigToLocal(value); } catch (e) { // a failure here means that an accessor threw an error // so don't translate it // TODO(diagnostics): add a diagnostic event for this } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (propertyNames_1_1 && !propertyNames_1_1.done && (_a = propertyNames_1.return)) _a.call(propertyNames_1); } finally { if (e_1) throw e_1.error; } } // translate remote responseHeaders and requestHeaders to local responseHeaders and requestHeaders try { if ((_f = (_e = (_d = config.autocapture) === null || _d === void 0 ? void 0 : _d.networkTracking) === null || _e === void 0 ? void 0 : _e.captureRules) === null || _f === void 0 ? void 0 : _f.length) { try { for (var _k = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(config.autocapture.networkTracking.captureRules), _l = _k.next(); !_l.done; _l = _k.next()) { var rule = _l.value; try { for (var _m = (e_3 = void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(['responseHeaders', 'requestHeaders'])), _o = _m.next(); !_o.done; _o = _m.next()) { var header = _o.value; var _p = (_g = rule[header]) !== null && _g !== void 0 ? _g : {}, captureSafeHeaders = _p.captureSafeHeaders, allowlist = _p.allowlist; if (!captureSafeHeaders && !allowlist) { continue; } // if allowlist is not an array, remote config contract is violated, remove it if (allowlist !== undefined && !Array.isArray(allowlist)) { delete rule[header]; continue; } rule[header] = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)((captureSafeHeaders ? _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.SAFE_HEADERS : [])), false), (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)((allowlist !== null && allowlist !== void 0 ? allowlist : [])), false); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_o && !_o.done && (_c = _m.return)) _c.call(_m); } finally { if (e_3) throw e_3.error; } } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_l && !_l.done && (_b = _k.return)) _b.call(_k); } finally { if (e_2) throw e_2.error; } } } } catch (e) { /* istanbul ignore next */ // surprise exception, so don't translate it } // translate frustrationInteractions pluralization var frustrationInteractions = (_h = config.autocapture) === null || _h === void 0 ? void 0 : _h.frustrationInteractions; if (frustrationInteractions) { if (frustrationInteractions.rageClick) { frustrationInteractions.rageClicks = frustrationInteractions.rageClick; delete frustrationInteractions.rageClick; } if (frustrationInteractions.deadClick) { frustrationInteractions.deadClicks = frustrationInteractions.deadClick; delete frustrationInteractions.deadClick; } } // normalize viewportContentUpdated inside elementInteractions try { var elementInteractions = (_j = config.autocapture) === null || _j === void 0 ? void 0 : _j.elementInteractions; if (elementInteractions && typeof elementInteractions === 'object') { // { enabled: true } (no other fields) collapses to `true`; convert back to {} for the SDK. if (elementInteractions.viewportContentUpdated === true) { elementInteractions.viewportContentUpdated = {}; } // { enabled: false, ... } collapses to `false`; convert back to { enabled: false } for the SDK. if (elementInteractions.viewportContentUpdated === false) { elementInteractions.viewportContentUpdated = { enabled: false }; } // Migrate deprecated top-level exposureDuration to viewportContentUpdated.exposureDuration if (elementInteractions.exposureDuration !== undefined) { var viewportContentUpdated = elementInteractions.viewportContentUpdated; if (viewportContentUpdated === undefined) { elementInteractions.viewportContentUpdated = { exposureDuration: elementInteractions.exposureDuration }; } else if (typeof viewportContentUpdated === 'object' && viewportContentUpdated.exposureDuration === undefined && viewportContentUpdated.enabled !== false) { viewportContentUpdated.exposureDuration = elementInteractions.exposureDuration; } delete elementInteractions.exposureDuration; } } } catch (e) { /* istanbul ignore next */ // surprise exception, so don't translate it } } function mergeUrls(urlsExact, urlsRegex, browserConfig) { var e_4, _a; // Convert string patterns to RegExp objects, warn on invalid patterns and skip them var regexList = []; try { for (var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(urlsRegex !== null && urlsRegex !== void 0 ? urlsRegex : []), _c = _b.next(); !_c.done; _c = _b.next()) { var pattern = _c.value; try { regexList.push(new RegExp(pattern)); } catch (regexError) { browserConfig.loggerProvider.warn("Invalid regex pattern: ".concat(pattern), regexError); } } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_4) throw e_4.error; } } return urlsExact.concat(regexList); } /** * Updates the browser config in place by applying remote configuration settings. * Primarily merges autocapture settings from the remote config into the browser config. * * @param remoteConfig - The remote configuration to apply, or null if none available * @param browserConfig - The browser config object to update (modified in place) */ function updateBrowserConfigWithRemoteConfig(remoteConfig, browserConfig) { var e_5, _a; var _b, _c, _d, _e, _f; if (!remoteConfig) { return; } // translate remote config to local compatible format translateRemoteConfigToLocal(remoteConfig); try { browserConfig.loggerProvider.debug('Update browser config with remote configuration:', JSON.stringify(remoteConfig)); // type cast error will be thrown if remoteConfig is not a valid RemoteConfigBrowserSDK // and it will be caught by the try-catch block var typedRemoteConfig = remoteConfig; // merge remoteConfig.autocapture and browserConfig.autocapture // if a field is in remoteConfig.autocapture, use that value // if a field is not in remoteConfig.autocapture, use the value from browserConfig.autocapture if (typedRemoteConfig && 'autocapture' in typedRemoteConfig) { if (typeof typedRemoteConfig.autocapture === 'boolean') { browserConfig.autocapture = typedRemoteConfig.autocapture; } if (typeof typedRemoteConfig.autocapture === 'object' && typedRemoteConfig.autocapture !== null) { var transformedAutocaptureRemoteConfig = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, typedRemoteConfig.autocapture); if (browserConfig.autocapture === undefined) { browserConfig.autocapture = typedRemoteConfig.autocapture; } // Handle Element Interactions config initialization if (typeof typedRemoteConfig.autocapture.elementInteractions === 'object' && typedRemoteConfig.autocapture.elementInteractions !== null && ((_b = typedRemoteConfig.autocapture.elementInteractions.pageUrlAllowlistRegex) === null || _b === void 0 ? void 0 : _b.length)) { transformedAutocaptureRemoteConfig.elementInteractions = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, typedRemoteConfig.autocapture.elementInteractions); var transformedRcElementInteractions = transformedAutocaptureRemoteConfig.elementInteractions; // combine exact allow list and regex allow list into just 'pageUrlAllowlist' var exactAllowList = (_c = transformedRcElementInteractions.pageUrlAllowlist) !== null && _c !== void 0 ? _c : []; var urlsRegex = typedRemoteConfig.autocapture.elementInteractions.pageUrlAllowlistRegex; transformedRcElementInteractions.pageUrlAllowlist = mergeUrls(exactAllowList, urlsRegex, browserConfig); // clean up the regex allow list delete transformedRcElementInteractions.pageUrlAllowlistRegex; } // Handle Network Tracking config initialization if (typeof typedRemoteConfig.autocapture.networkTracking === 'object' && typedRemoteConfig.autocapture.networkTracking !== null && ((_d = typedRemoteConfig.autocapture.networkTracking.captureRules) === null || _d === void 0 ? void 0 : _d.length)) { transformedAutocaptureRemoteConfig.networkTracking = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, typedRemoteConfig.autocapture.networkTracking); var transformedRcNetworkTracking = transformedAutocaptureRemoteConfig.networkTracking; /* istanbul ignore next */ var captureRules = (_e = transformedRcNetworkTracking.captureRules) !== null && _e !== void 0 ? _e : []; try { for (var captureRules_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(captureRules), captureRules_1_1 = captureRules_1.next(); !captureRules_1_1.done; captureRules_1_1 = captureRules_1.next()) { var rule = captureRules_1_1.value; rule.urls = mergeUrls((_f = rule.urls) !== null && _f !== void 0 ? _f : [], rule.urlsRegex, browserConfig); delete rule.urlsRegex; } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (captureRules_1_1 && !captureRules_1_1.done && (_a = captureRules_1.return)) _a.call(captureRules_1); } finally { if (e_5) throw e_5.error; } } } if (typeof browserConfig.autocapture === 'boolean') { browserConfig.autocapture = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ attribution: browserConfig.autocapture, fileDownloads: browserConfig.autocapture, formInteractions: browserConfig.autocapture, pageViews: browserConfig.autocapture, sessions: browserConfig.autocapture, elementInteractions: browserConfig.autocapture, webVitals: browserConfig.autocapture, frustrationInteractions: browserConfig.autocapture }, transformedAutocaptureRemoteConfig); } if (typeof browserConfig.autocapture === 'object') { browserConfig.autocapture = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, browserConfig.autocapture), transformedAutocaptureRemoteConfig); } } // Override default tracking options if autocapture is updated by remote config browserConfig.defaultTracking = browserConfig.autocapture; } if ('customEnrichment' in typedRemoteConfig && typedRemoteConfig.customEnrichment !== null) { // Respect a locally-explicit false: if the user disabled custom enrichment at init time, // remote config must not re-enable it. if (browserConfig.customEnrichment !== false) { browserConfig.customEnrichment = typedRemoteConfig.customEnrichment; } } browserConfig.loggerProvider.debug('Browser config after remote config update:', JSON.stringify(browserConfig)); } catch (e) { browserConfig.loggerProvider.error('Failed to apply remote configuration because of error: ', e); } } //# sourceMappingURL=joined-config.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/constants.js" /*!************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/constants.js ***! \************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DEFAULT_EVENT_PREFIX: () => (/* binding */ DEFAULT_EVENT_PREFIX), /* harmony export */ DEFAULT_FILE_DOWNLOAD_EVENT: () => (/* binding */ DEFAULT_FILE_DOWNLOAD_EVENT), /* harmony export */ DEFAULT_FORM_START_EVENT: () => (/* binding */ DEFAULT_FORM_START_EVENT), /* harmony export */ DEFAULT_FORM_SUBMIT_EVENT: () => (/* binding */ DEFAULT_FORM_SUBMIT_EVENT), /* harmony export */ DEFAULT_IDENTITY_STORAGE: () => (/* binding */ DEFAULT_IDENTITY_STORAGE), /* harmony export */ DEFAULT_PAGE_VIEW_EVENT: () => (/* binding */ DEFAULT_PAGE_VIEW_EVENT), /* harmony export */ DEFAULT_SERVER_ZONE: () => (/* binding */ DEFAULT_SERVER_ZONE), /* harmony export */ DEFAULT_SESSION_END_EVENT: () => (/* binding */ DEFAULT_SESSION_END_EVENT), /* harmony export */ DEFAULT_SESSION_START_EVENT: () => (/* binding */ DEFAULT_SESSION_START_EVENT), /* harmony export */ FILE_EXTENSION: () => (/* binding */ FILE_EXTENSION), /* harmony export */ FILE_NAME: () => (/* binding */ FILE_NAME), /* harmony export */ FORM_DESTINATION: () => (/* binding */ FORM_DESTINATION), /* harmony export */ FORM_ID: () => (/* binding */ FORM_ID), /* harmony export */ FORM_NAME: () => (/* binding */ FORM_NAME), /* harmony export */ LINK_ID: () => (/* binding */ LINK_ID), /* harmony export */ LINK_TEXT: () => (/* binding */ LINK_TEXT), /* harmony export */ LINK_URL: () => (/* binding */ LINK_URL) /* harmony export */ }); var DEFAULT_EVENT_PREFIX = '[Amplitude]'; var DEFAULT_PAGE_VIEW_EVENT = "".concat(DEFAULT_EVENT_PREFIX, " Page Viewed"); var DEFAULT_FORM_START_EVENT = "".concat(DEFAULT_EVENT_PREFIX, " Form Started"); var DEFAULT_FORM_SUBMIT_EVENT = "".concat(DEFAULT_EVENT_PREFIX, " Form Submitted"); var DEFAULT_FILE_DOWNLOAD_EVENT = "".concat(DEFAULT_EVENT_PREFIX, " File Downloaded"); var DEFAULT_SESSION_START_EVENT = 'session_start'; var DEFAULT_SESSION_END_EVENT = 'session_end'; var FILE_EXTENSION = "".concat(DEFAULT_EVENT_PREFIX, " File Extension"); var FILE_NAME = "".concat(DEFAULT_EVENT_PREFIX, " File Name"); var LINK_ID = "".concat(DEFAULT_EVENT_PREFIX, " Link ID"); var LINK_TEXT = "".concat(DEFAULT_EVENT_PREFIX, " Link Text"); var LINK_URL = "".concat(DEFAULT_EVENT_PREFIX, " Link URL"); var FORM_ID = "".concat(DEFAULT_EVENT_PREFIX, " Form ID"); var FORM_NAME = "".concat(DEFAULT_EVENT_PREFIX, " Form Name"); var FORM_DESTINATION = "".concat(DEFAULT_EVENT_PREFIX, " Form Destination"); var DEFAULT_IDENTITY_STORAGE = 'cookie'; var DEFAULT_SERVER_ZONE = 'US'; //# sourceMappingURL=constants.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/cookie-migration/index.js" /*!*************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/cookie-migration/index.js ***! \*************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ decode: () => (/* binding */ decode), /* harmony export */ parseLegacyCookies: () => (/* binding */ parseLegacyCookies), /* harmony export */ parseTime: () => (/* binding */ parseTime) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/cookie-name.js"); var parseLegacyCookies = function (apiKey, cookieStorage, deleteLegacyCookies) { if (deleteLegacyCookies === void 0) { deleteLegacyCookies = true; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { var cookieName, cookies, _a, deviceId, userId, optOut, sessionId, lastEventTime, lastEventId; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: cookieName = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getOldCookieName)(apiKey); return [4 /*yield*/, cookieStorage.getRaw(cookieName)]; case 1: cookies = _b.sent(); if (!cookies) { return [2 /*return*/, { optOut: false, }]; } if (!deleteLegacyCookies) return [3 /*break*/, 3]; return [4 /*yield*/, cookieStorage.remove(cookieName)]; case 2: _b.sent(); _b.label = 3; case 3: _a = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(cookies.split('.'), 6), deviceId = _a[0], userId = _a[1], optOut = _a[2], sessionId = _a[3], lastEventTime = _a[4], lastEventId = _a[5]; return [2 /*return*/, { deviceId: deviceId, userId: decode(userId), sessionId: parseTime(sessionId), lastEventId: parseTime(lastEventId), lastEventTime: parseTime(lastEventTime), optOut: Boolean(optOut), }]; } }); }); }; var parseTime = function (num) { var integer = parseInt(num, 32); if (isNaN(integer)) { return undefined; } return integer; }; var decode = function (value) { if (!atob || !escape || !value) { return undefined; } try { return decodeURIComponent(escape(atob(value))); } catch (_a) { return undefined; } }; //# sourceMappingURL=index.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/default-tracking.js" /*!*******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/default-tracking.js ***! \*******************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getAttributionTrackingConfig: () => (/* binding */ getAttributionTrackingConfig), /* harmony export */ getElementInteractionsConfig: () => (/* binding */ getElementInteractionsConfig), /* harmony export */ getFormInteractionsConfig: () => (/* binding */ getFormInteractionsConfig), /* harmony export */ getFrustrationInteractionsConfig: () => (/* binding */ getFrustrationInteractionsConfig), /* harmony export */ getNetworkTrackingConfig: () => (/* binding */ getNetworkTrackingConfig), /* harmony export */ getPageViewTrackingConfig: () => (/* binding */ getPageViewTrackingConfig), /* harmony export */ getPerformanceTrackingConfig: () => (/* binding */ getPerformanceTrackingConfig), /* harmony export */ isAttributionTrackingEnabled: () => (/* binding */ isAttributionTrackingEnabled), /* harmony export */ isCustomEnrichmentEnabled: () => (/* binding */ isCustomEnrichmentEnabled), /* harmony export */ isElementInteractionsEnabled: () => (/* binding */ isElementInteractionsEnabled), /* harmony export */ isFileDownloadTrackingEnabled: () => (/* binding */ isFileDownloadTrackingEnabled), /* harmony export */ isFormInteractionTrackingEnabled: () => (/* binding */ isFormInteractionTrackingEnabled), /* harmony export */ isFrustrationInteractionsEnabled: () => (/* binding */ isFrustrationInteractionsEnabled), /* harmony export */ isNetworkTrackingEnabled: () => (/* binding */ isNetworkTrackingEnabled), /* harmony export */ isPageUrlEnrichmentEnabled: () => (/* binding */ isPageUrlEnrichmentEnabled), /* harmony export */ isPageViewTrackingEnabled: () => (/* binding */ isPageViewTrackingEnabled), /* harmony export */ isPerformanceTrackingEnabled: () => (/* binding */ isPerformanceTrackingEnabled), /* harmony export */ isSessionTrackingEnabled: () => (/* binding */ isSessionTrackingEnabled), /* harmony export */ isWebVitalsEnabled: () => (/* binding */ isWebVitalsEnabled) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/environment.js"); /** * Returns false if autocapture === false or if autocapture[event], * otherwise returns true (even if "config.autocapture === undefined") */ var isTrackingEnabled = function (autocapture, event) { if (typeof autocapture === 'boolean') { return autocapture; } if ((autocapture === null || autocapture === void 0 ? void 0 : autocapture[event]) === false) { return false; } if ((0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.isChromeExtension)()) { return !!(autocapture === null || autocapture === void 0 ? void 0 : autocapture[event]); } return true; }; var isAttributionTrackingEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'attribution'); }; var isFileDownloadTrackingEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'fileDownloads'); }; var isFormInteractionTrackingEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'formInteractions'); }; var isPageViewTrackingEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'pageViews'); }; var isSessionTrackingEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'sessions'); }; var isPageUrlEnrichmentEnabled = function (autocapture) { return isTrackingEnabled(autocapture, 'pageUrlEnrichment'); }; /** * Returns true if * 1. if autocapture.networkTracking === true * 2. if autocapture.networkTracking === object * otherwise returns false */ var isNetworkTrackingEnabled = function (autocapture) { if (typeof autocapture === 'boolean') { return autocapture; } if (typeof autocapture === 'object' && (autocapture.networkTracking === true || typeof autocapture.networkTracking === 'object')) { return true; } return false; }; /** * Returns true if * 1. autocapture === true * 2. if autocapture.elementInteractions === true * 3. if autocapture.elementInteractions === object * otherwise returns false */ var isElementInteractionsEnabled = function (autocapture) { if (typeof autocapture === 'boolean') { return autocapture; } if (typeof autocapture === 'object' && (autocapture.elementInteractions === true || typeof autocapture.elementInteractions === 'object')) { return true; } return false; }; /** * Returns true if * 1. autocapture === true * 2. if autocapture.webVitals === true * otherwise returns false */ var isWebVitalsEnabled = function (autocapture) { if (typeof autocapture === 'boolean') { return autocapture; } if (typeof autocapture === 'object' && autocapture.webVitals === true) { return true; } return false; }; var isFrustrationInteractionsEnabled = function (autocapture) { if (typeof autocapture === 'boolean') { return autocapture; } if (typeof autocapture === 'object' && (autocapture.frustrationInteractions === true || typeof autocapture.frustrationInteractions === 'object')) { return true; } return false; }; var isPerformanceTrackingEnabled = function (autocapture) { if (typeof autocapture === 'object' && (autocapture.performanceTracking === true || typeof autocapture.performanceTracking === 'object')) { return true; } return false; }; var getPerformanceTrackingConfig = function (config) { if (typeof config.autocapture !== 'object') { return undefined; } var performanceTracking = config.autocapture.performanceTracking; if (performanceTracking === true) { return { mainThreadBlock: true }; } if (typeof performanceTracking === 'object' && performanceTracking !== null) { return performanceTracking; } return undefined; }; var isCustomEnrichmentEnabled = function (customEnrichment) { if (typeof customEnrichment === 'boolean') { return customEnrichment; } if (typeof customEnrichment === 'object' && customEnrichment !== null && customEnrichment.enabled !== false) { return true; } return false; }; var getElementInteractionsConfig = function (config) { if (isElementInteractionsEnabled(config.autocapture) && typeof config.autocapture === 'object' && typeof config.autocapture.elementInteractions === 'object') { return config.autocapture.elementInteractions; } return undefined; }; var getFrustrationInteractionsConfig = function (config) { if (isFrustrationInteractionsEnabled(config.autocapture) && typeof config.autocapture === 'object' && typeof config.autocapture.frustrationInteractions === 'object') { return config.autocapture.frustrationInteractions; } return undefined; }; var getNetworkTrackingConfig = function (config) { var _a; if (isNetworkTrackingEnabled(config.autocapture)) { var networkTrackingConfig = void 0; if (typeof config.autocapture === 'object' && typeof config.autocapture.networkTracking === 'object') { networkTrackingConfig = config.autocapture.networkTracking; } else if (config.networkTrackingOptions) { networkTrackingConfig = config.networkTrackingOptions; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, networkTrackingConfig), { captureRules: (_a = networkTrackingConfig === null || networkTrackingConfig === void 0 ? void 0 : networkTrackingConfig.captureRules) === null || _a === void 0 ? void 0 : _a.map(function (rule) { var _a, _b, _c; // if URLs and hosts are both set, URLs take precedence over hosts if (((_a = rule.urls) === null || _a === void 0 ? void 0 : _a.length) && ((_b = rule.hosts) === null || _b === void 0 ? void 0 : _b.length)) { var hostsString = JSON.stringify(rule.hosts); var urlsString = JSON.stringify(rule.urls); /* istanbul ignore next */ (_c = config.loggerProvider) === null || _c === void 0 ? void 0 : _c.warn("Found network capture rule with both urls='".concat(urlsString, "' and hosts='").concat(hostsString, "' set. ") + "Definition of urls takes precedence over hosts, so ignoring hosts."); return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, rule), { hosts: undefined }); } return rule; }) }); } return; }; var getPageViewTrackingConfig = function (config) { var trackOn = function () { return false; }; var trackHistoryChanges = undefined; var eventType; var pageCounter = config.pageCounter; var isDefaultPageViewTrackingEnabled = isPageViewTrackingEnabled(config.defaultTracking); if (isDefaultPageViewTrackingEnabled) { trackOn = undefined; eventType = undefined; if (config.defaultTracking && typeof config.defaultTracking === 'object' && config.defaultTracking.pageViews && typeof config.defaultTracking.pageViews === 'object') { if ('trackOn' in config.defaultTracking.pageViews) { trackOn = config.defaultTracking.pageViews.trackOn; } if ('trackHistoryChanges' in config.defaultTracking.pageViews) { trackHistoryChanges = config.defaultTracking.pageViews.trackHistoryChanges; } if ('eventType' in config.defaultTracking.pageViews && config.defaultTracking.pageViews.eventType) { eventType = config.defaultTracking.pageViews.eventType; } } } return { trackOn: trackOn, trackHistoryChanges: trackHistoryChanges, eventType: eventType, pageCounter: pageCounter, }; }; var getAttributionTrackingConfig = function (config) { if (isAttributionTrackingEnabled(config.defaultTracking) && config.defaultTracking && typeof config.defaultTracking === 'object' && config.defaultTracking.attribution && typeof config.defaultTracking.attribution === 'object') { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, config.defaultTracking.attribution); } return {}; }; var getFormInteractionsConfig = function (config) { if (isFormInteractionTrackingEnabled(config.defaultTracking) && config.defaultTracking && typeof config.defaultTracking === 'object' && typeof config.defaultTracking.formInteractions === 'object') { return config.defaultTracking.formInteractions; } return undefined; }; //# sourceMappingURL=default-tracking.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/det-notification.js" /*!*******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/det-notification.js ***! \*******************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ detNotify: () => (/* binding */ detNotify), /* harmony export */ resetNotify: () => (/* binding */ resetNotify) /* harmony export */ }); var notified = false; var detNotify = function (config) { if (notified || config.defaultTracking !== undefined) { return; } var message = "`options.defaultTracking` is set to undefined. This implicitly configures your Amplitude instance to track Page Views, Sessions, File Downloads, and Form Interactions. You can suppress this warning by explicitly setting a value to `options.defaultTracking`. The value must either be a boolean, to enable and disable all default events, or an object, for advanced configuration. For example:\n\namplitude.init(, {\n defaultTracking: true,\n});\n\nVisit https://www.docs.developers.amplitude.com/data/sdks/browser-2/#tracking-default-events for more details."; config.loggerProvider.warn(message); notified = true; }; /** * @private * This function is meant for testing purposes only */ var resetNotify = function () { notified = false; }; //# sourceMappingURL=det-notification.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/index.js" /*!********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/index.js ***! \********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AmplitudeBrowser: () => (/* reexport safe */ _browser_client__WEBPACK_IMPORTED_MODULE_1__.AmplitudeBrowser), /* harmony export */ Identify: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.Identify), /* harmony export */ Revenue: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.Revenue), /* harmony export */ Types: () => (/* reexport module object */ _types__WEBPACK_IMPORTED_MODULE_6__), /* harmony export */ _setDiagnosticsSampleRate: () => (/* binding */ _setDiagnosticsSampleRate), /* harmony export */ add: () => (/* binding */ add), /* harmony export */ createInstance: () => (/* reexport safe */ _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__.createInstance), /* harmony export */ extendSession: () => (/* binding */ extendSession), /* harmony export */ flush: () => (/* binding */ flush), /* harmony export */ getDeviceId: () => (/* binding */ getDeviceId), /* harmony export */ getIdentity: () => (/* binding */ getIdentity), /* harmony export */ getOptOut: () => (/* binding */ getOptOut), /* harmony export */ getSessionId: () => (/* binding */ getSessionId), /* harmony export */ getUserId: () => (/* binding */ getUserId), /* harmony export */ groupIdentify: () => (/* binding */ groupIdentify), /* harmony export */ identify: () => (/* binding */ identify), /* harmony export */ init: () => (/* binding */ init), /* harmony export */ logEvent: () => (/* binding */ logEvent), /* harmony export */ remove: () => (/* binding */ remove), /* harmony export */ reset: () => (/* binding */ reset), /* harmony export */ revenue: () => (/* binding */ revenue), /* harmony export */ runQueuedFunctions: () => (/* reexport safe */ _utils_snippet_helper__WEBPACK_IMPORTED_MODULE_2__.runQueuedFunctions), /* harmony export */ setDeviceId: () => (/* binding */ setDeviceId), /* harmony export */ setGroup: () => (/* binding */ setGroup), /* harmony export */ setIdentity: () => (/* binding */ setIdentity), /* harmony export */ setOptOut: () => (/* binding */ setOptOut), /* harmony export */ setSessionId: () => (/* binding */ setSessionId), /* harmony export */ setTransport: () => (/* binding */ setTransport), /* harmony export */ setUserId: () => (/* binding */ setUserId), /* harmony export */ track: () => (/* binding */ track), /* harmony export */ trackVideo: () => (/* reexport safe */ _video_capture_video_capture__WEBPACK_IMPORTED_MODULE_5__.trackVideo) /* harmony export */ }); /* harmony import */ var _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./browser-client-factory */ "./node_modules/@amplitude/analytics-browser/lib/esm/browser-client-factory.js"); /* harmony import */ var _browser_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./browser-client */ "./node_modules/@amplitude/analytics-browser/lib/esm/browser-client.js"); /* harmony import */ var _utils_snippet_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/snippet-helper */ "./node_modules/@amplitude/analytics-browser/lib/esm/utils/snippet-helper.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/identify.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/revenue.js"); /* harmony import */ var _video_capture_video_capture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./video-capture/video-capture */ "./node_modules/@amplitude/analytics-browser/lib/esm/video-capture/video-capture.js"); /* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./types */ "./node_modules/@amplitude/analytics-browser/lib/esm/types.js"); /* eslint-disable @typescript-eslint/unbound-method */ var add = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].add, extendSession = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].extendSession, flush = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].flush, getDeviceId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].getDeviceId, getIdentity = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].getIdentity, getOptOut = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].getOptOut, getSessionId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].getSessionId, getUserId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].getUserId, groupIdentify = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].groupIdentify, identify = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].identify, init = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].init, logEvent = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].logEvent, remove = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].remove, reset = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].reset, revenue = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].revenue, setDeviceId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setDeviceId, setGroup = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setGroup, setIdentity = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setIdentity, setOptOut = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setOptOut, setSessionId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setSessionId, setTransport = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setTransport, setUserId = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].setUserId, track = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"].track, _setDiagnosticsSampleRate = _browser_client_factory__WEBPACK_IMPORTED_MODULE_0__["default"]._setDiagnosticsSampleRate; //# sourceMappingURL=index.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/lib-prefix.js" /*!*************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/lib-prefix.js ***! \*************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LIBPREFIX: () => (/* binding */ LIBPREFIX) /* harmony export */ }); var LIBPREFIX = 'amplitude-ts'; //# sourceMappingURL=lib-prefix.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/context.js" /*!******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/plugins/context.js ***! \******************************************************************************/ (__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 */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/language.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/uuid.js"); /* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../version */ "./node_modules/@amplitude/analytics-browser/lib/esm/version.js"); /* harmony import */ var _lib_prefix__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../lib-prefix */ "./node_modules/@amplitude/analytics-browser/lib/esm/lib-prefix.js"); var BROWSER_PLATFORM = 'Web'; var IP_ADDRESS = '$remote'; var Context = /** @class */ (function () { function Context() { this.name = '@amplitude/plugin-context-browser'; this.type = 'before'; this.library = "".concat(_lib_prefix__WEBPACK_IMPORTED_MODULE_4__.LIBPREFIX, "/").concat(_version__WEBPACK_IMPORTED_MODULE_3__.VERSION); /* istanbul ignore else */ if (typeof navigator !== 'undefined') { this.userAgent = navigator.userAgent; } } Context.prototype.setup = function (config) { this.config = config; return Promise.resolve(undefined); }; Context.prototype.execute = function (context) { var _a, _b; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var time, lastEventId, nextEventId, event; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_c) { time = new Date().getTime(); lastEventId = (_a = this.config.lastEventId) !== null && _a !== void 0 ? _a : -1; nextEventId = (_b = context.event_id) !== null && _b !== void 0 ? _b : lastEventId + 1; this.config.lastEventId = nextEventId; if (!context.time) { this.config.lastEventTime = time; } event = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ user_id: this.config.userId, device_id: this.config.deviceId, session_id: this.config.sessionId, time: time }, (this.config.appVersion && { app_version: this.config.appVersion })), (this.config.trackingOptions.platform && { platform: BROWSER_PLATFORM })), (this.config.trackingOptions.language && { language: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getLanguage)() })), (this.config.trackingOptions.ipAddress && { ip: IP_ADDRESS })), { insert_id: (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.UUID)(), partner_id: this.config.partnerId, plan: this.config.plan }), (this.config.ingestionMetadata && { ingestion_metadata: { source_name: this.config.ingestionMetadata.sourceName, source_version: this.config.ingestionMetadata.sourceVersion, }, })), context), { event_id: nextEventId, library: this.library, user_agent: this.userAgent }); return [2 /*return*/, event]; }); }); }; return Context; }()); //# sourceMappingURL=context.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/file-download-tracking.js" /*!*********************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/plugins/file-download-tracking.js ***! \*********************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ fileDownloadTracking: () => (/* binding */ fileDownloadTracking) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constants */ "./node_modules/@amplitude/analytics-browser/lib/esm/constants.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); var fileDownloadTracking = function () { var observer; var eventListeners = []; var addEventListener = function (element, type, handler) { element.addEventListener(type, handler); eventListeners.push({ element: element, type: type, handler: handler, }); }; var removeClickListeners = function () { eventListeners.forEach(function (_a) { var element = _a.element, type = _a.type, handler = _a.handler; /* istanbul ignore next */ element === null || element === void 0 ? void 0 : element.removeEventListener(type, handler); }); eventListeners = []; }; var name = '@amplitude/plugin-file-download-tracking-browser'; var type = 'enrichment'; var setup = function (config, amplitude) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { var initializeFileDownloadTracking, window_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { initializeFileDownloadTracking = function () { /* istanbul ignore if */ if (!amplitude) { // TODO: Add required minimum version of @amplitude/analytics-browser config.loggerProvider.warn('File download tracking requires a later version of @amplitude/analytics-browser. File download events are not tracked.'); return; } /* istanbul ignore if */ if (typeof document === 'undefined') { return; } var addFileDownloadListener = function (a) { var url; try { // eslint-disable-next-line no-restricted-globals url = new URL(a.href, window.location.href); } catch (_a) { /* istanbul ignore next */ return; } var result = ext.exec(url.href); var fileExtension = result === null || result === void 0 ? void 0 : result[1]; if (fileExtension) { addEventListener(a, 'click', function () { var _a; if (fileExtension) { amplitude.track(_constants__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_FILE_DOWNLOAD_EVENT, (_a = {}, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FILE_EXTENSION] = fileExtension, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FILE_NAME] = url.pathname, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.LINK_ID] = a.id, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.LINK_TEXT] = a.text, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.LINK_URL] = a.href, _a)); } }); } }; var ext = /\.(pdf|xlsx?|docx?|txt|rtf|csv|exe|key|pp(s|t|tx)|7z|pkg|rar|gz|zip|avi|mov|mp4|mpe?g|wmv|midi?|mp3|wav|wma)(\?.+)?$/; // Adds listener to existing anchor tags var links = Array.from(document.getElementsByTagName('a')); links.forEach(addFileDownloadListener); // Adds listener to anchor tags added after initial load /* istanbul ignore else */ if (typeof MutationObserver !== 'undefined') { observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (node) { if (node.nodeName === 'A') { addFileDownloadListener(node); } if ('querySelectorAll' in node && typeof node.querySelectorAll === 'function') { Array.from(node.querySelectorAll('a')).map(addFileDownloadListener); } }); }); }); observer.observe(document.body, { subtree: true, childList: true, }); } }; // If the document is already loaded, initialize immediately. /* istanbul ignore else*/ if (document.readyState === 'complete') { initializeFileDownloadTracking(); } else { window_1 = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getGlobalScope)(); /* istanbul ignore else*/ if (window_1) { window_1.addEventListener('load', initializeFileDownloadTracking); } else { config.loggerProvider.debug('File download tracking is not installed because global is undefined.'); } } return [2 /*return*/]; }); }); }; var execute = function (event) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, event]; }); }); }; var teardown = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { observer === null || observer === void 0 ? void 0 : observer.disconnect(); removeClickListeners(); return [2 /*return*/]; }); }); }; return { name: name, type: type, setup: setup, execute: execute, teardown: teardown, }; }; //# sourceMappingURL=file-download-tracking.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/form-interaction-tracking.js" /*!************************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/plugins/form-interaction-tracking.js ***! \************************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ extractFormAction: () => (/* binding */ extractFormAction), /* harmony export */ formInteractionTracking: () => (/* binding */ formInteractionTracking), /* harmony export */ stringOrUndefined: () => (/* binding */ stringOrUndefined) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constants */ "./node_modules/@amplitude/analytics-browser/lib/esm/constants.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _default_tracking__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../default-tracking */ "./node_modules/@amplitude/analytics-browser/lib/esm/default-tracking.js"); var formInteractionTracking = function () { var observer; var eventListeners = []; var addEventListener = function (element, type, handler) { element.addEventListener(type, handler); eventListeners.push({ element: element, type: type, handler: handler, }); }; var removeClickListeners = function () { eventListeners.forEach(function (_a) { var element = _a.element, type = _a.type, handler = _a.handler; /* istanbul ignore next */ element === null || element === void 0 ? void 0 : element.removeEventListener(type, handler); }); eventListeners = []; }; var formInteractionsConfig; var name = '@amplitude/plugin-form-interaction-tracking-browser'; var type = 'enrichment'; var setup = function (config, amplitude) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { var initializeFormTracking, window_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { formInteractionsConfig = (0,_default_tracking__WEBPACK_IMPORTED_MODULE_3__.getFormInteractionsConfig)(config); initializeFormTracking = function () { /* istanbul ignore if */ if (!amplitude) { // TODO: Add required minimum version of @amplitude/analytics-browser config.loggerProvider.warn('Form interaction tracking requires a later version of @amplitude/analytics-browser. Form interaction events are not tracked.'); return; } /* istanbul ignore if */ if (typeof document === 'undefined') { return; } var addedFormNodes = new WeakSet(); var addFormInteractionListener = function (form) { if (addedFormNodes.has(form)) { return; } addedFormNodes.add(form); var hasFormChanged = false; addEventListener(form, 'change', function () { var _a; var formDestination = extractFormAction(form); if (!hasFormChanged) { amplitude.track(_constants__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_FORM_START_EVENT, (_a = {}, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_ID] = stringOrUndefined(form.id), _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_NAME] = stringOrUndefined(form.name), _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_DESTINATION] = formDestination, _a)); } hasFormChanged = true; }); addEventListener(form, 'submit', function (event) { var _a, _b; var formDestination = extractFormAction(form); if (!hasFormChanged) { amplitude.track(_constants__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_FORM_START_EVENT, (_a = {}, _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_ID] = stringOrUndefined(form.id), _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_NAME] = stringOrUndefined(form.name), _a[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_DESTINATION] = formDestination, _a)); } hasFormChanged = true; // Check if shouldTrackSubmit callback is provided and use it to determine whether to track form_submit if ((formInteractionsConfig === null || formInteractionsConfig === void 0 ? void 0 : formInteractionsConfig.shouldTrackSubmit) !== undefined) { if (typeof formInteractionsConfig.shouldTrackSubmit === 'function' && typeof SubmitEvent !== 'undefined' && event instanceof SubmitEvent) { try { var shouldTrack = formInteractionsConfig.shouldTrackSubmit(event); if (!shouldTrack) { return; } } catch (e) { config.loggerProvider.warn('shouldTrackSubmit callback threw an error, proceeding with tracking.'); } } else { config.loggerProvider.warn('shouldTrackSubmit is ignored because it is not a function or event is not a SubmitEvent.'); } } amplitude.track(_constants__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_FORM_SUBMIT_EVENT, (_b = {}, _b[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_ID] = stringOrUndefined(form.id), _b[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_NAME] = stringOrUndefined(form.name), _b[_constants__WEBPACK_IMPORTED_MODULE_1__.FORM_DESTINATION] = formDestination, _b)); hasFormChanged = false; }); }; // Adds listener to existing anchor tags var forms = Array.from(document.getElementsByTagName('form')); forms.forEach(addFormInteractionListener); // Adds listener to anchor tags added after initial load /* istanbul ignore else */ if (typeof MutationObserver !== 'undefined') { observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (node) { if (node.nodeName === 'FORM') { addFormInteractionListener(node); } if ('querySelectorAll' in node && typeof node.querySelectorAll === 'function') { Array.from(node.querySelectorAll('form')).map(addFormInteractionListener); } }); }); }); observer.observe(document.body, { subtree: true, childList: true, }); } }; // If the document is already loaded, initialize immediately. if (document.readyState === 'complete') { initializeFormTracking(); } else { window_1 = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.getGlobalScope)(); /* istanbul ignore else*/ if (window_1) { window_1.addEventListener('load', initializeFormTracking); } else { config.loggerProvider.debug('Form interaction tracking is not installed because global is undefined.'); } } return [2 /*return*/]; }); }); }; var execute = function (event) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, event]; }); }); }; var teardown = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { observer === null || observer === void 0 ? void 0 : observer.disconnect(); removeClickListeners(); return [2 /*return*/]; }); }); }; return { name: name, type: type, setup: setup, execute: execute, teardown: teardown, }; }; var stringOrUndefined = function (name) { /* istanbul ignore if */ if (typeof name !== 'string') { // We found instances where the value of `name` is an Element and not a string. // Elements may have circular references and would throw an error when passed to `JSON.stringify(...)`. // If a non-string value is seen, assume there is no value. return undefined; } return name; }; // Extracts the form action attribute, and normalizes it to a valid URL to preserve the previous behavior of accessing the action property directly. var extractFormAction = function (form) { var formDestination = form.getAttribute('action'); try { // eslint-disable-next-line no-restricted-globals formDestination = new URL(encodeURI(formDestination !== null && formDestination !== void 0 ? formDestination : ''), window.location.href).href; } catch (_a) { // } return formDestination; }; //# sourceMappingURL=form-interaction-tracking.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/plugins/network-connectivity-checker.js" /*!***************************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/plugins/network-connectivity-checker.js ***! \***************************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ networkConnectivityCheckerPlugin: () => (/* binding */ networkConnectivityCheckerPlugin) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); var networkConnectivityCheckerPlugin = function () { var name = '@amplitude/plugin-network-checker-browser'; var type = 'before'; var globalScope = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); var eventListeners = []; var addNetworkListener = function (type, handler) { /* istanbul ignore next */ if (globalScope === null || globalScope === void 0 ? void 0 : globalScope.addEventListener) { globalScope === null || globalScope === void 0 ? void 0 : globalScope.addEventListener(type, handler); eventListeners.push({ type: type, handler: handler, }); } }; var removeNetworkListeners = function () { eventListeners.forEach(function (_a) { var type = _a.type, handler = _a.handler; /* istanbul ignore next */ globalScope === null || globalScope === void 0 ? void 0 : globalScope.removeEventListener(type, handler); }); eventListeners = []; }; var setup = function (config, amplitude) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { if (typeof navigator === 'undefined') { config.loggerProvider.debug('Network connectivity checker plugin is disabled because navigator is not available.'); config.offline = false; return [2 /*return*/]; } config.offline = !navigator.onLine; addNetworkListener('online', function () { config.loggerProvider.debug('Network connectivity changed to online.'); config.offline = false; // Flush immediately will cause ERR_NETWORK_CHANGED setTimeout(function () { amplitude.flush(); }, config.flushIntervalMillis); }); addNetworkListener('offline', function () { config.loggerProvider.debug('Network connectivity changed to offline.'); config.offline = true; }); return [2 /*return*/]; }); }); }; var teardown = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(void 0, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { removeNetworkListeners(); return [2 /*return*/]; }); }); }; return { name: name, type: type, setup: setup, teardown: teardown, }; }; //# sourceMappingURL=network-connectivity-checker.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/storage/local-storage.js" /*!************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/storage/local-storage.js ***! \************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ LocalStorage: () => (/* binding */ LocalStorage) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/storage/browser-storage.js"); var MAX_ARRAY_LENGTH = 1000; var LocalStorage = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(LocalStorage, _super); function LocalStorage(config) { var _this = this; var _a, _b; var localStorage; try { localStorage = (_a = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)()) === null || _a === void 0 ? void 0 : _a.localStorage; } catch (e) { (_b = config === null || config === void 0 ? void 0 : config.loggerProvider) === null || _b === void 0 ? void 0 : _b.debug("Failed to access localStorage. error=".concat(JSON.stringify(e))); localStorage = undefined; } _this = _super.call(this, localStorage) || this; _this.loggerProvider = config === null || config === void 0 ? void 0 : config.loggerProvider; return _this; } LocalStorage.prototype.set = function (key, value) { var _a; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var droppedEventsCount; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: if (!(Array.isArray(value) && value.length > MAX_ARRAY_LENGTH)) return [3 /*break*/, 2]; droppedEventsCount = value.length - MAX_ARRAY_LENGTH; return [4 /*yield*/, _super.prototype.set.call(this, key, value.slice(0, MAX_ARRAY_LENGTH))]; case 1: _b.sent(); (_a = this.loggerProvider) === null || _a === void 0 ? void 0 : _a.error("Failed to save ".concat(droppedEventsCount, " events because the queue length exceeded ").concat(MAX_ARRAY_LENGTH, ".")); return [3 /*break*/, 4]; case 2: return [4 /*yield*/, _super.prototype.set.call(this, key, value)]; case 3: _b.sent(); _b.label = 4; case 4: return [2 /*return*/]; } }); }); }; return LocalStorage; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.BrowserStorage)); //# sourceMappingURL=local-storage.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/storage/session-storage.js" /*!**************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/storage/session-storage.js ***! \**************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SessionStorage: () => (/* binding */ SessionStorage) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/storage/browser-storage.js"); var SessionStorage = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(SessionStorage, _super); function SessionStorage() { var _a; return _super.call(this, (_a = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)()) === null || _a === void 0 ? void 0 : _a.sessionStorage) || this; } return SessionStorage; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.BrowserStorage)); //# sourceMappingURL=session-storage.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/fetch.js" /*!*******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/transports/fetch.js ***! \*******************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ FetchTransport: () => (/* binding */ FetchTransport) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/transports/base.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/transports/gzip.js"); // Temporary browser-specific fetch transport with gzip support. // TODO: Merge this implementation back into @amplitude/analytics-core FetchTransport // once React Native SDK supports request body gzip. var FetchTransport = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(FetchTransport, _super); function FetchTransport(customHeaders) { if (customHeaders === void 0) { customHeaders = {}; } var _this = _super.call(this) || this; _this.customHeaders = customHeaders; return _this; } FetchTransport.prototype.send = function (serverUrl, payload, shouldCompressUploadBody) { if (shouldCompressUploadBody === void 0) { shouldCompressUploadBody = false; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var bodyString, shouldCompressBody, body, headers, compressed, options, response, responseText; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: /* istanbul ignore if */ if (typeof fetch === 'undefined') { throw new Error('FetchTransport is not supported'); } bodyString = JSON.stringify(payload); shouldCompressBody = shouldCompressUploadBody && bodyString.length >= _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.MIN_GZIP_UPLOAD_BODY_SIZE_BYTES && (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.isCompressionStreamAvailable)(); body = bodyString; headers = { 'Content-Type': 'application/json', Accept: '*/*', }; if (!shouldCompressBody) return [3 /*break*/, 2]; return [4 /*yield*/, (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.compressToGzipArrayBuffer)(bodyString)]; case 1: compressed = _a.sent(); if (compressed) { headers['Content-Encoding'] = 'gzip'; body = compressed; } _a.label = 2; case 2: headers = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, this.customHeaders), headers); options = { headers: headers, body: body, method: 'POST', }; return [4 /*yield*/, fetch(serverUrl, options)]; case 3: response = _a.sent(); return [4 /*yield*/, response.text()]; case 4: responseText = _a.sent(); try { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument return [2 /*return*/, this.buildResponse(JSON.parse(responseText))]; } catch (_b) { return [2 /*return*/, this.buildResponse({ code: response.status })]; } // removed by dead control flow } }); }); }; return FetchTransport; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.BaseTransport)); //# sourceMappingURL=fetch.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/send-beacon.js" /*!*************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/transports/send-beacon.js ***! \*************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ SendBeaconTransport: () => (/* binding */ SendBeaconTransport) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/transports/base.js"); /** * SendBeacon does not support custom headers (e.g. Content-Encoding: gzip), * so request body compression is not applied even when enableRequestBodyCompression is true. */ var SendBeaconTransport = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(SendBeaconTransport, _super); function SendBeaconTransport() { return _super.call(this) || this; } SendBeaconTransport.prototype.send = function (serverUrl, payload, _enableRequestBodyCompression) { if (_enableRequestBodyCompression === void 0) { _enableRequestBodyCompression = false; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { var globalScope = (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); /* istanbul ignore if */ if (!(globalScope === null || globalScope === void 0 ? void 0 : globalScope.navigator.sendBeacon)) { throw new Error('SendBeaconTransport is not supported'); } try { var data = JSON.stringify(payload); // SendBeacon cannot set Content-Encoding, so we always send uncompressed var success = globalScope.navigator.sendBeacon(serverUrl, data); if (success) { return resolve(_this.buildResponse({ code: 200, events_ingested: payload.events.length, payload_size_bytes: data.length, server_upload_time: Date.now(), })); } return resolve(_this.buildResponse({ code: 500 })); } catch (e) { reject(e); } })]; }); }); }; return SendBeaconTransport; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.BaseTransport)); //# sourceMappingURL=send-beacon.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/transports/xhr.js" /*!*****************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/transports/xhr.js ***! \*****************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ XHRTransport: () => (/* binding */ XHRTransport) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/transports/base.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/transports/gzip.js"); var XHRTransport = /** @class */ (function (_super) { (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(XHRTransport, _super); function XHRTransport(customHeaders) { if (customHeaders === void 0) { customHeaders = {}; } var _this = _super.call(this) || this; _this.state = { done: 4, }; _this.customHeaders = customHeaders; return _this; } XHRTransport.prototype.send = function (serverUrl, payload, shouldCompressUploadBody) { if (shouldCompressUploadBody === void 0) { shouldCompressUploadBody = false; } return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { /* istanbul ignore if */ if (typeof XMLHttpRequest === 'undefined') { reject(new Error('XHRTransport is not supported.')); } var xhr = new XMLHttpRequest(); xhr.open('POST', serverUrl, true); xhr.onreadystatechange = function () { if (xhr.readyState === _this.state.done) { var responseText = xhr.responseText; try { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument resolve(_this.buildResponse(JSON.parse(responseText))); } catch (_a) { resolve(_this.buildResponse({ code: xhr.status })); } } }; var headers = { 'Content-Type': 'application/json', Accept: '*/*', }; var bodyString = JSON.stringify(payload); var shouldCompressBody = shouldCompressUploadBody && bodyString.length >= _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.MIN_GZIP_UPLOAD_BODY_SIZE_BYTES && (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.isCompressionStreamAvailable)(); var sendBody = function (body) { var e_1, _a; headers = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, _this.customHeaders), headers); try { for (var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(Object.entries(headers)), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_c.value, 2), key = _d[0], value = _d[1]; xhr.setRequestHeader(key, value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } xhr.send(body); }; var doSend = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(_this, void 0, void 0, function () { var compressed; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (!shouldCompressBody) return [3 /*break*/, 2]; return [4 /*yield*/, (0,_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.compressToGzipArrayBuffer)(bodyString)]; case 1: compressed = _a.sent(); if (compressed) { headers['Content-Encoding'] = 'gzip'; sendBody(compressed); } else { sendBody(bodyString); } return [3 /*break*/, 3]; case 2: sendBody(bodyString); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; doSend().catch(reject); })]; }); }); }; return XHRTransport; }(_amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.BaseTransport)); //# sourceMappingURL=xhr.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/types.js" /*!********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/types.js ***! \********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DEFAULT_ACTION_CLICK_ALLOWLIST: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_ACTION_CLICK_ALLOWLIST), /* harmony export */ DEFAULT_CSS_SELECTOR_ALLOWLIST: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_CSS_SELECTOR_ALLOWLIST), /* harmony export */ DEFAULT_DATA_ATTRIBUTE_PREFIX: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_DATA_ATTRIBUTE_PREFIX), /* harmony export */ EXCLUDE_INTERNAL_REFERRERS_CONDITIONS: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__.EXCLUDE_INTERNAL_REFERRERS_CONDITIONS), /* harmony export */ IdentifyOperation: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.IdentifyOperation), /* harmony export */ LogLevel: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.LogLevel), /* harmony export */ OfflineDisabled: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__.OfflineDisabled), /* harmony export */ RevenueProperty: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__.RevenueProperty), /* harmony export */ ServerZone: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__.ServerZone), /* harmony export */ SpecialEventType: () => (/* reexport safe */ _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__.SpecialEventType) /* harmony export */ }); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/revenue.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/loglevel.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/event/event.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/server-zone.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/offline.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/element-interactions.js"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/types/config/browser-config.js"); /* eslint-disable @typescript-eslint/unbound-method */ //# sourceMappingURL=types.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/utils/snippet-helper.js" /*!***********************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/utils/snippet-helper.js ***! \***********************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ convertProxyObjectToRealObject: () => (/* binding */ convertProxyObjectToRealObject), /* harmony export */ isInstanceProxy: () => (/* binding */ isInstanceProxy), /* harmony export */ runQueuedFunctions: () => (/* binding */ runQueuedFunctions) /* harmony export */ }); /** * Applies the proxied functions on the proxied amplitude snippet to an instance of the real object. * @ignore */ var runQueuedFunctions = function (instance, queue) { convertProxyObjectToRealObject(instance, queue); }; /** * Applies the proxied functions on the proxied object to an instance of the real object. * Used to convert proxied Identify and Revenue objects. */ var convertProxyObjectToRealObject = function (instance, queue) { for (var i = 0; i < queue.length; i++) { var _a = queue[i], name_1 = _a.name, args = _a.args, resolve = _a.resolve; var fn = instance && instance[name_1]; if (typeof fn === 'function') { var result = fn.apply(instance, args); if (typeof resolve === 'function') { resolve(result === null || result === void 0 ? void 0 : result.promise); } } } return instance; }; /** * Check if the param is snippet proxy */ var isInstanceProxy = function (instance) { var instanceProxy = instance; return instanceProxy && instanceProxy._q !== undefined; }; //# sourceMappingURL=snippet-helper.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/version.js" /*!**********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/version.js ***! \**********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ VERSION: () => (/* binding */ VERSION) /* harmony export */ }); var VERSION = '2.42.3'; //# sourceMappingURL=version.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-browser/lib/esm/video-capture/video-capture.js" /*!******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-browser/lib/esm/video-capture/video-capture.js ***! \******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ VideoCapture: () => (/* binding */ VideoCapture), /* harmony export */ trackVideo: () => (/* binding */ trackVideo) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @amplitude/analytics-core */ "./node_modules/@amplitude/analytics-core/lib/esm/observers/video.js"); var VideoCapture = /** @class */ (function () { function VideoCapture(amplitude) { this.amplitude = amplitude; this.videoEl = null; this.embeddedVideoPlayer = null; this.extraEventProperties = {}; this.listeners = []; this.onRemoveListeners = []; } /** * Specify a video element to capture events from * * @param videoEl - The HTML video element to capture events from. * @returns The VideoCapture instance. */ VideoCapture.prototype.withVideoElement = function (videoEl) { this.videoEl = videoEl; return this; }; /** * Specify an embedded video player.js instance to capture events from * @param player - The embedded video player.js instance to capture events from. * @returns The VideoCapture instance. */ VideoCapture.prototype.withEmbeddedPlayer = function (player) { this.embeddedVideoPlayer = player; return this; }; /** * Specify a vendor to capture extra vendor-specific event properties * * @param vendor - The vendor of the video player. Currently only "mux" is supported. * @returns The VideoCapture instance. */ VideoCapture.prototype.withVendor = function (vendor) { this.vendor = vendor; return this; }; /** * Specify extra event properties to include in all captured events * * @param properties - The extra event properties to include in the Amplitude event. * @returns The VideoCapture instance. */ VideoCapture.prototype.withExtraEventProperties = function (properties) { this.extraEventProperties = properties; return this; }; /** * Track a "Video Content Started" event every time the video starts playing * @returns The VideoCapture instance. */ VideoCapture.prototype.captureVideoStarted = function () { var _this = this; this.listeners.push(function (previousState, nextState) { if (previousState.playbackState !== 'playing' && nextState.playbackState === 'playing') { // placeholder for Heartbeat Start Event _this.amplitude.track('Video Content Started', (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, nextState.lastEvent), _this.extraEventProperties)); } }); return this; }; /** * Track a "Video Content Stopped" event every time the video stops playing * @returns The VideoCapture instance. */ VideoCapture.prototype.captureVideoStopped = function () { var _this = this; this.listeners.push(function (previousState, nextState) { if (previousState.playbackState === 'playing' && nextState.playbackState !== 'playing') { // placeholder for Heartbeat Stop Event _this.amplitude.track('Video Content Stopped', (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, nextState.lastEvent), { watch_duration: nextState.watchTime }), _this.extraEventProperties)); } }); return this; }; // Placeholder: may need a generic state change listener to capture unusual events or to have // more control over the event tracking. // withStateChangeListener(listener: (previousState: VideoState, nextState: VideoState) => void): VideoCapture { /** * Start capturing analytics events for the video element * @returns The VideoCapture instance. * @throws An error if the video element is not specified. */ VideoCapture.prototype.start = function () { var _this = this; var _a; var videoEl = (_a = this.videoEl) !== null && _a !== void 0 ? _a : this.embeddedVideoPlayer; if (!videoEl) { throw new Error('Video element not specified. Use withVideoElement() or withEmbeddedPlayer() to specify the video element.'); } if (this.videoEl && this.embeddedVideoPlayer) { throw new Error('Both video element and embedded video player specified. Use only one of withVideoElement() or withEmbeddedPlayer() to specify the video element.'); } var videoObserver = new _amplitude_analytics_core__WEBPACK_IMPORTED_MODULE_1__.VideoObserver({ videoEl: videoEl, onStateChange: function (previousState, nextState) { _this.listeners.forEach(function (listener) { return listener(previousState, nextState); }); }, vendor: this.vendor, isEmbedded: !!this.embeddedVideoPlayer, }); this.onRemoveListeners.push(function () { videoObserver.destroy(); }); return this; }; VideoCapture.prototype.stop = function () { this.onRemoveListeners.forEach(function (listener) { return listener(); }); this.onRemoveListeners = []; }; return VideoCapture; }()); /** * Track video analytics events for an HTML video element or embedded video player.js instance. * * Captures Video Started and Video Stopped events. * * @experimental This function is experimental and may not be stable. * @param amplitude - The Amplitude client instance. * @param videoEl - The HTML video element or embedded video player.js instance to capture events from. * @param options - The options for the video capture. * @returns A function to stop the video capture. */ function trackVideo(amplitude, videoEl, options) { var _a; if (options === void 0) { options = {}; } var videoCapture = new VideoCapture(amplitude); if (videoEl instanceof HTMLVideoElement) { videoCapture.withVideoElement(videoEl); } else { videoCapture.withEmbeddedPlayer(videoEl); } if (options.vendor) { videoCapture.withVendor(options.vendor); } videoCapture .withExtraEventProperties((_a = options.extraEventProperties) !== null && _a !== void 0 ? _a : {}) .captureVideoStarted() .captureVideoStopped() .start(); return function () { return videoCapture.stop(); }; } //# sourceMappingURL=video-capture.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-connector/dist/analytics-connector.esm.js" /*!*************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-connector/dist/analytics-connector.esm.js ***! \*************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AnalyticsConnector: () => (/* binding */ AnalyticsConnector) /* harmony export */ }); var ApplicationContextProviderImpl = /** @class */ (function () { function ApplicationContextProviderImpl() { } ApplicationContextProviderImpl.prototype.getApplicationContext = function () { return { versionName: this.versionName, language: getLanguage(), platform: 'Web', os: undefined, deviceModel: undefined, }; }; return ApplicationContextProviderImpl; }()); var getLanguage = function () { return ((typeof navigator !== 'undefined' && ((navigator.languages && navigator.languages[0]) || navigator.language)) || ''); }; var EventBridgeImpl = /** @class */ (function () { function EventBridgeImpl() { this.queue = []; } EventBridgeImpl.prototype.logEvent = function (event) { if (!this.receiver) { if (this.queue.length < 512) { this.queue.push(event); } } else { this.receiver(event); } }; EventBridgeImpl.prototype.setEventReceiver = function (receiver) { this.receiver = receiver; if (this.queue.length > 0) { this.queue.forEach(function (event) { receiver(event); }); this.queue = []; } }; return EventBridgeImpl; }()); /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any var isEqual = function (obj1, obj2) { var e_1, _a; var primitive = ['string', 'number', 'boolean', 'undefined']; var typeA = typeof obj1; var typeB = typeof obj2; if (typeA !== typeB) { return false; } try { for (var primitive_1 = __values(primitive), primitive_1_1 = primitive_1.next(); !primitive_1_1.done; primitive_1_1 = primitive_1.next()) { var p = primitive_1_1.value; if (p === typeA) { return obj1 === obj2; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (primitive_1_1 && !primitive_1_1.done && (_a = primitive_1.return)) _a.call(primitive_1); } finally { if (e_1) throw e_1.error; } } // check null if (obj1 == null && obj2 == null) { return true; } else if (obj1 == null || obj2 == null) { return false; } // if got here - objects if (obj1.length !== obj2.length) { return false; } //check if arrays var isArrayA = Array.isArray(obj1); var isArrayB = Array.isArray(obj2); if (isArrayA !== isArrayB) { return false; } if (isArrayA && isArrayB) { //arrays for (var i = 0; i < obj1.length; i++) { if (!isEqual(obj1[i], obj2[i])) { return false; } } } else { //objects var sorted1 = Object.keys(obj1).sort(); var sorted2 = Object.keys(obj2).sort(); if (!isEqual(sorted1, sorted2)) { return false; } //compare object values var result_1 = true; Object.keys(obj1).forEach(function (key) { if (!isEqual(obj1[key], obj2[key])) { result_1 = false; } }); return result_1; } return true; }; var ID_OP_SET = '$set'; var ID_OP_UNSET = '$unset'; var ID_OP_CLEAR_ALL = '$clearAll'; // Polyfill for Object.entries if (!Object.entries) { Object.entries = function (obj) { var ownProps = Object.keys(obj); var i = ownProps.length; var resArray = new Array(i); while (i--) { resArray[i] = [ownProps[i], obj[ownProps[i]]]; } return resArray; }; } var IdentityStoreImpl = /** @class */ (function () { function IdentityStoreImpl() { this.identity = { userProperties: {} }; this.listeners = new Set(); } IdentityStoreImpl.prototype.editIdentity = function () { // eslint-disable-next-line @typescript-eslint/no-this-alias var self = this; var actingUserProperties = __assign({}, this.identity.userProperties); var actingIdentity = __assign(__assign({}, this.identity), { userProperties: actingUserProperties }); return { setUserId: function (userId) { actingIdentity.userId = userId; return this; }, setDeviceId: function (deviceId) { actingIdentity.deviceId = deviceId; return this; }, setUserProperties: function (userProperties) { actingIdentity.userProperties = userProperties; return this; }, setOptOut: function (optOut) { actingIdentity.optOut = optOut; return this; }, updateUserProperties: function (actions) { var e_1, _a, e_2, _b, e_3, _c; var actingProperties = actingIdentity.userProperties || {}; try { for (var _d = __values(Object.entries(actions)), _e = _d.next(); !_e.done; _e = _d.next()) { var _f = __read(_e.value, 2), action = _f[0], properties = _f[1]; switch (action) { case ID_OP_SET: try { for (var _g = (e_2 = void 0, __values(Object.entries(properties))), _h = _g.next(); !_h.done; _h = _g.next()) { var _j = __read(_h.value, 2), key = _j[0], value = _j[1]; actingProperties[key] = value; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_h && !_h.done && (_b = _g.return)) _b.call(_g); } finally { if (e_2) throw e_2.error; } } break; case ID_OP_UNSET: try { for (var _k = (e_3 = void 0, __values(Object.keys(properties))), _l = _k.next(); !_l.done; _l = _k.next()) { var key = _l.value; delete actingProperties[key]; } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_l && !_l.done && (_c = _k.return)) _c.call(_k); } finally { if (e_3) throw e_3.error; } } break; case ID_OP_CLEAR_ALL: actingProperties = {}; break; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_e && !_e.done && (_a = _d.return)) _a.call(_d); } finally { if (e_1) throw e_1.error; } } actingIdentity.userProperties = actingProperties; return this; }, commit: function () { self.setIdentity(actingIdentity); return this; }, }; }; IdentityStoreImpl.prototype.getIdentity = function () { return __assign({}, this.identity); }; IdentityStoreImpl.prototype.setIdentity = function (identity) { var originalIdentity = __assign({}, this.identity); this.identity = __assign({}, identity); if (!isEqual(originalIdentity, this.identity)) { this.listeners.forEach(function (listener) { listener(identity); }); } }; IdentityStoreImpl.prototype.addIdentityListener = function (listener) { this.listeners.add(listener); }; IdentityStoreImpl.prototype.removeIdentityListener = function (listener) { this.listeners.delete(listener); }; return IdentityStoreImpl; }()); var safeGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : self; var AnalyticsConnector = /** @class */ (function () { function AnalyticsConnector() { this.identityStore = new IdentityStoreImpl(); this.eventBridge = new EventBridgeImpl(); this.applicationContextProvider = new ApplicationContextProviderImpl(); } AnalyticsConnector.getInstance = function (instanceName) { if (!safeGlobal['analyticsConnectorInstances']) { safeGlobal['analyticsConnectorInstances'] = {}; } if (!safeGlobal['analyticsConnectorInstances'][instanceName]) { safeGlobal['analyticsConnectorInstances'][instanceName] = new AnalyticsConnector(); } return safeGlobal['analyticsConnectorInstances'][instanceName]; }; return AnalyticsConnector; }()); /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/analytics-connector.js" /*!*******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/analytics-connector.js ***! \*******************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getAnalyticsConnector: () => (/* binding */ getAnalyticsConnector), /* harmony export */ setConnectorDeviceId: () => (/* binding */ setConnectorDeviceId), /* harmony export */ setConnectorUserId: () => (/* binding */ setConnectorUserId) /* harmony export */ }); /* harmony import */ var _amplitude_analytics_connector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @amplitude/analytics-connector */ "./node_modules/@amplitude/analytics-connector/dist/analytics-connector.esm.js"); /* harmony import */ var _types_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/constants */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); var getAnalyticsConnector = function (instanceName) { if (instanceName === void 0) { instanceName = _types_constants__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_INSTANCE_NAME; } return _amplitude_analytics_connector__WEBPACK_IMPORTED_MODULE_0__.AnalyticsConnector.getInstance(instanceName); }; var setConnectorUserId = function (userId, instanceName) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore getAnalyticsConnector(instanceName).identityStore.editIdentity().setUserId(userId).commit(); }; var setConnectorDeviceId = function (deviceId, instanceName) { getAnalyticsConnector(instanceName).identityStore.editIdentity().setDeviceId(deviceId).commit(); }; //# sourceMappingURL=analytics-connector.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/campaign/campaign-parser.js" /*!************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/campaign/campaign-parser.js ***! \************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ CampaignParser: () => (/* binding */ CampaignParser) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _query_params__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../query-params */ "./node_modules/@amplitude/analytics-core/lib/esm/query-params.js"); /* harmony import */ var _types_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/constants */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); var CampaignParser = /** @class */ (function () { function CampaignParser() { } CampaignParser.prototype.parse = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { return [2 /*return*/, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, _types_constants__WEBPACK_IMPORTED_MODULE_2__.BASE_CAMPAIGN), this.getUtmParam()), this.getReferrer()), this.getClickIds())]; }); }); }; CampaignParser.prototype.getUtmParam = function () { var params = (0,_query_params__WEBPACK_IMPORTED_MODULE_1__.getQueryParams)(); var utmCampaign = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_CAMPAIGN]; var utmContent = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_CONTENT]; var utmId = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_ID]; var utmMedium = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_MEDIUM]; var utmSource = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_SOURCE]; var utmTerm = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.UTM_TERM]; return { utm_campaign: utmCampaign, utm_content: utmContent, utm_id: utmId, utm_medium: utmMedium, utm_source: utmSource, utm_term: utmTerm, }; }; CampaignParser.prototype.getReferrer = function () { var _a, _b; var data = { referrer: undefined, referring_domain: undefined, }; try { data.referrer = document.referrer || undefined; data.referring_domain = (_b = (_a = data.referrer) === null || _a === void 0 ? void 0 : _a.split('/')[2]) !== null && _b !== void 0 ? _b : undefined; } catch (_c) { // nothing to track } return data; }; CampaignParser.prototype.getClickIds = function () { var _a; var params = (0,_query_params__WEBPACK_IMPORTED_MODULE_1__.getQueryParams)(); return _a = {}, _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.DCLID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.DCLID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.FBCLID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.FBCLID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.GBRAID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.GBRAID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.GCLID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.GCLID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.KO_CLICK_ID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.KO_CLICK_ID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.LI_FAT_ID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.LI_FAT_ID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.MSCLKID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.MSCLKID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.RDT_CID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.RDT_CID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.TTCLID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.TTCLID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.TWCLID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.TWCLID], _a[_types_constants__WEBPACK_IMPORTED_MODULE_2__.WBRAID] = params[_types_constants__WEBPACK_IMPORTED_MODULE_2__.WBRAID], _a; }; return CampaignParser; }()); //# sourceMappingURL=campaign-parser.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/config.js" /*!******************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/config.js ***! \******************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Config: () => (/* binding */ Config), /* harmony export */ RequestMetadata: () => (/* binding */ RequestMetadata), /* harmony export */ createServerConfig: () => (/* binding */ createServerConfig), /* harmony export */ getDefaultConfig: () => (/* binding */ getDefaultConfig), /* harmony export */ getServerUrl: () => (/* binding */ getServerUrl) /* harmony export */ }); /* harmony import */ var _types_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types/constants */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./node_modules/@amplitude/analytics-core/lib/esm/logger.js"); /* harmony import */ var _types_loglevel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./types/loglevel */ "./node_modules/@amplitude/analytics-core/lib/esm/types/loglevel.js"); var getDefaultConfig = function () { return ({ flushMaxRetries: 12, flushQueueSize: 200, flushIntervalMillis: 10000, instanceName: _types_constants__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_INSTANCE_NAME, logLevel: _types_loglevel__WEBPACK_IMPORTED_MODULE_2__.LogLevel.Warn, loggerProvider: new _logger__WEBPACK_IMPORTED_MODULE_1__.Logger(), offline: false, optOut: false, serverUrl: _types_constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_SERVER_URL, serverZone: 'US', useBatch: false, }); }; var Config = /** @class */ (function () { function Config(options) { var _a, _b, _c, _d; this._optOut = false; var defaultConfig = getDefaultConfig(); this.apiKey = options.apiKey; this.flushIntervalMillis = (_a = options.flushIntervalMillis) !== null && _a !== void 0 ? _a : defaultConfig.flushIntervalMillis; this.flushMaxRetries = options.flushMaxRetries || defaultConfig.flushMaxRetries; this.flushQueueSize = options.flushQueueSize || defaultConfig.flushQueueSize; this.instanceName = options.instanceName || defaultConfig.instanceName; this.loggerProvider = options.loggerProvider || defaultConfig.loggerProvider; this.logLevel = (_b = options.logLevel) !== null && _b !== void 0 ? _b : defaultConfig.logLevel; this.minIdLength = options.minIdLength; this.plan = options.plan; this.ingestionMetadata = options.ingestionMetadata; this.offline = options.offline !== undefined ? options.offline : defaultConfig.offline; this.optOut = (_c = options.optOut) !== null && _c !== void 0 ? _c : defaultConfig.optOut; this.serverUrl = options.serverUrl; this.serverZone = options.serverZone || defaultConfig.serverZone; this.storageProvider = options.storageProvider; this.transportProvider = options.transportProvider; this.useBatch = (_d = options.useBatch) !== null && _d !== void 0 ? _d : defaultConfig.useBatch; this.loggerProvider.enable(this.logLevel); var serverConfig = createServerConfig(options.serverUrl, options.serverZone, options.useBatch); this.serverZone = serverConfig.serverZone; this.serverUrl = serverConfig.serverUrl; } Object.defineProperty(Config.prototype, "optOut", { get: function () { return this._optOut; }, set: function (optOut) { this._optOut = optOut; }, enumerable: false, configurable: true }); return Config; }()); var getServerUrl = function (serverZone, useBatch) { if (serverZone === 'EU') { return useBatch ? _types_constants__WEBPACK_IMPORTED_MODULE_0__.EU_AMPLITUDE_BATCH_SERVER_URL : _types_constants__WEBPACK_IMPORTED_MODULE_0__.EU_AMPLITUDE_SERVER_URL; } return useBatch ? _types_constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_BATCH_SERVER_URL : _types_constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_SERVER_URL; }; var createServerConfig = function (serverUrl, serverZone, useBatch) { if (serverUrl === void 0) { serverUrl = ''; } if (serverZone === void 0) { serverZone = getDefaultConfig().serverZone; } if (useBatch === void 0) { useBatch = getDefaultConfig().useBatch; } if (serverUrl) { return { serverUrl: serverUrl, serverZone: undefined }; } var _serverZone = ['US', 'EU'].includes(serverZone) ? serverZone : getDefaultConfig().serverZone; return { serverZone: _serverZone, serverUrl: getServerUrl(_serverZone, useBatch), }; }; var RequestMetadata = /** @class */ (function () { function RequestMetadata() { this.sdk = { metrics: { histogram: {}, }, }; } RequestMetadata.prototype.recordHistogram = function (key, value) { this.sdk.metrics.histogram[key] = value; }; return RequestMetadata; }()); var HistogramOptions = /** @class */ (function () { function HistogramOptions() { } return HistogramOptions; }()); //# sourceMappingURL=config.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/cookie-name.js" /*!***********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/cookie-name.js ***! \***********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getCookieName: () => (/* binding */ getCookieName), /* harmony export */ getOldCookieName: () => (/* binding */ getOldCookieName) /* harmony export */ }); /* harmony import */ var _types_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types/constants */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); var getCookieName = function (apiKey, postKey, limit) { if (postKey === void 0) { postKey = ''; } if (limit === void 0) { limit = 10; } return [_types_constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_PREFIX, postKey, apiKey.substring(0, limit)].filter(Boolean).join('_'); }; var getOldCookieName = function (apiKey) { return "".concat(_types_constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_PREFIX.toLowerCase(), "_").concat(apiKey.substring(0, 6)); }; //# sourceMappingURL=cookie-name.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/core-client.js" /*!***********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/core-client.js ***! \***********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AmplitudeCore: () => (/* binding */ AmplitudeCore) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _types_event_event__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/event/event */ "./node_modules/@amplitude/analytics-core/lib/esm/types/event/event.js"); /* harmony import */ var _identify__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./identify */ "./node_modules/@amplitude/analytics-core/lib/esm/identify.js"); /* harmony import */ var _types_messages__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./types/messages */ "./node_modules/@amplitude/analytics-core/lib/esm/types/messages.js"); /* harmony import */ var _timeline__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timeline */ "./node_modules/@amplitude/analytics-core/lib/esm/timeline.js"); /* harmony import */ var _utils_event_builder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/event-builder */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/event-builder.js"); /* harmony import */ var _utils_result_builder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/result-builder */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/result-builder.js"); /* harmony import */ var _utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/return-wrapper */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/return-wrapper.js"); var AmplitudeCore = /** @class */ (function () { function AmplitudeCore(name) { if (name === void 0) { name = '$default'; } this.initializing = false; this.isReady = false; this.q = []; this.dispatchQ = []; this.logEvent = this.track.bind(this); this.timeline = new _timeline__WEBPACK_IMPORTED_MODULE_4__.Timeline(this); this.name = name; } AmplitudeCore.prototype._init = function (config) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: this.config = config; this.timeline.reset(this); this.timeline.loggerProvider = this.config.loggerProvider; return [4 /*yield*/, this.runQueuedFunctions('q')]; case 1: _a.sent(); this.isReady = true; return [2 /*return*/]; } }); }); }; AmplitudeCore.prototype.runQueuedFunctions = function (queueName) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var queuedFunctions, queuedFunctions_1, queuedFunctions_1_1, queuedFunction, val, e_1_1; var e_1, _a; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: queuedFunctions = this[queueName]; this[queueName] = []; _b.label = 1; case 1: _b.trys.push([1, 8, 9, 10]); queuedFunctions_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(queuedFunctions), queuedFunctions_1_1 = queuedFunctions_1.next(); _b.label = 2; case 2: if (!!queuedFunctions_1_1.done) return [3 /*break*/, 7]; queuedFunction = queuedFunctions_1_1.value; val = queuedFunction(); if (!(val && 'promise' in val)) return [3 /*break*/, 4]; return [4 /*yield*/, val.promise]; case 3: _b.sent(); return [3 /*break*/, 6]; case 4: return [4 /*yield*/, val]; case 5: _b.sent(); _b.label = 6; case 6: queuedFunctions_1_1 = queuedFunctions_1.next(); return [3 /*break*/, 2]; case 7: return [3 /*break*/, 10]; case 8: e_1_1 = _b.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 10]; case 9: try { if (queuedFunctions_1_1 && !queuedFunctions_1_1.done && (_a = queuedFunctions_1.return)) _a.call(queuedFunctions_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 10: if (!this[queueName].length) return [3 /*break*/, 12]; return [4 /*yield*/, this.runQueuedFunctions(queueName)]; case 11: _b.sent(); _b.label = 12; case 12: return [2 /*return*/]; } }); }); }; AmplitudeCore.prototype.track = function (eventInput, eventProperties, eventOptions) { var event = (0,_utils_event_builder__WEBPACK_IMPORTED_MODULE_5__.createTrackEvent)(eventInput, eventProperties, eventOptions); // Update client user properties immediately and synchronously this.userProperties = this.getOperationAppliedUserProperties(event.user_properties); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.dispatch(event)); }; AmplitudeCore.prototype.identify = function (identify, eventOptions) { var event = (0,_utils_event_builder__WEBPACK_IMPORTED_MODULE_5__.createIdentifyEvent)(identify, eventOptions); // Update client user properties immediately and synchronously this.userProperties = this.getOperationAppliedUserProperties(event.user_properties); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.dispatch(event)); }; AmplitudeCore.prototype.groupIdentify = function (groupType, groupName, identify, eventOptions) { var event = (0,_utils_event_builder__WEBPACK_IMPORTED_MODULE_5__.createGroupIdentifyEvent)(groupType, groupName, identify, eventOptions); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.dispatch(event)); }; AmplitudeCore.prototype.setGroup = function (groupType, groupName, eventOptions) { var event = (0,_utils_event_builder__WEBPACK_IMPORTED_MODULE_5__.createGroupEvent)(groupType, groupName, eventOptions); // Update client user properties immediately and synchronously this.userProperties = this.getOperationAppliedUserProperties(event.user_properties); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.dispatch(event)); }; AmplitudeCore.prototype.revenue = function (revenue, eventOptions) { var event = (0,_utils_event_builder__WEBPACK_IMPORTED_MODULE_5__.createRevenueEvent)(revenue, eventOptions); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.dispatch(event)); }; AmplitudeCore.prototype.add = function (plugin) { if (!this.isReady) { this.q.push(this._addPlugin.bind(this, plugin)); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(); } return this._addPlugin(plugin); }; AmplitudeCore.prototype._addPlugin = function (plugin) { return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.timeline.register(plugin, this.config)); }; AmplitudeCore.prototype.remove = function (pluginName) { if (!this.isReady) { this.q.push(this._removePlugin.bind(this, pluginName)); return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(); } return this._removePlugin(pluginName); }; AmplitudeCore.prototype._removePlugin = function (pluginName) { return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.timeline.deregister(pluginName, this.config)); }; AmplitudeCore.prototype.dispatchWithCallback = function (event, callback) { if (!this.isReady) { return callback((0,_utils_result_builder__WEBPACK_IMPORTED_MODULE_6__.buildResult)(event, 0, _types_messages__WEBPACK_IMPORTED_MODULE_3__.CLIENT_NOT_INITIALIZED)); } void this.process(event).then(callback); }; AmplitudeCore.prototype.dispatch = function (event) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { if (!this.isReady) { return [2 /*return*/, new Promise(function (resolve) { _this.dispatchQ.push(_this.dispatchWithCallback.bind(_this, event, resolve)); })]; } return [2 /*return*/, this.process(event)]; }); }); }; /** * * This method applies identify operations to user properties and * returns a single object representing the final user property state. * * This is a best-effort api that only supports $set, $clearAll, and $unset. * Other operations are not supported and are ignored. * * Operations are applied on top of current client state (this.userProperties). * * @param userProperties The new user properties object from identify() or setIdentity(). * @returns A key-value object user properties without operations. * * @example * Input: * { * $set: { plan: 'premium' }, * custom_flag: true * } * * Output: * { * plan: 'premium', * custom_flag: true * } */ AmplitudeCore.prototype.getOperationAppliedUserProperties = function (userProperties) { var _a; var base = (_a = this.userProperties) !== null && _a !== void 0 ? _a : {}; var updatedProperties = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, base); if (userProperties === undefined) { return updatedProperties; } // Keep non-operation keys for later merge var nonOpProperties = {}; Object.keys(userProperties).forEach(function (key) { if (!Object.values(_types_event_event__WEBPACK_IMPORTED_MODULE_1__.IdentifyOperation).includes(key)) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment nonOpProperties[key] = userProperties[key]; } }); _identify__WEBPACK_IMPORTED_MODULE_2__.OrderedIdentifyOperations.forEach(function (operation) { // Skip when key is an operation. if (!Object.keys(userProperties).includes(operation)) return; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment var opProperties = userProperties[operation]; switch (operation) { case _types_event_event__WEBPACK_IMPORTED_MODULE_1__.IdentifyOperation.CLEAR_ALL: // Due to operation order, the following line will never execute. /* istanbul ignore next */ Object.keys(updatedProperties).forEach(function (prop) { delete updatedProperties[prop]; }); break; case _types_event_event__WEBPACK_IMPORTED_MODULE_1__.IdentifyOperation.UNSET: Object.keys(opProperties).forEach(function (prop) { delete updatedProperties[prop]; }); break; case _types_event_event__WEBPACK_IMPORTED_MODULE_1__.IdentifyOperation.SET: Object.assign(updatedProperties, opProperties); break; } }); // Merge non-operation properties. // Custom properties should not be affected by operations. // https://github.com/amplitude/nova/blob/343f678ded83c032e83b189796b3c2be161b48f5/src/main/java/com/amplitude/userproperty/model/ModifyUserPropertiesIdent.java#L79-L83 Object.assign(updatedProperties, nonOpProperties); return updatedProperties; }; AmplitudeCore.prototype.process = function (event) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var result, e_2, message, result; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); // skip event processing if opt out if (this.config.optOut) { return [2 /*return*/, (0,_utils_result_builder__WEBPACK_IMPORTED_MODULE_6__.buildResult)(event, 0, _types_messages__WEBPACK_IMPORTED_MODULE_3__.OPT_OUT_MESSAGE)]; } if (event.event_type === _types_event_event__WEBPACK_IMPORTED_MODULE_1__.SpecialEventType.IDENTIFY) { // Do not update this.userProperties here. // It is only set synchronously in identify() or setIdentity() this.timeline.onIdentityChanged({ userProperties: this.userProperties }); } return [4 /*yield*/, this.timeline.push(event)]; case 1: result = _a.sent(); result.code === 200 ? this.config.loggerProvider.log(result.message) : result.code === 100 ? this.config.loggerProvider.warn(result.message) : this.config.loggerProvider.error(result.message); return [2 /*return*/, result]; case 2: e_2 = _a.sent(); message = String(e_2); this.config.loggerProvider.error(message); result = (0,_utils_result_builder__WEBPACK_IMPORTED_MODULE_6__.buildResult)(event, 0, message); return [2 /*return*/, result]; case 3: return [2 /*return*/]; } }); }); }; AmplitudeCore.prototype.setOptOut = function (optOut) { if (!this.isReady) { this.q.push(this._setOptOut.bind(this, Boolean(optOut))); return; } this._setOptOut(optOut); }; AmplitudeCore.prototype._setOptOut = function (optOut) { if (this.config.optOut !== optOut) { this.config.optOut = Boolean(optOut); this.timeline.onOptOutChanged(optOut); } }; AmplitudeCore.prototype.flush = function () { return (0,_utils_return_wrapper__WEBPACK_IMPORTED_MODULE_7__.returnWrapper)(this.timeline.flush()); }; AmplitudeCore.prototype.plugin = function (name) { var plugin = this.timeline.plugins.find(function (plugin) { return plugin.name === name; }); if (plugin === undefined) { this.config.loggerProvider.debug("Cannot find plugin with name ".concat(name)); return undefined; } return plugin; }; AmplitudeCore.prototype.plugins = function (pluginClass) { return this.timeline.plugins.filter(function (plugin) { return plugin instanceof pluginClass; }); }; return AmplitudeCore; }()); //# sourceMappingURL=core-client.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-client.js" /*!******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-client.js ***! \******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DIAGNOSTICS_EU_SERVER_URL: () => (/* binding */ DIAGNOSTICS_EU_SERVER_URL), /* harmony export */ DIAGNOSTICS_US_SERVER_URL: () => (/* binding */ DIAGNOSTICS_US_SERVER_URL), /* harmony export */ DiagnosticsClient: () => (/* binding */ DiagnosticsClient), /* harmony export */ FLUSH_INTERVAL_MS: () => (/* binding */ FLUSH_INTERVAL_MS), /* harmony export */ MAX_MEMORY_STORAGE_COUNT: () => (/* binding */ MAX_MEMORY_STORAGE_COUNT), /* harmony export */ MAX_MEMORY_STORAGE_EVENTS_COUNT: () => (/* binding */ MAX_MEMORY_STORAGE_EVENTS_COUNT), /* harmony export */ SAVE_INTERVAL_MS: () => (/* binding */ SAVE_INTERVAL_MS) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _diagnostics_storage__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./diagnostics-storage */ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-storage.js"); /* harmony import */ var _global_scope__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../global-scope */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _utils_sampling__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/sampling */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/sampling.js"); /* harmony import */ var _uncaught_sdk_errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./uncaught-sdk-errors */ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/uncaught-sdk-errors.js"); var SAVE_INTERVAL_MS = 1000; // 1 second var FLUSH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes var DIAGNOSTICS_US_SERVER_URL = 'https://diagnostics.prod.us-west-2.amplitude.com/v1/capture'; var DIAGNOSTICS_EU_SERVER_URL = 'https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture'; // In-memory storage limits var MAX_MEMORY_STORAGE_COUNT = 10000; // for tags, counters, histograms separately var MAX_MEMORY_STORAGE_EVENTS_COUNT = 10; var DiagnosticsClient = /** @class */ (function () { function DiagnosticsClient(apiKey, logger, serverZone, options) { if (serverZone === void 0) { serverZone = 'US'; } // In-memory storages this.inMemoryTags = {}; this.inMemoryCounters = {}; this.inMemoryHistograms = {}; this.inMemoryEvents = []; // Timer for 1-second persistence this.saveTimer = null; // Timer for flush interval this.flushTimer = null; this.apiKey = apiKey; this.logger = logger; this.serverUrl = serverZone === 'US' ? DIAGNOSTICS_US_SERVER_URL : DIAGNOSTICS_EU_SERVER_URL; this.logger.debug('DiagnosticsClient: Initializing with options', JSON.stringify(options, null, 2)); // Diagnostics is enabled by default with sample rate of 0 (no sampling) this.config = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ enabled: true, sampleRate: 0 }, options); this.startTimestamp = Date.now(); this.shouldTrack = (0,_utils_sampling__WEBPACK_IMPORTED_MODULE_3__.isTimestampInSampleTemp)(this.startTimestamp, this.config.sampleRate) && this.config.enabled; if (_diagnostics_storage__WEBPACK_IMPORTED_MODULE_1__.DiagnosticsStorage.isSupported()) { this.storage = new _diagnostics_storage__WEBPACK_IMPORTED_MODULE_1__.DiagnosticsStorage(apiKey, logger); } else { this.logger.debug('DiagnosticsClient: IndexedDB is not supported'); } void this.initializeFlushInterval(); // Track internal diagnostics metrics for sampling if (this.shouldTrack) { this.increment('sdk.diagnostics.sampled.in.and.enabled'); (0,_uncaught_sdk_errors__WEBPACK_IMPORTED_MODULE_4__.enableSdkErrorListeners)(this); } } /** * Check if storage is available and tracking is enabled */ DiagnosticsClient.prototype.isStorageAndTrackEnabled = function () { return Boolean(this.storage) && Boolean(this.shouldTrack); }; DiagnosticsClient.prototype.setTag = function (name, value) { if (!this.isStorageAndTrackEnabled()) { return; } if (Object.keys(this.inMemoryTags).length >= MAX_MEMORY_STORAGE_COUNT) { this.logger.debug('DiagnosticsClient: Early return setTags as reaching memory limit'); return; } this.inMemoryTags[name] = value; this.startTimersIfNeeded(); }; DiagnosticsClient.prototype.increment = function (name, size) { if (size === void 0) { size = 1; } if (!this.isStorageAndTrackEnabled()) { return; } if (Object.keys(this.inMemoryCounters).length >= MAX_MEMORY_STORAGE_COUNT) { this.logger.debug('DiagnosticsClient: Early return increment as reaching memory limit'); return; } this.inMemoryCounters[name] = (this.inMemoryCounters[name] || 0) + size; this.startTimersIfNeeded(); }; DiagnosticsClient.prototype.recordHistogram = function (name, value) { if (!this.isStorageAndTrackEnabled()) { return; } if (Object.keys(this.inMemoryHistograms).length >= MAX_MEMORY_STORAGE_COUNT) { this.logger.debug('DiagnosticsClient: Early return recordHistogram as reaching memory limit'); return; } var existing = this.inMemoryHistograms[name]; if (existing) { // Update existing stats incrementally existing.count += 1; existing.min = Math.min(existing.min, value); existing.max = Math.max(existing.max, value); existing.sum += value; } else { // Create new stats this.inMemoryHistograms[name] = { count: 1, min: value, max: value, sum: value, }; } this.startTimersIfNeeded(); }; DiagnosticsClient.prototype.recordEvent = function (name, properties) { if (!this.isStorageAndTrackEnabled()) { return; } if (this.inMemoryEvents.length >= MAX_MEMORY_STORAGE_EVENTS_COUNT) { this.logger.debug('DiagnosticsClient: Early return recordEvent as reaching memory limit'); return; } this.inMemoryEvents.push({ event_name: name, time: Date.now(), event_properties: properties, }); this.startTimersIfNeeded(); }; DiagnosticsClient.prototype.startTimersIfNeeded = function () { var _this = this; if (!this.saveTimer) { this.saveTimer = setTimeout(function () { _this.saveAllDataToStorage() .catch(function (error) { _this.logger.debug('DiagnosticsClient: Failed to save all data to storage', error); }) .finally(function () { _this.saveTimer = null; }); }, SAVE_INTERVAL_MS); } if (!this.flushTimer) { this.flushTimer = setTimeout(function () { _this._flush() .catch(function (error) { _this.logger.debug('DiagnosticsClient: Failed to flush', error); }) .finally(function () { _this.flushTimer = null; }); }, FLUSH_INTERVAL_MS); } }; DiagnosticsClient.prototype.saveAllDataToStorage = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var tagsToSave, countersToSave, histogramsToSave, eventsToSave; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (!this.storage) { return [2 /*return*/]; } tagsToSave = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, this.inMemoryTags); countersToSave = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, this.inMemoryCounters); histogramsToSave = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, this.inMemoryHistograms); eventsToSave = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(this.inMemoryEvents), false); this.inMemoryEvents = []; this.inMemoryTags = {}; this.inMemoryCounters = {}; this.inMemoryHistograms = {}; return [4 /*yield*/, Promise.all([ this.storage.setTags(tagsToSave), this.storage.incrementCounters(countersToSave), this.storage.setHistogramStats(histogramsToSave), this.storage.addEventRecords(eventsToSave), ])]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; DiagnosticsClient.prototype._flush = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var _a, tagRecords, counterRecords, histogramStatsRecords, eventRecords, tags, counters, histogram, events, payload; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: if (!this.storage) { return [2 /*return*/]; } return [4 /*yield*/, this.saveAllDataToStorage()]; case 1: _b.sent(); this.saveTimer = null; this.flushTimer = null; return [4 /*yield*/, this.storage.getAllAndClear()]; case 2: _a = _b.sent(), tagRecords = _a.tags, counterRecords = _a.counters, histogramStatsRecords = _a.histogramStats, eventRecords = _a.events; // Update the last flush timestamp void this.storage.setLastFlushTimestamp(Date.now()); tags = {}; tagRecords.forEach(function (record) { tags[record.key] = record.value; }); counters = {}; counterRecords.forEach(function (record) { counters[record.key] = record.value; }); histogram = {}; histogramStatsRecords.forEach(function (stats) { histogram[stats.key] = { count: stats.count, min: stats.min, max: stats.max, avg: Math.round((stats.sum / stats.count) * 100) / 100, // round the average to 2 decimal places. }; }); events = eventRecords.map(function (record) { return ({ event_name: record.event_name, time: record.time, event_properties: record.event_properties, }); }); // Early return if all data collections are empty if (Object.keys(counters).length === 0 && Object.keys(histogram).length === 0 && events.length === 0) { return [2 /*return*/]; } payload = { tags: tags, histogram: histogram, counters: counters, events: events, }; // Send payload to diagnostics server void this.fetch(payload); return [2 /*return*/]; } }); }); }; /** * Send diagnostics data to the server */ DiagnosticsClient.prototype.fetch = function (payload) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var response, error_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!(0,_global_scope__WEBPACK_IMPORTED_MODULE_2__.getGlobalScope)()) { throw new Error('DiagnosticsClient: Fetch is not supported'); } return [4 /*yield*/, fetch(this.serverUrl, { method: 'POST', headers: { 'X-ApiKey': this.apiKey, 'Content-Type': 'application/json', }, body: JSON.stringify(payload), })]; case 1: response = _a.sent(); if (!response.ok) { this.logger.debug('DiagnosticsClient: Failed to send diagnostics data.'); return [2 /*return*/]; } this.logger.debug('DiagnosticsClient: Successfully sent diagnostics data'); return [3 /*break*/, 3]; case 2: error_1 = _a.sent(); this.logger.debug('DiagnosticsClient: Failed to send diagnostics data. ', error_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; /** * Initialize flush interval logic. * Check if 5 minutes has passed since last flush, if so flush immediately. * Otherwise set a timer to flush when the interval is reached. */ DiagnosticsClient.prototype.initializeFlushInterval = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var now, lastFlushTimestamp, timeSinceLastFlush; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: if (!this.storage) { return [2 /*return*/]; } now = Date.now(); return [4 /*yield*/, this.storage.getLastFlushTimestamp()]; case 1: lastFlushTimestamp = (_a.sent()) || -1; // If last flush timestamp is -1, it means this is a new client // Save current timestamp as the initial "last flush timestamp" // and schedule the flush timer if (lastFlushTimestamp === -1) { void this.storage.setLastFlushTimestamp(now); this._setFlushTimer(FLUSH_INTERVAL_MS); return [2 /*return*/]; } timeSinceLastFlush = now - lastFlushTimestamp; if (timeSinceLastFlush >= FLUSH_INTERVAL_MS) { // More than 5 minutes has passed, flush immediately void this._flush(); return [2 /*return*/]; } else { // Set timer for remaining time this._setFlushTimer(FLUSH_INTERVAL_MS - timeSinceLastFlush); } return [2 /*return*/]; } }); }); }; /** * Helper method to set flush timer with consistent error handling */ DiagnosticsClient.prototype._setFlushTimer = function (delay) { var _this = this; this.flushTimer = setTimeout(function () { _this._flush() .catch(function (error) { _this.logger.debug('DiagnosticsClient: Failed to flush', error); }) .finally(function () { _this.flushTimer = null; }); }, delay); }; DiagnosticsClient.prototype._setSampleRate = function (sampleRate) { this.logger.debug('DiagnosticsClient: Setting sample rate to', sampleRate); this.config.sampleRate = sampleRate; this.shouldTrack = (0,_utils_sampling__WEBPACK_IMPORTED_MODULE_3__.isTimestampInSampleTemp)(this.startTimestamp, this.config.sampleRate) && this.config.enabled; this.logger.debug('DiagnosticsClient: Should track is', this.shouldTrack); }; return DiagnosticsClient; }()); //# sourceMappingURL=diagnostics-client.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-storage.js" /*!*******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/diagnostics-storage.js ***! \*******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ DiagnosticsStorage: () => (/* binding */ DiagnosticsStorage), /* harmony export */ INTERNAL_KEYS: () => (/* binding */ INTERNAL_KEYS), /* harmony export */ TABLE_NAMES: () => (/* binding */ TABLE_NAMES) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _global_scope__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../global-scope */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); var MAX_PERSISTENT_STORAGE_EVENTS_COUNT = 10; // Database configuration var DB_VERSION = 1; // Table names for different diagnostics types var TABLE_NAMES = { TAGS: 'tags', COUNTERS: 'counters', HISTOGRAMS: 'histograms', EVENTS: 'events', INTERNAL: 'internal', // New table for internal storage like flush timestamps }; // Keys for internal storage table var INTERNAL_KEYS = { LAST_FLUSH_TIMESTAMP: 'last_flush_timestamp', }; /** * Purpose-specific IndexedDB storage for diagnostics data * Provides optimized methods for each type of diagnostics data */ var DiagnosticsStorage = /** @class */ (function () { function DiagnosticsStorage(apiKey, logger) { this.dbPromise = null; this.logger = logger; this.dbName = "AMP_diagnostics_".concat(apiKey.substring(0, 10)); } /** * Check if IndexedDB is supported in the current environment * @returns true if IndexedDB is available, false otherwise */ DiagnosticsStorage.isSupported = function () { var _a; return ((_a = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)()) === null || _a === void 0 ? void 0 : _a.indexedDB) !== undefined; }; DiagnosticsStorage.prototype.getDB = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { if (!this.dbPromise) { this.dbPromise = this.openDB(); } return [2 /*return*/, this.dbPromise]; }); }); }; DiagnosticsStorage.prototype.openDB = function () { var _this = this; return new Promise(function (resolve, reject) { var request = indexedDB.open(_this.dbName, DB_VERSION); request.onerror = function () { // Clear dbPromise when it rejects for the first time _this.dbPromise = null; reject(new Error('Failed to open IndexedDB')); }; request.onsuccess = function () { var db = request.result; // Clear dbPromise when connection was on but went off later db.onclose = function () { _this.dbPromise = null; _this.logger.debug('DiagnosticsStorage: DB connection closed.'); }; db.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: A global database error occurred.', event); db.close(); }; resolve(db); }; request.onupgradeneeded = function (event) { var db = event.target.result; _this.createTables(db); }; }); }; DiagnosticsStorage.prototype.createTables = function (db) { // Create tags table if (!db.objectStoreNames.contains(TABLE_NAMES.TAGS)) { db.createObjectStore(TABLE_NAMES.TAGS, { keyPath: 'key' }); } // Create counters table if (!db.objectStoreNames.contains(TABLE_NAMES.COUNTERS)) { db.createObjectStore(TABLE_NAMES.COUNTERS, { keyPath: 'key' }); } // Create histograms table for storing histogram stats (count, min, max, sum) if (!db.objectStoreNames.contains(TABLE_NAMES.HISTOGRAMS)) { db.createObjectStore(TABLE_NAMES.HISTOGRAMS, { keyPath: 'key', }); } // Create events table if (!db.objectStoreNames.contains(TABLE_NAMES.EVENTS)) { var eventsStore = db.createObjectStore(TABLE_NAMES.EVENTS, { keyPath: 'id', autoIncrement: true, }); // Create index on time for chronological queries eventsStore.createIndex('time_idx', 'time', { unique: false }); } // Create internal table for storing internal data like flush timestamps if (!db.objectStoreNames.contains(TABLE_NAMES.INTERNAL)) { db.createObjectStore(TABLE_NAMES.INTERNAL, { keyPath: 'key' }); } }; DiagnosticsStorage.prototype.setTags = function (tags) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_1, store_1, error_1; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (Object.entries(tags).length === 0) { return [2 /*return*/]; } return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_1 = db.transaction([TABLE_NAMES.TAGS], 'readwrite'); store_1 = transaction_1.objectStore(TABLE_NAMES.TAGS); return [2 /*return*/, new Promise(function (resolve) { var entries = Object.entries(tags); transaction_1.oncomplete = function () { resolve(); }; transaction_1.onabort = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to set tags', event); resolve(); }; entries.forEach(function (_a) { var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_a, 2), key = _b[0], value = _b[1]; var putRequest = store_1.put({ key: key, value: value }); putRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to set tag', key, value, event); }; }); })]; case 2: error_1 = _a.sent(); this.logger.debug('DiagnosticsStorage: Failed to set tags', error_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.incrementCounters = function (counters) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_2, store_2, error_2; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (Object.entries(counters).length === 0) { return [2 /*return*/]; } return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_2 = db.transaction([TABLE_NAMES.COUNTERS], 'readwrite'); store_2 = transaction_2.objectStore(TABLE_NAMES.COUNTERS); return [2 /*return*/, new Promise(function (resolve) { var entries = Object.entries(counters); transaction_2.oncomplete = function () { resolve(); }; transaction_2.onabort = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to increment counters', event); resolve(); }; // Read existing values and update them entries.forEach(function (_a) { var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_a, 2), key = _b[0], incrementValue = _b[1]; var getRequest = store_2.get(key); getRequest.onsuccess = function () { var existingRecord = getRequest.result; /* istanbul ignore next */ var existingValue = existingRecord ? existingRecord.value : 0; var putRequest = store_2.put({ key: key, value: existingValue + incrementValue }); putRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to update counter', key, event); }; }; getRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to read existing counter', key, event); }; }); })]; case 2: error_2 = _a.sent(); this.logger.debug('DiagnosticsStorage: Failed to increment counters', error_2); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.setHistogramStats = function (histogramStats) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_3, store_3, error_3; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (Object.entries(histogramStats).length === 0) { return [2 /*return*/]; } return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_3 = db.transaction([TABLE_NAMES.HISTOGRAMS], 'readwrite'); store_3 = transaction_3.objectStore(TABLE_NAMES.HISTOGRAMS); return [2 /*return*/, new Promise(function (resolve) { var entries = Object.entries(histogramStats); transaction_3.oncomplete = function () { resolve(); }; transaction_3.onabort = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to set histogram stats', event); resolve(); }; // Read existing values and update them entries.forEach(function (_a) { var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(_a, 2), key = _b[0], newStats = _b[1]; var getRequest = store_3.get(key); getRequest.onsuccess = function () { var existingRecord = getRequest.result; var updatedStats; /* istanbul ignore next */ if (existingRecord) { // Accumulate with existing stats updatedStats = { key: key, count: existingRecord.count + newStats.count, min: Math.min(existingRecord.min, newStats.min), max: Math.max(existingRecord.max, newStats.max), sum: existingRecord.sum + newStats.sum, }; } else { // Create new stats updatedStats = { key: key, count: newStats.count, min: newStats.min, max: newStats.max, sum: newStats.sum, }; } var putRequest = store_3.put(updatedStats); putRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to set histogram stats', key, event); }; }; getRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to read existing histogram stats', key, event); }; }); })]; case 2: error_3 = _a.sent(); this.logger.debug('DiagnosticsStorage: Failed to set histogram stats', error_3); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.addEventRecords = function (events) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_4, store_4, error_4; var _this = this; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (events.length === 0) { return [2 /*return*/]; } return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_4 = db.transaction([TABLE_NAMES.EVENTS], 'readwrite'); store_4 = transaction_4.objectStore(TABLE_NAMES.EVENTS); return [2 /*return*/, new Promise(function (resolve) { transaction_4.oncomplete = function () { resolve(); }; /* istanbul ignore next */ transaction_4.onabort = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to add event records', event); resolve(); }; // First, check how many events are currently stored var countRequest = store_4.count(); countRequest.onsuccess = function () { var currentCount = countRequest.result; // Calculate how many events we can add var availableSlots = Math.max(0, MAX_PERSISTENT_STORAGE_EVENTS_COUNT - currentCount); if (availableSlots < events.length) { _this.logger.debug("DiagnosticsStorage: Only added ".concat(availableSlots, " of ").concat(events.length, " events due to storage limit")); } // Only add events up to the available slots (take the least recent ones) events.slice(0, availableSlots).forEach(function (event) { var request = store_4.add(event); request.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to add event record', event); }; }); }; countRequest.onerror = function (event) { _this.logger.debug('DiagnosticsStorage: Failed to count existing events', event); }; })]; case 2: error_4 = _a.sent(); this.logger.debug('DiagnosticsStorage: Failed to add event records', error_4); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.setInternal = function (key, value) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_5, store_5, error_5; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_5 = db.transaction([TABLE_NAMES.INTERNAL], 'readwrite'); store_5 = transaction_5.objectStore(TABLE_NAMES.INTERNAL); return [2 /*return*/, new Promise(function (resolve, reject) { /* istanbul ignore next */ transaction_5.onabort = function () { return reject(new Error('Failed to set internal value')); }; var request = store_5.put({ key: key, value: value }); request.onsuccess = function () { return resolve(); }; /* istanbul ignore next */ request.onerror = function () { return reject(new Error('Failed to set internal value')); }; })]; case 2: error_5 = _a.sent(); /* istanbul ignore next */ this.logger.debug('DiagnosticsStorage: Failed to set internal value', error_5); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.getInternal = function (key) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction_6, store_6, error_6; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.getDB()]; case 1: db = _a.sent(); transaction_6 = db.transaction([TABLE_NAMES.INTERNAL], 'readonly'); store_6 = transaction_6.objectStore(TABLE_NAMES.INTERNAL); return [2 /*return*/, new Promise(function (resolve, reject) { /* istanbul ignore next */ transaction_6.onabort = function () { return reject(new Error('Failed to get internal value')); }; var request = store_6.get(key); request.onsuccess = function () { return resolve(request.result); }; /* istanbul ignore next */ request.onerror = function () { return reject(new Error('Failed to get internal value')); }; })]; case 2: error_6 = _a.sent(); this.logger.debug('DiagnosticsStorage: Failed to get internal value', error_6); return [2 /*return*/, undefined]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.getLastFlushTimestamp = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var record, error_7; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.getInternal(INTERNAL_KEYS.LAST_FLUSH_TIMESTAMP)]; case 1: record = _a.sent(); return [2 /*return*/, record ? parseInt(record.value, 10) : undefined]; case 2: error_7 = _a.sent(); /* istanbul ignore next */ this.logger.debug('DiagnosticsStorage: Failed to get last flush timestamp', error_7); /* istanbul ignore next */ return [2 /*return*/, undefined]; case 3: return [2 /*return*/]; } }); }); }; DiagnosticsStorage.prototype.setLastFlushTimestamp = function (timestamp) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var error_8; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.setInternal(INTERNAL_KEYS.LAST_FLUSH_TIMESTAMP, timestamp.toString())]; case 1: _a.sent(); return [3 /*break*/, 3]; case 2: error_8 = _a.sent(); /* istanbul ignore next */ this.logger.debug('DiagnosticsStorage: Failed to set last flush timestamp', error_8); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }; /* istanbul ignore next */ DiagnosticsStorage.prototype.clearTable = function (transaction, tableName) { return new Promise(function (resolve, reject) { var store = transaction.objectStore(tableName); var request = store.clear(); request.onsuccess = function () { return resolve(); }; request.onerror = function () { return reject(new Error("Failed to clear table ".concat(tableName))); }; }); }; /* istanbul ignore next */ DiagnosticsStorage.prototype.getAllAndClear = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var db, transaction, _a, tags, counters, histogramStats, events, error_9; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 4, , 5]); return [4 /*yield*/, this.getDB()]; case 1: db = _b.sent(); transaction = db.transaction([TABLE_NAMES.TAGS, TABLE_NAMES.COUNTERS, TABLE_NAMES.HISTOGRAMS, TABLE_NAMES.EVENTS], 'readwrite'); return [4 /*yield*/, Promise.all([ this.getAllFromStore(transaction, TABLE_NAMES.TAGS), this.getAllFromStore(transaction, TABLE_NAMES.COUNTERS), this.getAllFromStore(transaction, TABLE_NAMES.HISTOGRAMS), this.getAllFromStore(transaction, TABLE_NAMES.EVENTS), ])]; case 2: _a = tslib__WEBPACK_IMPORTED_MODULE_0__.__read.apply(void 0, [_b.sent(), 4]), tags = _a[0], counters = _a[1], histogramStats = _a[2], events = _a[3]; // Clear all data in the same transaction return [4 /*yield*/, Promise.all([ this.clearTable(transaction, TABLE_NAMES.COUNTERS), this.clearTable(transaction, TABLE_NAMES.HISTOGRAMS), this.clearTable(transaction, TABLE_NAMES.EVENTS), ])]; case 3: // Clear all data in the same transaction _b.sent(); return [2 /*return*/, { tags: tags, counters: counters, histogramStats: histogramStats, events: events }]; case 4: error_9 = _b.sent(); this.logger.debug('DiagnosticsStorage: Failed to get all and clear data', error_9); return [2 /*return*/, { tags: [], counters: [], histogramStats: [], events: [] }]; case 5: return [2 /*return*/]; } }); }); }; /** * Helper method to get all records from a store within a transaction */ /* istanbul ignore next */ DiagnosticsStorage.prototype.getAllFromStore = function (transaction, tableName) { return new Promise(function (resolve, reject) { var store = transaction.objectStore(tableName); var request = store.getAll(); request.onsuccess = function () { return resolve(request.result); }; request.onerror = function () { return reject(new Error("Failed to get all from ".concat(tableName))); }; }); }; return DiagnosticsStorage; }()); //# sourceMappingURL=diagnostics-storage.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/uncaught-sdk-errors.js" /*!*******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/diagnostics/uncaught-sdk-errors.js ***! \*******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ EVENT_NAME_ERROR_UNCAUGHT: () => (/* binding */ EVENT_NAME_ERROR_UNCAUGHT), /* harmony export */ GLOBAL_KEY: () => (/* binding */ GLOBAL_KEY), /* harmony export */ enableSdkErrorListeners: () => (/* binding */ enableSdkErrorListeners), /* harmony export */ registerSdkLoaderMetadata: () => (/* binding */ registerSdkLoaderMetadata) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _global_scope__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../global-scope */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); var GLOBAL_KEY = '__AMPLITUDE_SCRIPT_URL__'; var EVENT_NAME_ERROR_UNCAUGHT = 'sdk.error.uncaught'; var getNormalizedScriptUrls = function () { var scope = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); /* istanbul ignore next */ if (!scope) { return []; } var value = scope[GLOBAL_KEY]; if (Array.isArray(value)) { return value; } /* istanbul ignore next - legacy single URL stored as string */ if (typeof value === 'string') { return [value]; } return []; }; var addNormalizedScriptUrl = function (url) { var scope = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); /* istanbul ignore next */ if (!scope) { return; } var urls = getNormalizedScriptUrls(); if (!urls.includes(url)) { urls.push(url); scope[GLOBAL_KEY] = urls; } }; var registerSdkLoaderMetadata = function (metadata) { if (metadata.scriptUrl) { var normalized = normalizeUrl(metadata.scriptUrl); if (normalized) { addNormalizedScriptUrl(normalized); } } }; var enableSdkErrorListeners = function (client) { var scope = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); if (!scope || typeof scope.addEventListener !== 'function') { return; } var handleError = function (event) { var error = event.error instanceof Error ? event.error : undefined; var stack = error === null || error === void 0 ? void 0 : error.stack; var match = detectSdkOrigin({ filename: event.filename, stack: stack }); if (!match) { return; } capture({ type: 'error', message: event.message, stack: stack, filename: event.filename, errorName: error === null || error === void 0 ? void 0 : error.name, metadata: { colno: event.colno, lineno: event.lineno, isTrusted: event.isTrusted, matchReason: match, }, }); }; var handleRejection = function (event) { var _a; var error = event.reason instanceof Error ? event.reason : undefined; var stack = error === null || error === void 0 ? void 0 : error.stack; var filename = extractFilenameFromStack(stack); var match = detectSdkOrigin({ filename: filename, stack: stack }); if (!match) { return; } /* istanbul ignore next */ capture({ type: 'unhandledrejection', message: (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : stringifyReason(event.reason), stack: stack, filename: filename, errorName: error === null || error === void 0 ? void 0 : error.name, metadata: { isTrusted: event.isTrusted, matchReason: match, }, }); }; var capture = function (context) { client.recordEvent(EVENT_NAME_ERROR_UNCAUGHT, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({ type: context.type, message: context.message, filename: context.filename, error_name: context.errorName, stack: context.stack }, context.metadata)); }; scope.addEventListener('error', handleError, true); scope.addEventListener('unhandledrejection', handleRejection, true); }; var detectSdkOrigin = function (payload) { var e_1, _a; var normalizedScriptUrls = getNormalizedScriptUrls(); if (normalizedScriptUrls.length === 0) { return undefined; } try { for (var normalizedScriptUrls_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(normalizedScriptUrls), normalizedScriptUrls_1_1 = normalizedScriptUrls_1.next(); !normalizedScriptUrls_1_1.done; normalizedScriptUrls_1_1 = normalizedScriptUrls_1.next()) { var normalizedScriptUrl = normalizedScriptUrls_1_1.value; if (payload.filename && payload.filename.includes(normalizedScriptUrl)) { return 'filename'; } if (payload.stack && payload.stack.includes(normalizedScriptUrl)) { return 'stack'; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (normalizedScriptUrls_1_1 && !normalizedScriptUrls_1_1.done && (_a = normalizedScriptUrls_1.return)) _a.call(normalizedScriptUrls_1); } finally { if (e_1) throw e_1.error; } } return undefined; }; var normalizeUrl = function (value) { var _a, _b; try { /* istanbul ignore next */ var url = new URL(value, (_b = (_a = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)()) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.origin); return url.origin + url.pathname; } catch (_c) { return undefined; } }; var extractFilenameFromStack = function (stack) { if (!stack) { return undefined; } var match = stack.match(/(https?:\/\/\S+?)(?=[)\s]|$)/); /* istanbul ignore next */ return match ? match[1] : undefined; }; /* istanbul ignore next */ var stringifyReason = function (reason) { if (typeof reason === 'string') { return reason; } try { return JSON.stringify(reason); } catch (_a) { return '[object Object]'; } }; //# sourceMappingURL=uncaught-sdk-errors.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js" /*!************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js ***! \************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getGlobalScope: () => (/* binding */ getGlobalScope) /* harmony export */ }); /* eslint-disable no-restricted-globals */ /* Only file allowed to access to globalThis, window, self */ var getGlobalScope = function () { // This should only be used for integrations with Amplitude that are not running in a browser environment // We need to specify the name of the global variable as a string to prevent it from being minified var ampIntegrationContextName = 'ampIntegrationContext'; if (typeof globalThis !== 'undefined' && typeof globalThis[ampIntegrationContextName] !== 'undefined') { return globalThis[ampIntegrationContextName]; } if (typeof globalThis !== 'undefined') { return globalThis; } if (typeof window !== 'undefined') { return window; } if (typeof self !== 'undefined') { return self; } if (typeof __webpack_require__.g !== 'undefined') { return __webpack_require__.g; } return undefined; }; //# sourceMappingURL=global-scope.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/identify.js" /*!********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/identify.js ***! \********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Identify: () => (/* binding */ Identify), /* harmony export */ IdentifyOperation: () => (/* binding */ IdentifyOperation), /* harmony export */ OrderedIdentifyOperations: () => (/* binding */ OrderedIdentifyOperations) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _types_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/constants */ "./node_modules/@amplitude/analytics-core/lib/esm/types/constants.js"); /* harmony import */ var _utils_valid_properties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/valid-properties */ "./node_modules/@amplitude/analytics-core/lib/esm/utils/valid-properties.js"); var Identify = /** @class */ (function () { function Identify() { this._propertySet = new Set(); this._properties = {}; } Identify.prototype.getUserProperties = function () { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__assign)({}, this._properties); }; Identify.prototype.set = function (property, value) { this._safeSet(IdentifyOperation.SET, property, value); return this; }; Identify.prototype.setOnce = function (property, value) { this._safeSet(IdentifyOperation.SET_ONCE, property, value); return this; }; Identify.prototype.append = function (property, value) { this._safeSet(IdentifyOperation.APPEND, property, value); return this; }; Identify.prototype.prepend = function (property, value) { this._safeSet(IdentifyOperation.PREPEND, property, value); return this; }; Identify.prototype.postInsert = function (property, value) { this._safeSet(IdentifyOperation.POSTINSERT, property, value); return this; }; Identify.prototype.preInsert = function (property, value) { this._safeSet(IdentifyOperation.PREINSERT, property, value); return this; }; Identify.prototype.remove = function (property, value) { this._safeSet(IdentifyOperation.REMOVE, property, value); return this; }; Identify.prototype.add = function (property, value) { this._safeSet(IdentifyOperation.ADD, property, value); return this; }; Identify.prototype.unset = function (property) { this._safeSet(IdentifyOperation.UNSET, property, _types_constants__WEBPACK_IMPORTED_MODULE_1__.UNSET_VALUE); return this; }; Identify.prototype.clearAll = function () { // When clear all happens, all properties are unset. Reset the entire object. this._properties = {}; this._properties[IdentifyOperation.CLEAR_ALL] = _types_constants__WEBPACK_IMPORTED_MODULE_1__.UNSET_VALUE; return this; }; // Returns whether or not this set actually worked. Identify.prototype._safeSet = function (operation, property, value) { if (this._validate(operation, property, value)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment var userPropertyMap = this._properties[operation]; if (userPropertyMap === undefined) { userPropertyMap = {}; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment this._properties[operation] = userPropertyMap; } // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access userPropertyMap[property] = value; this._propertySet.add(property); return true; } return false; }; Identify.prototype._validate = function (operation, property, value) { if (this._properties[IdentifyOperation.CLEAR_ALL] !== undefined) { // clear all already set. Skipping operation; return false; } if (this._propertySet.has(property)) { // Property already used. Skipping operation return false; } if (operation === IdentifyOperation.ADD) { return typeof value === 'number'; } if (operation !== IdentifyOperation.UNSET && operation !== IdentifyOperation.REMOVE) { return (0,_utils_valid_properties__WEBPACK_IMPORTED_MODULE_2__.isValidProperties)(property, value); } return true; }; return Identify; }()); var IdentifyOperation; (function (IdentifyOperation) { // Base Operations to set values IdentifyOperation["SET"] = "$set"; IdentifyOperation["SET_ONCE"] = "$setOnce"; // Operations around modifying existing values IdentifyOperation["ADD"] = "$add"; IdentifyOperation["APPEND"] = "$append"; IdentifyOperation["PREPEND"] = "$prepend"; IdentifyOperation["REMOVE"] = "$remove"; // Operations around appending values *if* they aren't present IdentifyOperation["PREINSERT"] = "$preInsert"; IdentifyOperation["POSTINSERT"] = "$postInsert"; // Operations around removing properties/values IdentifyOperation["UNSET"] = "$unset"; IdentifyOperation["CLEAR_ALL"] = "$clearAll"; })(IdentifyOperation || (IdentifyOperation = {})); /** * Note that the order of operations should align with https://github.com/amplitude/nova/blob/7701b5986b565d4b2fb53b99a9f2175df055dea8/src/main/java/com/amplitude/ingestion/core/UserPropertyUtils.java#L210 */ var OrderedIdentifyOperations = [ IdentifyOperation.CLEAR_ALL, IdentifyOperation.UNSET, IdentifyOperation.SET, IdentifyOperation.SET_ONCE, IdentifyOperation.ADD, IdentifyOperation.APPEND, IdentifyOperation.PREPEND, IdentifyOperation.PREINSERT, IdentifyOperation.POSTINSERT, IdentifyOperation.REMOVE, ]; //# sourceMappingURL=identify.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/language.js" /*!********************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/language.js ***! \********************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getLanguage: () => (/* binding */ getLanguage) /* harmony export */ }); var getLanguage = function () { var _a, _b, _c, _d; if (typeof navigator === 'undefined') return ''; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access var userLanguage = navigator.userLanguage; return (_d = (_c = (_b = (_a = navigator.languages) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : navigator.language) !== null && _c !== void 0 ? _c : userLanguage) !== null && _d !== void 0 ? _d : ''; }; //# sourceMappingURL=language.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/logger.js" /*!******************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/logger.js ***! \******************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Logger: () => (/* binding */ Logger) /* harmony export */ }); /* harmony import */ var _types_loglevel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types/loglevel */ "./node_modules/@amplitude/analytics-core/lib/esm/types/loglevel.js"); var PREFIX = 'Amplitude Logger '; var Logger = /** @class */ (function () { function Logger() { this.logLevel = _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.None; } Logger.prototype.disable = function () { this.logLevel = _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.None; }; Logger.prototype.enable = function (logLevel) { if (logLevel === void 0) { logLevel = _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.Warn; } this.logLevel = logLevel; }; Logger.prototype.log = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.logLevel < _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.Verbose) { return; } console.log("".concat(PREFIX, "[Log]: ").concat(args.join(' '))); }; Logger.prototype.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.logLevel < _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.Warn) { return; } console.warn("".concat(PREFIX, "[Warn]: ").concat(args.join(' '))); }; Logger.prototype.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.logLevel < _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.Error) { return; } console.error("".concat(PREFIX, "[Error]: ").concat(args.join(' '))); }; Logger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (this.logLevel < _types_loglevel__WEBPACK_IMPORTED_MODULE_0__.LogLevel.Debug) { return; } // console.debug output is hidden by default in chrome console.log("".concat(PREFIX, "[Debug]: ").concat(args.join(' '))); }; return Logger; }()); //# sourceMappingURL=logger.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/background-capture.js" /*!****************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/messenger/background-capture.js ***! \****************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ enableBackgroundCapture: () => (/* binding */ enableBackgroundCapture) /* harmony export */ }); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/constants.js"); /** * Brand key set on the messenger instance to track whether background capture * has been enabled. */ var BG_CAPTURE_BRAND = '__AMPLITUDE_BACKGROUND_CAPTURE__'; /** * Enable background capture on a messenger instance. * Plugins can call this on a shared messenger instance. * The first call registers the handlers; subsequent calls are no-ops. * * @param messenger - The messenger to enable background capture on * @param options.scriptUrl - Override the background capture script URL (optional) */ function enableBackgroundCapture(messenger, options) { var _a; // Check the brand on the messenger object itself — works across bundle boundaries var branded = messenger; if (branded[BG_CAPTURE_BRAND] === true) { return; } branded[BG_CAPTURE_BRAND] = true; var scriptUrl = (_a = options === null || options === void 0 ? void 0 : options.scriptUrl) !== null && _a !== void 0 ? _a : _constants__WEBPACK_IMPORTED_MODULE_0__.AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL; var backgroundCaptureInstance = null; var onBackgroundCapture = function (type, backgroundCaptureData) { var _a, _b; if (type === 'background-capture-complete') { (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Background capture complete'); messenger.notify({ action: 'background-capture-complete', data: backgroundCaptureData }); } }; messenger.registerActionHandler('initialize-background-capture', function () { var _a, _b; (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Initializing background capture (external script)'); var resolvedUrl = new URL(scriptUrl, messenger.endpoint).toString(); messenger .loadScriptOnce(resolvedUrl) .then(function () { var _a, _b, _c; (_b = (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.call(_a, 'Background capture script loaded (external)'); // eslint-disable-next-line backgroundCaptureInstance = /* istanbul ignore next -- window is always defined in browser */ (_c = window === null || window === void 0 ? void 0 : window.amplitudeBackgroundCapture) === null || _c === void 0 ? void 0 : _c.call(window, { messenger: messenger, onBackgroundCapture: onBackgroundCapture, }); messenger.notify({ action: 'background-capture-loaded' }); }) .catch(function () { var _a; (_a = messenger.logger) === null || _a === void 0 ? void 0 : _a.warn('Failed to initialize background capture'); }); }); messenger.registerActionHandler('close-background-capture', function () { var _a; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call (_a = backgroundCaptureInstance === null || backgroundCaptureInstance === void 0 ? void 0 : backgroundCaptureInstance.close) === null || _a === void 0 ? void 0 : _a.call(backgroundCaptureInstance); backgroundCaptureInstance = null; }); } //# sourceMappingURL=background-capture.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/base-window-messenger.js" /*!*******************************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/messenger/base-window-messenger.js ***! \*******************************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ getOrCreateWindowMessenger: () => (/* binding */ getOrCreateWindowMessenger) /* harmony export */ }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); /* harmony import */ var _global_scope__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../global-scope */ "./node_modules/@amplitude/analytics-core/lib/esm/global-scope.js"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants */ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/constants.js"); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils */ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/utils.js"); var _a; /** * Brand key used to identify BaseWindowMessenger instances across bundle boundaries. */ var MESSENGER_BRAND = '__AMPLITUDE_MESSENGER_INSTANCE__'; /** Global scope key where the singleton messenger is stored. */ var MESSENGER_GLOBAL_KEY = '__AMPLITUDE_MESSENGER__'; /** * BaseWindowMessenger provides generic cross-window communication via postMessage. * Singleton access via getOrCreateWindowMessenger() to prevent duplicate instances */ var BaseWindowMessenger = /** @class */ (function () { function BaseWindowMessenger(_b) { var _c = _b === void 0 ? {} : _b, _d = _c.origin, origin = _d === void 0 ? _constants__WEBPACK_IMPORTED_MODULE_2__.AMPLITUDE_ORIGIN : _d; /** Brand property for cross-bundle instanceof checks. */ this[_a] = true; this.isSetup = false; this.messageHandler = null; this.requestCallbacks = {}; this.actionHandlers = new Map(); /** * Messages received for actions that had no registered handler yet. * Drained automatically when the corresponding handler is registered via * registerActionHandler(), solving startup race conditions between * independently-initialized plugins. */ this.pendingMessages = new Map(); /** * Tracks in-flight and completed script loads by URL. * Using a map, this prevents duplicate loads before the first resolves. */ this.scriptLoadPromises = new Map(); this.endpoint = origin; } /** * Send a message to the parent window (window.opener). */ BaseWindowMessenger.prototype.notify = function (message) { var _b, _c, _d, _e; (_c = (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug) === null || _c === void 0 ? void 0 : _c.call(_b, 'Message sent: ', JSON.stringify(message)); (_e = (_d = window.opener) === null || _d === void 0 ? void 0 : _d.postMessage) === null || _e === void 0 ? void 0 : _e.call(_d, message, this.endpoint); }; /** * Send an async request to the parent window with a unique ID. * Returns a Promise that resolves when the parent responds. */ BaseWindowMessenger.prototype.sendRequest = function (action, args, options) { var _this = this; if (options === void 0) { options = { timeout: 15000 }; } var id = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.generateUniqueId)(); var request = { id: id, action: action, args: args }; var promise = new Promise(function (resolve, reject) { _this.requestCallbacks[id] = { resolve: resolve, reject: reject }; _this.notify(request); if (options.timeout > 0) { setTimeout(function () { reject(new Error("".concat(action, " timed out (id: ").concat(id, ")"))); delete _this.requestCallbacks[id]; }, options.timeout); } }); return promise; }; /** * Handle a response to a previous request by resolving its Promise. */ BaseWindowMessenger.prototype.handleResponse = function (response) { var _b; if (!this.requestCallbacks[response.id]) { (_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn("No callback found for request id: ".concat(response.id)); return; } this.requestCallbacks[response.id].resolve(response.responseData); delete this.requestCallbacks[response.id]; }; /** * Register a handler for a specific action type. * Logs a warning if overwriting an existing handler. */ BaseWindowMessenger.prototype.registerActionHandler = function (action, handler) { var e_1, _b; var _c, _d; if (this.actionHandlers.has(action)) { (_d = (_c = this.logger) === null || _c === void 0 ? void 0 : _c.warn) === null || _d === void 0 ? void 0 : _d.call(_c, "Overwriting existing action handler for: ".concat(action)); } this.actionHandlers.set(action, handler); // Replay any messages that arrived before this handler was registered var queued = this.pendingMessages.get(action); if (queued) { this.pendingMessages.delete(action); try { for (var queued_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(queued), queued_1_1 = queued_1.next(); !queued_1_1.done; queued_1_1 = queued_1.next()) { var data = queued_1_1.value; handler(data); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (queued_1_1 && !queued_1_1.done && (_b = queued_1.return)) _b.call(queued_1); } finally { if (e_1) throw e_1.error; } } } }; /** * Load a script once, deduplicating by URL. * Safe against concurrent calls — the second call awaits the first's in-flight Promise * rather than triggering a duplicate load. */ BaseWindowMessenger.prototype.loadScriptOnce = function (url) { return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__awaiter)(this, void 0, void 0, function () { var existing, loadPromise, error_1; return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { switch (_b.label) { case 0: existing = this.scriptLoadPromises.get(url); if (existing) { return [2 /*return*/, existing]; } loadPromise = (0,_utils__WEBPACK_IMPORTED_MODULE_3__.asyncLoadScript)(url).then(function () { // Resolve to void }); this.scriptLoadPromises.set(url, loadPromise); _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); return [4 /*yield*/, loadPromise]; case 2: _b.sent(); return [3 /*break*/, 4]; case 3: error_1 = _b.sent(); // Remove failed loads so they can be retried this.scriptLoadPromises.delete(url); throw error_1; case 4: return [2 /*return*/]; } }); }); }; /** * Set up the message listener. Idempotent — safe to call multiple times. * Subclasses should call super.setup() and then register their own action handlers. */ BaseWindowMessenger.prototype.setup = function (_b) { var _this = this; var _c, _d; var _e = _b === void 0 ? {} : _b, logger = _e.logger, endpoint = _e.endpoint; if (logger) { this.logger = logger; } // If endpoint is customized, don't override a previously customized endpoint. if (endpoint && this.endpoint === _constants__WEBPACK_IMPORTED_MODULE_2__.AMPLITUDE_ORIGIN) { this.endpoint = endpoint; } // Only attach the message listener once if (this.isSetup) { return; } this.isSetup = true; (_d = (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug) === null || _d === void 0 ? void 0 : _d.call(_c, 'Setting up messenger'); // Attach Event Listener to listen for messages from the parent window this.messageHandler = function (event) { var _b, _c, _d, _e, _f; (_c = (_b = _this.logger) === null || _b === void 0 ? void 0 : _b.debug) === null || _c === void 0 ? void 0 : _c.call(_b, 'Message received: ', JSON.stringify(event)); // Only accept messages from the specified origin if (_this.endpoint !== event.origin) { return; } var eventData = event.data; var action = eventData === null || eventData === void 0 ? void 0 : eventData.action; // Ignore messages without action if (!action) { return; } // If id exists, handle responses to previous requests if ('id' in eventData && eventData.id) { (_e = (_d = _this.logger) === null || _d === void 0 ? void 0 : _d.debug) === null || _e === void 0 ? void 0 : _e.call(_d, 'Received Response to previous request: ', JSON.stringify(event)); _this.handleResponse(eventData); } else { if (action === 'ping') { _this.notify({ action: 'pong' }); return; } // Dispatch to registered action handlers, or buffer for late registration var handler = _this.actionHandlers.get(action); if (handler) { handler(eventData.data); } else { var queue = (_f = _this.pendingMessages.get(action)) !== null && _f !== void 0 ? _f : []; queue.push(eventData.data); _this.pendingMessages.set(action, queue); } } }; window.addEventListener('message', this.messageHandler); this.notify({ action: 'page-loaded' }); }; /** * Tear down the messenger: remove the message listener, clear all state. */ BaseWindowMessenger.prototype.destroy = function () { if (this.messageHandler) { window.removeEventListener('message', this.messageHandler); this.messageHandler = null; } this.isSetup = false; this.actionHandlers.clear(); this.pendingMessages.clear(); this.requestCallbacks = {}; this.scriptLoadPromises.clear(); // Remove from global scope if this is the singleton var globalScope = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); if ((globalScope === null || globalScope === void 0 ? void 0 : globalScope[MESSENGER_GLOBAL_KEY]) === this) { delete globalScope[MESSENGER_GLOBAL_KEY]; } }; return BaseWindowMessenger; }()); _a = MESSENGER_BRAND; /** * Type guard: checks whether a value is a BaseWindowMessenger instance. */ function isWindowMessenger(value) { return (typeof value === 'object' && value !== null && MESSENGER_BRAND in value && value[MESSENGER_BRAND] === true); } /** * Get or create a singleton BaseWindowMessenger instance. * Ensures only one messenger (and one message listener) exists per page, * preventing duplicate script loads and double notifications. * * The singleton is stored on globalScope under the same MESSENGER_KEY. * The branded property check verifies the stored value is actually a messenger. */ function getOrCreateWindowMessenger(options) { var globalScope = (0,_global_scope__WEBPACK_IMPORTED_MODULE_1__.getGlobalScope)(); var existing = globalScope === null || globalScope === void 0 ? void 0 : globalScope[MESSENGER_GLOBAL_KEY]; if (isWindowMessenger(existing)) { return existing; } var messenger = new BaseWindowMessenger(options); if (globalScope) { globalScope[MESSENGER_GLOBAL_KEY] = messenger; } return messenger; } //# sourceMappingURL=base-window-messenger.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/constants.js" /*!*******************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/messenger/constants.js ***! \*******************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL: () => (/* binding */ AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL), /* harmony export */ AMPLITUDE_ORIGIN: () => (/* binding */ AMPLITUDE_ORIGIN), /* harmony export */ AMPLITUDE_ORIGINS_MAP: () => (/* binding */ AMPLITUDE_ORIGINS_MAP), /* harmony export */ AMPLITUDE_ORIGIN_EU: () => (/* binding */ AMPLITUDE_ORIGIN_EU), /* harmony export */ AMPLITUDE_ORIGIN_STAGING: () => (/* binding */ AMPLITUDE_ORIGIN_STAGING) /* harmony export */ }); // Shared origin constants for Amplitude cross-window communication var AMPLITUDE_ORIGIN = 'https://app.amplitude.com'; var AMPLITUDE_ORIGIN_EU = 'https://app.eu.amplitude.com'; var AMPLITUDE_ORIGIN_STAGING = 'https://apps.stag2.amplitude.com'; var AMPLITUDE_ORIGINS_MAP = { US: AMPLITUDE_ORIGIN, EU: AMPLITUDE_ORIGIN_EU, STAGING: AMPLITUDE_ORIGIN_STAGING, }; // Background capture script URL (shared between autocapture and session-replay) var AMPLITUDE_BACKGROUND_CAPTURE_SCRIPT_URL = 'https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.3.js.gz'; //# sourceMappingURL=constants.js.map /***/ }, /***/ "./node_modules/@amplitude/analytics-core/lib/esm/messenger/utils.js" /*!***************************************************************************!*\ !*** ./node_modules/@amplitude/analytics-core/lib/esm/messenger/utils.js ***! \***************************************************************************/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ asyncLoadScript: () => (/* binding */ asyncLoadScript), /* harmony export */ generateUniqueId: () => (/* binding */ generateUniqueId) /* harmony export */ }); /* eslint-disable no-restricted-globals */ /** * Dynamically loads an external script by appending a `. this.sequenceIndex = Number(c === CharCodes.Lt); } } stateCDATASequence(c) { if (c === Sequences.Cdata[this.sequenceIndex]) { if (++this.sequenceIndex === Sequences.Cdata.length) { this.state = State.InCommentLike; this.currentSequence = Sequences.CdataEnd; this.sequenceIndex = 0; this.sectionStart = this.index + 1; } } else { this.sequenceIndex = 0; this.state = State.InDeclaration; this.stateInDeclaration(c); // Reconsume the character } } /** * When we wait for one specific character, we can speed things up * by skipping through the buffer until we find it. * * @returns Whether the character was found. */ fastForwardTo(c) { while (++this.index < this.buffer.length + this.offset) { if (this.buffer.charCodeAt(this.index - this.offset) === c) { return true; } } /* * We increment the index at the end of the `parse` loop, * so set it to `buffer.length - 1` here. * * TODO: Refactor `parse` to increment index before calling states. */ this.index = this.buffer.length + this.offset - 1; return false; } /** * Comments and CDATA end with `-->` and `]]>`. * * Their common qualities are: * - Their end sequences have a distinct character they start with. * - That character is then repeated, so we have to check multiple repeats. * - All characters but the start character of the sequence can be skipped. */ stateInCommentLike(c) { if (c === this.currentSequence[this.sequenceIndex]) { if (++this.sequenceIndex === this.currentSequence.length) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, this.index, 2); } else { this.cbs.oncomment(this.sectionStart, this.index, 2); } this.sequenceIndex = 0; this.sectionStart = this.index + 1; this.state = State.Text; } } else if (this.sequenceIndex === 0) { // Fast-forward to the first character of the sequence if (this.fastForwardTo(this.currentSequence[0])) { this.sequenceIndex = 1; } } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { // Allow long sequences, eg. --->, ]]]> this.sequenceIndex = 0; } } /** * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name. * * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar). * We allow anything that wouldn't end the tag. */ isTagStartChar(c) { return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c); } startSpecial(sequence, offset) { this.isSpecial = true; this.currentSequence = sequence; this.sequenceIndex = offset; this.state = State.SpecialStartSequence; } stateBeforeTagName(c) { if (c === CharCodes.ExclamationMark) { this.state = State.BeforeDeclaration; this.sectionStart = this.index + 1; } else if (c === CharCodes.Questionmark) { this.state = State.InProcessingInstruction; this.sectionStart = this.index + 1; } else if (this.isTagStartChar(c)) { const lower = c | 0x20; this.sectionStart = this.index; if (this.xmlMode) { this.state = State.InTagName; } else if (lower === Sequences.ScriptEnd[2]) { this.state = State.BeforeSpecialS; } else if (lower === Sequences.TitleEnd[2] || lower === Sequences.XmpEnd[2]) { this.state = State.BeforeSpecialT; } else { this.state = State.InTagName; } } else if (c === CharCodes.Slash) { this.state = State.BeforeClosingTagName; } else { this.state = State.Text; this.stateText(c); } } stateInTagName(c) { if (isEndOfTagSection(c)) { this.cbs.onopentagname(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } } stateBeforeClosingTagName(c) { if (isWhitespace(c)) { // Ignore } else if (c === CharCodes.Gt) { this.state = State.Text; } else { this.state = this.isTagStartChar(c) ? State.InClosingTagName : State.InSpecialComment; this.sectionStart = this.index; } } stateInClosingTagName(c) { if (c === CharCodes.Gt || isWhitespace(c)) { this.cbs.onclosetag(this.sectionStart, this.index); this.sectionStart = -1; this.state = State.AfterClosingTagName; this.stateAfterClosingTagName(c); } } stateAfterClosingTagName(c) { // Skip everything until ">" if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeAttributeName(c) { if (c === CharCodes.Gt) { this.cbs.onopentagend(this.index); if (this.isSpecial) { this.state = State.InSpecialTag; this.sequenceIndex = 0; } else { this.state = State.Text; } this.sectionStart = this.index + 1; } else if (c === CharCodes.Slash) { this.state = State.InSelfClosingTag; } else if (!isWhitespace(c)) { this.state = State.InAttributeName; this.sectionStart = this.index; } } stateInSelfClosingTag(c) { if (c === CharCodes.Gt) { this.cbs.onselfclosingtag(this.index); this.state = State.Text; this.sectionStart = this.index + 1; this.isSpecial = false; // Reset special state, in case of self-closing special tags } else if (!isWhitespace(c)) { this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } } stateInAttributeName(c) { if (c === CharCodes.Eq || isEndOfTagSection(c)) { this.cbs.onattribname(this.sectionStart, this.index); this.sectionStart = this.index; this.state = State.AfterAttributeName; this.stateAfterAttributeName(c); } } stateAfterAttributeName(c) { if (c === CharCodes.Eq) { this.state = State.BeforeAttributeValue; } else if (c === CharCodes.Slash || c === CharCodes.Gt) { this.cbs.onattribend(QuoteType.NoValue, this.sectionStart); this.sectionStart = -1; this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (!isWhitespace(c)) { this.cbs.onattribend(QuoteType.NoValue, this.sectionStart); this.state = State.InAttributeName; this.sectionStart = this.index; } } stateBeforeAttributeValue(c) { if (c === CharCodes.DoubleQuote) { this.state = State.InAttributeValueDq; this.sectionStart = this.index + 1; } else if (c === CharCodes.SingleQuote) { this.state = State.InAttributeValueSq; this.sectionStart = this.index + 1; } else if (!isWhitespace(c)) { this.sectionStart = this.index; this.state = State.InAttributeValueNq; this.stateInAttributeValueNoQuotes(c); // Reconsume token } } handleInAttributeValue(c, quote) { if (c === quote || (!this.decodeEntities && this.fastForwardTo(quote))) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend(quote === CharCodes.DoubleQuote ? QuoteType.Double : QuoteType.Single, this.index + 1); this.state = State.BeforeAttributeName; } else if (this.decodeEntities && c === CharCodes.Amp) { this.startEntity(); } } stateInAttributeValueDoubleQuotes(c) { this.handleInAttributeValue(c, CharCodes.DoubleQuote); } stateInAttributeValueSingleQuotes(c) { this.handleInAttributeValue(c, CharCodes.SingleQuote); } stateInAttributeValueNoQuotes(c) { if (isWhitespace(c) || c === CharCodes.Gt) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = -1; this.cbs.onattribend(QuoteType.Unquoted, this.index); this.state = State.BeforeAttributeName; this.stateBeforeAttributeName(c); } else if (this.decodeEntities && c === CharCodes.Amp) { this.startEntity(); } } stateBeforeDeclaration(c) { if (c === CharCodes.OpeningSquareBracket) { this.state = State.CDATASequence; this.sequenceIndex = 0; } else { this.state = c === CharCodes.Dash ? State.BeforeComment : State.InDeclaration; } } stateInDeclaration(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.ondeclaration(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } } stateInProcessingInstruction(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.onprocessinginstruction(this.sectionStart, this.index); this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeComment(c) { if (c === CharCodes.Dash) { this.state = State.InCommentLike; this.currentSequence = Sequences.CommentEnd; // Allow short comments (eg. ) this.sequenceIndex = 2; this.sectionStart = this.index + 1; } else { this.state = State.InDeclaration; } } stateInSpecialComment(c) { if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) { this.cbs.oncomment(this.sectionStart, this.index, 0); this.state = State.Text; this.sectionStart = this.index + 1; } } stateBeforeSpecialS(c) { const lower = c | 0x20; if (lower === Sequences.ScriptEnd[3]) { this.startSpecial(Sequences.ScriptEnd, 4); } else if (lower === Sequences.StyleEnd[3]) { this.startSpecial(Sequences.StyleEnd, 4); } else { this.state = State.InTagName; this.stateInTagName(c); // Consume the token again } } stateBeforeSpecialT(c) { const lower = c | 0x20; switch (lower) { case Sequences.TitleEnd[3]: { this.startSpecial(Sequences.TitleEnd, 4); break; } case Sequences.TextareaEnd[3]: { this.startSpecial(Sequences.TextareaEnd, 4); break; } case Sequences.XmpEnd[3]: { this.startSpecial(Sequences.XmpEnd, 4); break; } default: { this.state = State.InTagName; this.stateInTagName(c); // Consume the token again } } } startEntity() { this.baseState = this.state; this.state = State.InEntity; this.entityStart = this.index; this.entityDecoder.startEntity(this.xmlMode ? decode_1.DecodingMode.Strict : this.baseState === State.Text || this.baseState === State.InSpecialTag ? decode_1.DecodingMode.Legacy : decode_1.DecodingMode.Attribute); } stateInEntity() { const indexInBuffer = this.index - this.offset; const length = this.entityDecoder.write(this.buffer, indexInBuffer); // If `length` is positive, we are done with the entity. if (length >= 0) { this.state = this.baseState; if (length === 0) { this.index -= 1; } } else { if (indexInBuffer < this.buffer.length && this.buffer.charCodeAt(indexInBuffer) === CharCodes.Amp) { this.state = this.baseState; this.index -= 1; return; } // Mark buffer as consumed. this.index = this.offset + this.buffer.length - 1; } } /** * Remove data that has already been consumed from the buffer. */ cleanup() { // If we are inside of text or attributes, emit what we already have. if (this.running && this.sectionStart !== this.index) { if (this.state === State.Text || (this.state === State.InSpecialTag && this.sequenceIndex === 0)) { this.cbs.ontext(this.sectionStart, this.index); this.sectionStart = this.index; } else if (this.state === State.InAttributeValueDq || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueNq) { this.cbs.onattribdata(this.sectionStart, this.index); this.sectionStart = this.index; } } } shouldContinue() { return this.index < this.buffer.length + this.offset && this.running; } /** * Iterates through the buffer, calling the function corresponding to the current state. * * States that are more likely to be hit are higher up, as a performance improvement. */ parse() { while (this.shouldContinue()) { const c = this.buffer.charCodeAt(this.index - this.offset); switch (this.state) { case State.Text: { this.stateText(c); break; } case State.SpecialStartSequence: { this.stateSpecialStartSequence(c); break; } case State.InSpecialTag: { this.stateInSpecialTag(c); break; } case State.CDATASequence: { this.stateCDATASequence(c); break; } case State.InAttributeValueDq: { this.stateInAttributeValueDoubleQuotes(c); break; } case State.InAttributeName: { this.stateInAttributeName(c); break; } case State.InCommentLike: { this.stateInCommentLike(c); break; } case State.InSpecialComment: { this.stateInSpecialComment(c); break; } case State.BeforeAttributeName: { this.stateBeforeAttributeName(c); break; } case State.InTagName: { this.stateInTagName(c); break; } case State.InClosingTagName: { this.stateInClosingTagName(c); break; } case State.BeforeTagName: { this.stateBeforeTagName(c); break; } case State.AfterAttributeName: { this.stateAfterAttributeName(c); break; } case State.InAttributeValueSq: { this.stateInAttributeValueSingleQuotes(c); break; } case State.BeforeAttributeValue: { this.stateBeforeAttributeValue(c); break; } case State.BeforeClosingTagName: { this.stateBeforeClosingTagName(c); break; } case State.AfterClosingTagName: { this.stateAfterClosingTagName(c); break; } case State.BeforeSpecialS: { this.stateBeforeSpecialS(c); break; } case State.BeforeSpecialT: { this.stateBeforeSpecialT(c); break; } case State.InAttributeValueNq: { this.stateInAttributeValueNoQuotes(c); break; } case State.InSelfClosingTag: { this.stateInSelfClosingTag(c); break; } case State.InDeclaration: { this.stateInDeclaration(c); break; } case State.BeforeDeclaration: { this.stateBeforeDeclaration(c); break; } case State.BeforeComment: { this.stateBeforeComment(c); break; } case State.InProcessingInstruction: { this.stateInProcessingInstruction(c); break; } case State.InEntity: { this.stateInEntity(); break; } } this.index++; } this.cleanup(); } finish() { if (this.state === State.InEntity) { this.entityDecoder.end(); this.state = this.baseState; } this.handleTrailingData(); this.cbs.onend(); } /** Handle any trailing data. */ handleTrailingData() { const endIndex = this.buffer.length + this.offset; // If there is no remaining data, we are done. if (this.sectionStart >= endIndex) { return; } if (this.state === State.InCommentLike) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, endIndex, 0); } else { this.cbs.oncomment(this.sectionStart, endIndex, 0); } } else if (this.state === State.InTagName || this.state === State.BeforeAttributeName || this.state === State.BeforeAttributeValue || this.state === State.AfterAttributeName || this.state === State.InAttributeName || this.state === State.InAttributeValueSq || this.state === State.InAttributeValueDq || this.state === State.InAttributeValueNq || this.state === State.InClosingTagName) { /* * If we are currently in an opening or closing tag, us not calling the * respective callback signals that the tag should be ignored. */ } else { this.cbs.ontext(this.sectionStart, endIndex); } } emitCodePoint(cp, consumed) { if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) { if (this.sectionStart < this.entityStart) { this.cbs.onattribdata(this.sectionStart, this.entityStart); } this.sectionStart = this.entityStart + consumed; this.index = this.sectionStart - 1; this.cbs.onattribentity(cp); } else { if (this.sectionStart < this.entityStart) { this.cbs.ontext(this.sectionStart, this.entityStart); } this.sectionStart = this.entityStart + consumed; this.index = this.sectionStart - 1; this.cbs.ontextentity(cp, this.sectionStart); } } } exports["default"] = Tokenizer; //# sourceMappingURL=Tokenizer.js.map /***/ }, /***/ "./node_modules/htmlparser2/dist/commonjs/index.js" /*!*********************************************************!*\ !*** ./node_modules/htmlparser2/dist/commonjs/index.js ***! \*********************************************************/ (__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DomUtils = exports.getFeed = exports.ElementType = exports.QuoteType = exports.Tokenizer = exports.DefaultHandler = exports.DomHandler = exports.Parser = void 0; exports.parseDocument = parseDocument; exports.parseDOM = parseDOM; exports.createDocumentStream = createDocumentStream; exports.createDomStream = createDomStream; exports.parseFeed = parseFeed; const Parser_js_1 = __webpack_require__(/*! ./Parser.js */ "./node_modules/htmlparser2/dist/commonjs/Parser.js"); var Parser_js_2 = __webpack_require__(/*! ./Parser.js */ "./node_modules/htmlparser2/dist/commonjs/Parser.js"); Object.defineProperty(exports, "Parser", ({ enumerable: true, get: function () { return Parser_js_2.Parser; } })); const domhandler_1 = __webpack_require__(/*! domhandler */ "./node_modules/domhandler/lib/index.js"); var domhandler_2 = __webpack_require__(/*! domhandler */ "./node_modules/domhandler/lib/index.js"); Object.defineProperty(exports, "DomHandler", ({ enumerable: true, get: function () { return domhandler_2.DomHandler; } })); // Old name for DomHandler Object.defineProperty(exports, "DefaultHandler", ({ enumerable: true, get: function () { return domhandler_2.DomHandler; } })); // Helper methods /** * Parses the data, returns the resulting document. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM handler. */ function parseDocument(data, options) { const handler = new domhandler_1.DomHandler(undefined, options); new Parser_js_1.Parser(handler, options).end(data); return handler.root; } /** * Parses data, returns an array of the root nodes. * * Note that the root nodes still have a `Document` node as their parent. * Use `parseDocument` to get the `Document` node instead. * * @param data The data that should be parsed. * @param options Optional options for the parser and DOM handler. * @deprecated Use `parseDocument` instead. */ function parseDOM(data, options) { return parseDocument(data, options).children; } /** * Creates a parser instance, with an attached DOM handler. * * @param callback A callback that will be called once parsing has been completed, with the resulting document. * @param options Optional options for the parser and DOM handler. * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM. */ function createDocumentStream(callback, options, elementCallback) { const handler = new domhandler_1.DomHandler((error) => callback(error, handler.root), options, elementCallback); return new Parser_js_1.Parser(handler, options); } /** * Creates a parser instance, with an attached DOM handler. * * @param callback A callback that will be called once parsing has been completed, with an array of root nodes. * @param options Optional options for the parser and DOM handler. * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM. * @deprecated Use `createDocumentStream` instead. */ function createDomStream(callback, options, elementCallback) { const handler = new domhandler_1.DomHandler(callback, options, elementCallback); return new Parser_js_1.Parser(handler, options); } var Tokenizer_js_1 = __webpack_require__(/*! ./Tokenizer.js */ "./node_modules/htmlparser2/dist/commonjs/Tokenizer.js"); Object.defineProperty(exports, "Tokenizer", ({ enumerable: true, get: function () { return __importDefault(Tokenizer_js_1).default; } })); Object.defineProperty(exports, "QuoteType", ({ enumerable: true, get: function () { return Tokenizer_js_1.QuoteType; } })); /* * All of the following exports exist for backwards-compatibility. * They should probably be removed eventually. */ exports.ElementType = __importStar(__webpack_require__(/*! domelementtype */ "./node_modules/domelementtype/lib/index.js")); const domutils_1 = __webpack_require__(/*! domutils */ "./node_modules/domutils/lib/index.js"); var domutils_2 = __webpack_require__(/*! domutils */ "./node_modules/domutils/lib/index.js"); Object.defineProperty(exports, "getFeed", ({ enumerable: true, get: function () { return domutils_2.getFeed; } })); const parseFeedDefaultOptions = { xmlMode: true }; /** * Parse a feed. * * @param feed The feed that should be parsed, as a string. * @param options Optionally, options for parsing. When using this, you should set `xmlMode` to `true`. */ function parseFeed(feed, options = parseFeedDefaultOptions) { return (0, domutils_1.getFeed)(parseDOM(feed, options)); } exports.DomUtils = __importStar(__webpack_require__(/*! domutils */ "./node_modules/domutils/lib/index.js")); //# sourceMappingURL=index.js.map /***/ }, /***/ "./node_modules/nanoid/non-secure/index.cjs" /*!**************************************************!*\ !*** ./node_modules/nanoid/non-secure/index.cjs ***! \**************************************************/ (module) { // This alphabet uses `A-Za-z0-9_-` symbols. // The order of characters is optimized for better gzip and brotli compression. // References to the same file (works both for gzip and brotli): // `'use`, `andom`, and `rict'` // References to the brotli default dictionary: // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf` let urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' let customAlphabet = (alphabet, defaultSize = 21) => { return (size = defaultSize) => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. let i = size | 0 while (i--) { // `| 0` is more compact and faster than `Math.floor()`. id += alphabet[(Math.random() * alphabet.length) | 0] } return id } } let nanoid = (size = 21) => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. let i = size | 0 while (i--) { // `| 0` is more compact and faster than `Math.floor()`. id += urlAlphabet[(Math.random() * 64) | 0] } return id } module.exports = { nanoid, customAlphabet } /***/ }, /***/ "./node_modules/axios/lib/adapters/adapters.js" /*!*****************************************************!*\ !*** ./node_modules/axios/lib/adapters/adapters.js ***! \*****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _http_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./http.js */ "./node_modules/axios/lib/helpers/null.js"); /* harmony import */ var _xhr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./xhr.js */ "./node_modules/axios/lib/adapters/xhr.js"); /* harmony import */ var _fetch_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fetch.js */ "./node_modules/axios/lib/adapters/fetch.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /** * Known adapters mapping. * Provides environment-specific adapters for Axios: * - `http` for Node.js * - `xhr` for browsers * - `fetch` for fetch API-based requests * * @type {Object} */ const knownAdapters = { http: _http_js__WEBPACK_IMPORTED_MODULE_1__["default"], xhr: _xhr_js__WEBPACK_IMPORTED_MODULE_2__["default"], fetch: { get: _fetch_js__WEBPACK_IMPORTED_MODULE_3__.getFetch, }, }; // Assign adapter names for easier debugging and identification _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(knownAdapters, (fn, value) => { if (fn) { try { // Null-proto descriptors so a polluted Object.prototype.get cannot turn // these data descriptors into accessor descriptors on the way in. Object.defineProperty(fn, 'name', { __proto__: null, value }); } catch (e) { // eslint-disable-next-line no-empty } Object.defineProperty(fn, 'adapterName', { __proto__: null, value }); } }); /** * Render a rejection reason string for unknown or unsupported adapters * * @param {string} reason * @returns {string} */ const renderReason = (reason) => `- ${reason}`; /** * Check if the adapter is resolved (function, null, or false) * * @param {Function|null|false} adapter * @returns {boolean} */ const isResolvedHandle = (adapter) => _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(adapter) || adapter === null || adapter === false; /** * Get the first suitable adapter from the provided list. * Tries each adapter in order until a supported one is found. * Throws an AxiosError if no adapter is suitable. * * @param {Array|string|Function} adapters - Adapter(s) by name or function. * @param {Object} config - Axios request configuration * @throws {AxiosError} If no suitable adapter is available * @returns {Function} The resolved adapter function */ function getAdapter(adapters, config) { adapters = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(adapters) ? adapters : [adapters]; const { length } = adapters; let nameOrAdapter; let adapter; const rejectedReasons = {}; for (let i = 0; i < length; i++) { nameOrAdapter = adapters[i]; let id; adapter = nameOrAdapter; if (!isResolvedHandle(nameOrAdapter)) { adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; if (adapter === undefined) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_4__["default"](`Unknown adapter '${id}'`); } } if (adapter && (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(adapter) || (adapter = adapter.get(config)))) { break; } rejectedReasons[id || '#' + i] = adapter; } if (!adapter) { const reasons = Object.entries(rejectedReasons).map( ([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build') ); let s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified'; throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_4__["default"]( `There is no suitable adapter to dispatch the request ` + s, 'ERR_NOT_SUPPORT' ); } return adapter; } /** * Exports Axios adapters and utility to resolve an adapter */ /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ /** * Resolve an adapter from a list of adapter names or functions. * @type {Function} */ getAdapter, /** * Exposes all known adapters * @type {Object} */ adapters: knownAdapters, }); /***/ }, /***/ "./node_modules/axios/lib/adapters/fetch.js" /*!**************************************************!*\ !*** ./node_modules/axios/lib/adapters/fetch.js ***! \**************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), /* harmony export */ getFetch: () => (/* binding */ getFetch) /* harmony export */ }); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _helpers_composeSignals_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../helpers/composeSignals.js */ "./node_modules/axios/lib/helpers/composeSignals.js"); /* harmony import */ var _helpers_trackStream_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../helpers/trackStream.js */ "./node_modules/axios/lib/helpers/trackStream.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../helpers/progressEventReducer.js */ "./node_modules/axios/lib/helpers/progressEventReducer.js"); /* harmony import */ var _helpers_resolveConfig_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../helpers/resolveConfig.js */ "./node_modules/axios/lib/helpers/resolveConfig.js"); /* harmony import */ var _core_settle_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../core/settle.js */ "./node_modules/axios/lib/core/settle.js"); /* harmony import */ var _helpers_estimateDataURLDecodedBytes_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../helpers/estimateDataURLDecodedBytes.js */ "./node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js"); /* harmony import */ var _env_data_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../env/data.js */ "./node_modules/axios/lib/env/data.js"); /* harmony import */ var _helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../helpers/sanitizeHeaderValue.js */ "./node_modules/axios/lib/helpers/sanitizeHeaderValue.js"); const DEFAULT_CHUNK_SIZE = 64 * 1024; const { isFunction } = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"]; const test = (fn, ...args) => { try { return !!fn(...args); } catch (e) { return false; } }; const factory = (env) => { const globalObject = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].global !== undefined && _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].global !== null ? _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].global : globalThis; const { ReadableStream, TextEncoder } = globalObject; env = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].merge.call( { skipUndefined: true, }, { Request: globalObject.Request, Response: globalObject.Response, }, env ); const { fetch: envFetch, Request, Response } = env; const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; const isRequestSupported = isFunction(Request); const isResponseSupported = isFunction(Response); if (!isFetchSupported) { return false; } const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream); const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? ( (encoder) => (str) => encoder.encode(str) )(new TextEncoder()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer())); const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { let duplexAccessed = false; const request = new Request(_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].origin, { body: new ReadableStream(), method: 'POST', get duplex() { duplexAccessed = true; return 'half'; }, }); const hasContentType = request.headers.has('Content-Type'); if (request.body != null) { request.body.cancel(); } return duplexAccessed && !hasContentType; }); const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isReadableStream(new Response('').body)); const resolvers = { stream: supportsResponseStream && ((res) => res.body), }; isFetchSupported && (() => { ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => { !resolvers[type] && (resolvers[type] = (res, config) => { let method = res && res[type]; if (method) { return method.call(res); } throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( `Response type '${type}' is not supported`, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_NOT_SUPPORT, config ); }); }); })(); const getBodyLength = async (body) => { if (body == null) { return 0; } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isBlob(body)) { return body.size; } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isSpecCompliantForm(body)) { const _request = new Request(_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].origin, { method: 'POST', body, }); return (await _request.arrayBuffer()).byteLength; } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isArrayBufferView(body) || _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isArrayBuffer(body)) { return body.byteLength; } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isURLSearchParams(body)) { body = body + ''; } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isString(body)) { return (await encodeText(body)).byteLength; } }; const resolveBodyLength = async (headers, body) => { const length = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].toFiniteNumber(headers.getContentLength()); return length == null ? getBodyLength(body) : length; }; return async (config) => { let { url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, withCredentials = 'same-origin', fetchOptions, maxContentLength, maxBodyLength, } = (0,_helpers_resolveConfig_js__WEBPACK_IMPORTED_MODULE_7__["default"])(config); const hasMaxContentLength = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isNumber(maxContentLength) && maxContentLength > -1; const hasMaxBodyLength = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isNumber(maxBodyLength) && maxBodyLength > -1; let _fetch = envFetch || fetch; responseType = responseType ? (responseType + '').toLowerCase() : 'text'; let composedSignal = (0,_helpers_composeSignals_js__WEBPACK_IMPORTED_MODULE_3__["default"])( [signal, cancelToken && cancelToken.toAbortSignal()], timeout ); let request = null; const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { composedSignal.unsubscribe(); }); let requestContentLength; try { // Enforce maxContentLength for data: URLs up-front so we never materialize // an oversized payload. The HTTP adapter applies the same check (see http.js // "if (protocol === 'data:')" branch). if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) { const estimated = (0,_helpers_estimateDataURLDecodedBytes_js__WEBPACK_IMPORTED_MODULE_9__["default"])(url); if (estimated > maxContentLength) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'maxContentLength size of ' + maxContentLength + ' exceeded', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_BAD_RESPONSE, config, request ); } } // Enforce maxBodyLength against the outbound request body before dispatch. // Mirrors http.js behavior (ERR_BAD_REQUEST / 'Request body larger than // maxBodyLength limit'). Skip when the body length cannot be determined // (e.g. a live ReadableStream supplied by the caller). if (hasMaxBodyLength && method !== 'get' && method !== 'head') { const outboundLength = await resolveBodyLength(headers, data); if ( typeof outboundLength === 'number' && isFinite(outboundLength) && outboundLength > maxBodyLength ) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'Request body larger than maxBodyLength limit', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_BAD_REQUEST, config, request ); } } if ( onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && (requestContentLength = await resolveBodyLength(headers, data)) !== 0 ) { let _request = new Request(url, { method: 'POST', body: data, duplex: 'half', }); let contentTypeHeader; if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { headers.setContentType(contentTypeHeader); } if (_request.body) { const [onProgress, flush] = (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.progressEventDecorator)( requestContentLength, (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.progressEventReducer)((0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.asyncDecorator)(onUploadProgress)) ); data = (0,_helpers_trackStream_js__WEBPACK_IMPORTED_MODULE_4__.trackStream)(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); } } if (!_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isString(withCredentials)) { withCredentials = withCredentials ? 'include' : 'omit'; } // Cloudflare Workers throws when credentials are defined // see https://github.com/cloudflare/workerd/issues/902 const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype; // If data is FormData and Content-Type is multipart/form-data without boundary, // delete it so fetch can set it correctly with the boundary if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isFormData(data)) { const contentType = headers.getContentType(); if ( contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType) ) { headers.delete('content-type'); } } // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js) headers.set('User-Agent', 'axios/' + _env_data_js__WEBPACK_IMPORTED_MODULE_10__.VERSION, false); const resolvedOptions = { ...fetchOptions, signal: composedSignal, method: method.toUpperCase(), headers: (0,_helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_11__.toByteStringHeaderObject)(headers.normalize()), body: data, duplex: 'half', credentials: isCredentialsSupported ? withCredentials : undefined, }; request = isRequestSupported && new Request(url, resolvedOptions); let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); // Cheap pre-check: if the server honestly declares a content-length that // already exceeds the cap, reject before we start streaming. if (hasMaxContentLength) { const declaredLength = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].toFiniteNumber(response.headers.get('content-length')); if (declaredLength != null && declaredLength > maxContentLength) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'maxContentLength size of ' + maxContentLength + ' exceeded', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_BAD_RESPONSE, config, request ); } } const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); if ( supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe)) ) { const options = {}; ['status', 'statusText', 'headers'].forEach((prop) => { options[prop] = response[prop]; }); const responseContentLength = _utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].toFiniteNumber(response.headers.get('content-length')); const [onProgress, flush] = (onDownloadProgress && (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.progressEventDecorator)( responseContentLength, (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.progressEventReducer)((0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_6__.asyncDecorator)(onDownloadProgress), true) )) || []; let bytesRead = 0; const onChunkProgress = (loadedBytes) => { if (hasMaxContentLength) { bytesRead = loadedBytes; if (bytesRead > maxContentLength) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'maxContentLength size of ' + maxContentLength + ' exceeded', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_BAD_RESPONSE, config, request ); } } onProgress && onProgress(loadedBytes); }; response = new Response( (0,_helpers_trackStream_js__WEBPACK_IMPORTED_MODULE_4__.trackStream)(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => { flush && flush(); unsubscribe && unsubscribe(); }), options ); } responseType = responseType || 'text'; let responseData = await resolvers[_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].findKey(resolvers, responseType) || 'text']( response, config ); // Fallback enforcement for environments without ReadableStream support // (legacy runtimes). Detect materialized size from typed output; skip // streams/Response passthrough since the user will read those themselves. if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) { let materializedSize; if (responseData != null) { if (typeof responseData.byteLength === 'number') { materializedSize = responseData.byteLength; } else if (typeof responseData.size === 'number') { materializedSize = responseData.size; } else if (typeof responseData === 'string') { materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length; } } if (typeof materializedSize === 'number' && materializedSize > maxContentLength) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'maxContentLength size of ' + maxContentLength + ' exceeded', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_BAD_RESPONSE, config, request ); } } !isStreamResponse && unsubscribe && unsubscribe(); return await new Promise((resolve, reject) => { (0,_core_settle_js__WEBPACK_IMPORTED_MODULE_8__["default"])(resolve, reject, { data: responseData, headers: _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_5__["default"].from(response.headers), status: response.status, statusText: response.statusText, config, request, }); }); } catch (err) { unsubscribe && unsubscribe(); // Safari can surface fetch aborts as a DOMException-like object whose // branded getters throw. Prefer our composed signal reason before reading // the caught error, preserving timeout vs cancellation semantics. if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]) { const canceledError = composedSignal.reason; canceledError.config = config; request && (canceledError.request = request); err !== canceledError && (canceledError.cause = err); throw canceledError; } if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { throw Object.assign( new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"]( 'Network Error', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERR_NETWORK, config, request, err && err.response ), { cause: err.cause || err, } ); } throw _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_2__["default"].from(err, err && err.code, config, request, err && err.response); } }; }; const seedCache = new Map(); const getFetch = (config) => { let env = (config && config.env) || {}; const { fetch, Request, Response } = env; const seeds = [Request, Response, fetch]; let len = seeds.length, i = len, seed, target, map = seedCache; while (i--) { seed = seeds[i]; target = map.get(seed); target === undefined && map.set(seed, (target = i ? new Map() : factory(env))); map = target; } return target; }; const adapter = getFetch(); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (adapter); /***/ }, /***/ "./node_modules/axios/lib/adapters/xhr.js" /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _core_settle_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core/settle.js */ "./node_modules/axios/lib/core/settle.js"); /* harmony import */ var _defaults_transitional_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../defaults/transitional.js */ "./node_modules/axios/lib/defaults/transitional.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../cancel/CanceledError.js */ "./node_modules/axios/lib/cancel/CanceledError.js"); /* harmony import */ var _helpers_parseProtocol_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../helpers/parseProtocol.js */ "./node_modules/axios/lib/helpers/parseProtocol.js"); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../helpers/progressEventReducer.js */ "./node_modules/axios/lib/helpers/progressEventReducer.js"); /* harmony import */ var _helpers_resolveConfig_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../helpers/resolveConfig.js */ "./node_modules/axios/lib/helpers/resolveConfig.js"); /* harmony import */ var _helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../helpers/sanitizeHeaderValue.js */ "./node_modules/axios/lib/helpers/sanitizeHeaderValue.js"); const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (isXHRAdapterSupported && function (config) { return new Promise(function dispatchXhrRequest(resolve, reject) { const _config = (0,_helpers_resolveConfig_js__WEBPACK_IMPORTED_MODULE_9__["default"])(config); let requestData = _config.data; const requestHeaders = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_7__["default"].from(_config.headers).normalize(); let { responseType, onUploadProgress, onDownloadProgress } = _config; let onCanceled; let uploadThrottled, downloadThrottled; let flushUpload, flushDownload; function done() { flushUpload && flushUpload(); // flush events flushDownload && flushDownload(); // flush events _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); _config.signal && _config.signal.removeEventListener('abort', onCanceled); } let request = new XMLHttpRequest(); request.open(_config.method.toUpperCase(), _config.url, true); // Set the request timeout in MS request.timeout = _config.timeout; function onloadend() { if (!request) { return; } // Prepare the response const responseHeaders = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_7__["default"].from( 'getAllResponseHeaders' in request && request.getAllResponseHeaders() ); const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; const response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config, request, }; (0,_core_settle_js__WEBPACK_IMPORTED_MODULE_1__["default"])( function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response ); // Clean up request request = null; } 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.startsWith('file:')) ) { 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; } reject(new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"]('Request aborted', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"].ECONNABORTED, config, request)); done(); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError(event) { // Browsers deliver a ProgressEvent in XHR onerror // (message may be empty; when present, surface it) // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event const msg = event && event.message ? event.message : 'Network Error'; const err = new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"](msg, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"].ERR_NETWORK, config, request); // attach the underlying event for consumers who want details err.event = event || null; reject(err); done(); request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; const transitional = _config.transitional || _defaults_transitional_js__WEBPACK_IMPORTED_MODULE_2__["default"]; if (_config.timeoutErrorMessage) { timeoutErrorMessage = _config.timeoutErrorMessage; } reject( new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"]( timeoutErrorMessage, transitional.clarifyTimeoutError ? _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"].ETIMEDOUT : _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"].ECONNABORTED, config, request ) ); done(); // Clean up request request = null; }; // Remove Content-Type if data is undefined requestData === undefined && requestHeaders.setContentType(null); // Add headers to the request if ('setRequestHeader' in request) { _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach((0,_helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_10__.toByteStringHeaderObject)(requestHeaders), function setRequestHeader(val, key) { request.setRequestHeader(key, val); }); } // Add withCredentials to request if needed if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(_config.withCredentials)) { request.withCredentials = !!_config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = _config.responseType; } // Handle progress if needed if (onDownloadProgress) { [downloadThrottled, flushDownload] = (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_8__.progressEventReducer)(onDownloadProgress, true); request.addEventListener('progress', downloadThrottled); } // Not all browsers support upload events if (onUploadProgress && request.upload) { [uploadThrottled, flushUpload] = (0,_helpers_progressEventReducer_js__WEBPACK_IMPORTED_MODULE_8__.progressEventReducer)(onUploadProgress); request.upload.addEventListener('progress', uploadThrottled); request.upload.addEventListener('loadend', flushUpload); } if (_config.cancelToken || _config.signal) { // Handle cancellation // eslint-disable-next-line func-names onCanceled = (cancel) => { if (!request) { return; } reject(!cancel || cancel.type ? new _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_4__["default"](null, config, request) : cancel); request.abort(); done(); request = null; }; _config.cancelToken && _config.cancelToken.subscribe(onCanceled); if (_config.signal) { _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); } } const protocol = (0,_helpers_parseProtocol_js__WEBPACK_IMPORTED_MODULE_5__["default"])(_config.url); if (protocol && !_platform_index_js__WEBPACK_IMPORTED_MODULE_6__["default"].protocols.includes(protocol)) { reject( new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"]( 'Unsupported protocol ' + protocol + ':', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_3__["default"].ERR_BAD_REQUEST, config ) ); return; } // Send the request request.send(requestData || null); }); }); /***/ }, /***/ "./node_modules/axios/lib/axios.js" /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _helpers_bind_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers/bind.js */ "./node_modules/axios/lib/helpers/bind.js"); /* harmony import */ var _core_Axios_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./core/Axios.js */ "./node_modules/axios/lib/core/Axios.js"); /* harmony import */ var _core_mergeConfig_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./core/mergeConfig.js */ "./node_modules/axios/lib/core/mergeConfig.js"); /* harmony import */ var _defaults_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./defaults/index.js */ "./node_modules/axios/lib/defaults/index.js"); /* harmony import */ var _helpers_formDataToJSON_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./helpers/formDataToJSON.js */ "./node_modules/axios/lib/helpers/formDataToJSON.js"); /* harmony import */ var _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./cancel/CanceledError.js */ "./node_modules/axios/lib/cancel/CanceledError.js"); /* harmony import */ var _cancel_CancelToken_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./cancel/CancelToken.js */ "./node_modules/axios/lib/cancel/CancelToken.js"); /* harmony import */ var _cancel_isCancel_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./cancel/isCancel.js */ "./node_modules/axios/lib/cancel/isCancel.js"); /* harmony import */ var _env_data_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./env/data.js */ "./node_modules/axios/lib/env/data.js"); /* harmony import */ var _helpers_toFormData_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./helpers/toFormData.js */ "./node_modules/axios/lib/helpers/toFormData.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _helpers_spread_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./helpers/spread.js */ "./node_modules/axios/lib/helpers/spread.js"); /* harmony import */ var _helpers_isAxiosError_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./helpers/isAxiosError.js */ "./node_modules/axios/lib/helpers/isAxiosError.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _adapters_adapters_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./adapters/adapters.js */ "./node_modules/axios/lib/adapters/adapters.js"); /* harmony import */ var _helpers_HttpStatusCode_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./helpers/HttpStatusCode.js */ "./node_modules/axios/lib/helpers/HttpStatusCode.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * * @returns {Axios} A new instance of Axios */ function createInstance(defaultConfig) { const context = new _core_Axios_js__WEBPACK_IMPORTED_MODULE_2__["default"](defaultConfig); const instance = (0,_helpers_bind_js__WEBPACK_IMPORTED_MODULE_1__["default"])(_core_Axios_js__WEBPACK_IMPORTED_MODULE_2__["default"].prototype.request, context); // Copy axios.prototype to instance _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].extend(instance, _core_Axios_js__WEBPACK_IMPORTED_MODULE_2__["default"].prototype, context, { allOwnKeys: true }); // Copy context to instance _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].extend(instance, context, null, { allOwnKeys: true }); // Factory for creating new instances instance.create = function create(instanceConfig) { return createInstance((0,_core_mergeConfig_js__WEBPACK_IMPORTED_MODULE_3__["default"])(defaultConfig, instanceConfig)); }; return instance; } // Create the default instance to be exported const axios = createInstance(_defaults_index_js__WEBPACK_IMPORTED_MODULE_4__["default"]); // Expose Axios class to allow class inheritance axios.Axios = _core_Axios_js__WEBPACK_IMPORTED_MODULE_2__["default"]; // Expose Cancel & CancelToken axios.CanceledError = _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_6__["default"]; axios.CancelToken = _cancel_CancelToken_js__WEBPACK_IMPORTED_MODULE_7__["default"]; axios.isCancel = _cancel_isCancel_js__WEBPACK_IMPORTED_MODULE_8__["default"]; axios.VERSION = _env_data_js__WEBPACK_IMPORTED_MODULE_9__.VERSION; axios.toFormData = _helpers_toFormData_js__WEBPACK_IMPORTED_MODULE_10__["default"]; // Expose AxiosError class axios.AxiosError = _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_11__["default"]; // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = _helpers_spread_js__WEBPACK_IMPORTED_MODULE_12__["default"]; // Expose isAxiosError axios.isAxiosError = _helpers_isAxiosError_js__WEBPACK_IMPORTED_MODULE_13__["default"]; // Expose mergeConfig axios.mergeConfig = _core_mergeConfig_js__WEBPACK_IMPORTED_MODULE_3__["default"]; axios.AxiosHeaders = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_14__["default"]; axios.formToJSON = (thing) => (0,_helpers_formDataToJSON_js__WEBPACK_IMPORTED_MODULE_5__["default"])(_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = _adapters_adapters_js__WEBPACK_IMPORTED_MODULE_15__["default"].getAdapter; axios.HttpStatusCode = _helpers_HttpStatusCode_js__WEBPACK_IMPORTED_MODULE_16__["default"]; axios.default = axios; // this module should only have a default export /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (axios); /***/ }, /***/ "./node_modules/axios/lib/cancel/CancelToken.js" /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _CanceledError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CanceledError.js */ "./node_modules/axios/lib/cancel/CanceledError.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @param {Function} executor The executor function. * * @returns {CancelToken} */ class CancelToken { constructor(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } let resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); const token = this; // eslint-disable-next-line func-names this.promise.then((cancel) => { if (!token._listeners) return; let i = token._listeners.length; while (i-- > 0) { token._listeners[i](cancel); } token._listeners = null; }); // eslint-disable-next-line func-names this.promise.then = (onfulfilled) => { let _resolve; // eslint-disable-next-line func-names const promise = new Promise((resolve) => { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message, config, request) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new _CanceledError_js__WEBPACK_IMPORTED_MODULE_0__["default"](message, config, request); resolvePromise(token.reason); }); } /** * Throws a `CanceledError` if cancellation has been requested. */ throwIfRequested() { if (this.reason) { throw this.reason; } } /** * Subscribe to the cancel signal */ subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } } /** * Unsubscribe from the cancel signal */ unsubscribe(listener) { if (!this._listeners) { return; } const index = this._listeners.indexOf(listener); if (index !== -1) { this._listeners.splice(index, 1); } } toAbortSignal() { const controller = new AbortController(); const abort = (err) => { controller.abort(err); }; this.subscribe(abort); controller.signal.unsubscribe = () => this.unsubscribe(abort); return controller.signal; } /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ static source() { let cancel; const token = new CancelToken(function executor(c) { cancel = c; }); return { token, cancel, }; } } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CancelToken); /***/ }, /***/ "./node_modules/axios/lib/cancel/CanceledError.js" /*!********************************************************!*\ !*** ./node_modules/axios/lib/cancel/CanceledError.js ***! \********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); class CanceledError extends _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_0__["default"] { /** * A `CanceledError` is an object that is thrown when an operation is canceled. * * @param {string=} message The message. * @param {Object=} config The config. * @param {Object=} request The request. * * @returns {CanceledError} The created error. */ constructor(message, config, request) { super(message == null ? 'canceled' : message, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_0__["default"].ERR_CANCELED, config, request); this.name = 'CanceledError'; this.__CANCEL__ = true; } } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanceledError); /***/ }, /***/ "./node_modules/axios/lib/cancel/isCancel.js" /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ isCancel) /* harmony export */ }); function isCancel(value) { return !!(value && value.__CANCEL__); } /***/ }, /***/ "./node_modules/axios/lib/core/Axios.js" /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _helpers_buildURL_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../helpers/buildURL.js */ "./node_modules/axios/lib/helpers/buildURL.js"); /* harmony import */ var _InterceptorManager_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./InterceptorManager.js */ "./node_modules/axios/lib/core/InterceptorManager.js"); /* harmony import */ var _dispatchRequest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dispatchRequest.js */ "./node_modules/axios/lib/core/dispatchRequest.js"); /* harmony import */ var _mergeConfig_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./mergeConfig.js */ "./node_modules/axios/lib/core/mergeConfig.js"); /* harmony import */ var _buildFullPath_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./buildFullPath.js */ "./node_modules/axios/lib/core/buildFullPath.js"); /* harmony import */ var _helpers_validator_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../helpers/validator.js */ "./node_modules/axios/lib/helpers/validator.js"); /* harmony import */ var _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _defaults_transitional_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../defaults/transitional.js */ "./node_modules/axios/lib/defaults/transitional.js"); const validators = _helpers_validator_js__WEBPACK_IMPORTED_MODULE_6__["default"].validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance * * @return {Axios} A new instance of Axios */ class Axios { constructor(instanceConfig) { this.defaults = instanceConfig || {}; this.interceptors = { request: new _InterceptorManager_js__WEBPACK_IMPORTED_MODULE_2__["default"](), response: new _InterceptorManager_js__WEBPACK_IMPORTED_MODULE_2__["default"](), }; } /** * Dispatch a request * * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) * @param {?Object} config * * @returns {Promise} The Promise to be fulfilled */ async request(configOrUrl, config) { try { return await this._request(configOrUrl, config); } catch (err) { if (err instanceof Error) { let dummy = {}; Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); // slice off the Error: ... line const stack = (() => { if (!dummy.stack) { return ''; } const firstNewlineIndex = dummy.stack.indexOf('\n'); return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1); })(); try { if (!err.stack) { err.stack = stack; // match without the 2 top stack lines } else if (stack) { const firstNewlineIndex = stack.indexOf('\n'); const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1); const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1); if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) { err.stack += '\n' + stack; } } } catch (e) { // ignore the case where "stack" is an un-writable property } } throw err; } } _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 || {}; } config = (0,_mergeConfig_js__WEBPACK_IMPORTED_MODULE_4__["default"])(this.defaults, config); const { transitional, paramsSerializer, headers } = config; if (transitional !== undefined) { _helpers_validator_js__WEBPACK_IMPORTED_MODULE_6__["default"].assertOptions( transitional, { silentJSONParsing: validators.transitional(validators.boolean), forcedJSONParsing: validators.transitional(validators.boolean), clarifyTimeoutError: validators.transitional(validators.boolean), legacyInterceptorReqResOrdering: validators.transitional(validators.boolean), }, false ); } if (paramsSerializer != null) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(paramsSerializer)) { config.paramsSerializer = { serialize: paramsSerializer, }; } else { _helpers_validator_js__WEBPACK_IMPORTED_MODULE_6__["default"].assertOptions( paramsSerializer, { encode: validators.function, serialize: validators.function, }, true ); } } // Set config.allowAbsoluteUrls if (config.allowAbsoluteUrls !== undefined) { // do nothing } else if (this.defaults.allowAbsoluteUrls !== undefined) { config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; } else { config.allowAbsoluteUrls = true; } _helpers_validator_js__WEBPACK_IMPORTED_MODULE_6__["default"].assertOptions( config, { baseUrl: validators.spelling('baseURL'), withXsrfToken: validators.spelling('withXSRFToken'), }, true ); // Set config.method config.method = (config.method || this.defaults.method || 'get').toLowerCase(); // Flatten headers let contextHeaders = headers && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].merge(headers.common, headers[config.method]); headers && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => { delete headers[method]; }); config.headers = _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_7__["default"].concat(contextHeaders, headers); // filter out skipped interceptors const requestInterceptorChain = []; let synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; const transitional = config.transitional || _defaults_transitional_js__WEBPACK_IMPORTED_MODULE_8__["default"]; const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering; if (legacyInterceptorReqResOrdering) { requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); } else { requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); } }); const responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); let promise; let i = 0; let len; if (!synchronousRequestInterceptors) { const chain = [_dispatchRequest_js__WEBPACK_IMPORTED_MODULE_3__["default"].bind(this), undefined]; chain.unshift(...requestInterceptorChain); chain.push(...responseInterceptorChain); len = chain.length; promise = Promise.resolve(config); while (i < len) { promise = promise.then(chain[i++], chain[i++]); } return promise; } len = requestInterceptorChain.length; let newConfig = config; while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected.call(this, error); break; } } try { promise = _dispatchRequest_js__WEBPACK_IMPORTED_MODULE_3__["default"].call(this, newConfig); } catch (error) { return Promise.reject(error); } i = 0; len = responseInterceptorChain.length; while (i < len) { promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); } return promise; } getUri(config) { config = (0,_mergeConfig_js__WEBPACK_IMPORTED_MODULE_4__["default"])(this.defaults, config); const fullPath = (0,_buildFullPath_js__WEBPACK_IMPORTED_MODULE_5__["default"])(config.baseURL, config.url, config.allowAbsoluteUrls); return (0,_helpers_buildURL_js__WEBPACK_IMPORTED_MODULE_1__["default"])(fullPath, config.params, config.paramsSerializer); } } // Provide aliases for supported request methods _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function (url, config) { return this.request( (0,_mergeConfig_js__WEBPACK_IMPORTED_MODULE_4__["default"])(config || {}, { method, url, data: (config || {}).data, }) ); }; }); _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) { function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { return this.request( (0,_mergeConfig_js__WEBPACK_IMPORTED_MODULE_4__["default"])(config || {}, { method, headers: isForm ? { 'Content-Type': 'multipart/form-data', } : {}, url, data, }) ); }; } Axios.prototype[method] = generateHTTPMethod(); // QUERY is a safe/idempotent read method; multipart form bodies don't fit // its semantics, so no queryForm shorthand is generated. if (method !== 'query') { Axios.prototype[method + 'Form'] = generateHTTPMethod(true); } }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Axios); /***/ }, /***/ "./node_modules/axios/lib/core/AxiosError.js" /*!***************************************************!*\ !*** ./node_modules/axios/lib/core/AxiosError.js ***! \***************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); const REDACTED = '[REDACTED ****]'; function hasOwnOrPrototypeToJSON(source) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(source, 'toJSON')) { return true; } let prototype = Object.getPrototypeOf(source); while (prototype && prototype !== Object.prototype) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(prototype, 'toJSON')) { return true; } prototype = Object.getPrototypeOf(prototype); } return false; } // Build a plain-object snapshot of `config` and replace the value of any key // (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays // and AxiosHeaders, and short-circuits on circular references. function redactConfig(config, redactKeys) { const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase())); const seen = []; const visit = (source) => { if (source === null || typeof source !== 'object') return source; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBuffer(source)) return source; if (seen.indexOf(source) !== -1) return undefined; if (source instanceof _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_1__["default"]) { source = source.toJSON(); } seen.push(source); let result; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(source)) { result = []; source.forEach((v, i) => { const reducedValue = visit(v); if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(reducedValue)) { result[i] = reducedValue; } }); } else { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) { seen.pop(); return source; } result = Object.create(null); for (const [key, value] of Object.entries(source)) { const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value); if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(reducedValue)) { result[key] = reducedValue; } } } seen.pop(); return result; }; return visit(config); } class AxiosError extends Error { static from(error, code, config, request, response, customProps) { const axiosError = new AxiosError(error.message, code || error.code, config, request, response); axiosError.cause = error; axiosError.name = error.name; // Preserve status from the original error if not already set from response if (error.status != null && axiosError.status == null) { axiosError.status = error.status; } customProps && Object.assign(axiosError, customProps); return axiosError; } /** * 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. */ constructor(message, code, config, request, response) { super(message); // Make message enumerable to maintain backward compatibility // The native Error constructor sets message as non-enumerable, // but axios < v1.13.3 had it as enumerable Object.defineProperty(this, 'message', { // Null-proto descriptor so a polluted Object.prototype.get cannot turn // this data descriptor into an accessor descriptor on the way in. __proto__: null, value: message, enumerable: true, writable: true, configurable: true, }); this.name = 'AxiosError'; this.isAxiosError = true; code && (this.code = code); config && (this.config = config); request && (this.request = request); if (response) { this.response = response; this.status = response.status; } } toJSON() { // Opt-in redaction: when the request config carries a `redact` array, the // value of any matching key (case-insensitive, at any depth) is replaced // with REDACTED in the serialized snapshot. Undefined or empty leaves the // existing serialization behavior unchanged. const config = this.config; const redactKeys = config && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(config, 'redact') ? config.redact : undefined; const serializedConfig = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toJSONObject(config); 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: serializedConfig, code: this.code, status: this.status, }; } } // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated. AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE'; AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION'; AxiosError.ECONNABORTED = 'ECONNABORTED'; AxiosError.ETIMEDOUT = 'ETIMEDOUT'; AxiosError.ECONNREFUSED = 'ECONNREFUSED'; AxiosError.ERR_NETWORK = 'ERR_NETWORK'; AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS'; AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED'; AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE'; AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST'; AxiosError.ERR_CANCELED = 'ERR_CANCELED'; AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT'; AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL'; AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED'; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AxiosError); /***/ }, /***/ "./node_modules/axios/lib/core/AxiosHeaders.js" /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/AxiosHeaders.js ***! \*****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _helpers_parseHeaders_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../helpers/parseHeaders.js */ "./node_modules/axios/lib/helpers/parseHeaders.js"); /* harmony import */ var _helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../helpers/sanitizeHeaderValue.js */ "./node_modules/axios/lib/helpers/sanitizeHeaderValue.js"); const $internals = Symbol('internals'); function normalizeHeader(header) { return header && String(header).trim().toLowerCase(); } function normalizeValue(value) { if (value === false || value == null) { return value; } return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(value) ? value.map(normalizeValue) : (0,_helpers_sanitizeHeaderValue_js__WEBPACK_IMPORTED_MODULE_2__.sanitizeHeaderValue)(String(value)); } function parseTokens(str) { const tokens = Object.create(null); const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; let match; while ((match = tokensRE.exec(str))) { tokens[match[1]] = match[2]; } return tokens; } const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(filter)) { return filter.call(this, value, header); } if (isHeaderNameFilter) { value = header; } if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(value)) return; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(filter)) { return value.indexOf(filter) !== -1; } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isRegExp(filter)) { return filter.test(value); } } function formatHeader(header) { return header .trim() .toLowerCase() .replace(/([a-z\d])(\w*)/g, (w, char, str) => { return char.toUpperCase() + str; }); } function buildAccessors(obj, header) { const accessorName = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toCamelCase(' ' + header); ['get', 'set', 'has'].forEach((methodName) => { Object.defineProperty(obj, methodName + accessorName, { // Null-proto descriptor so a polluted Object.prototype.get cannot turn // this data descriptor into an accessor descriptor on the way in. __proto__: null, value: function (arg1, arg2, arg3) { return this[methodName].call(this, header, arg1, arg2, arg3); }, configurable: true, }); }); } class AxiosHeaders { constructor(headers) { headers && this.set(headers); } set(header, valueOrRewrite, rewrite) { const self = this; function setHeader(_value, _header, _rewrite) { const lHeader = normalizeHeader(_header); if (!lHeader) { throw new Error('header name must be a non-empty string'); } const key = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].findKey(self, lHeader); if ( !key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false) ) { self[key || _header] = normalizeValue(_value); } } const setHeaders = (headers, _rewrite) => _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(header) || header instanceof this.constructor) { setHeaders(header, valueOrRewrite); } else if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { setHeaders((0,_helpers_parseHeaders_js__WEBPACK_IMPORTED_MODULE_1__["default"])(header), valueOrRewrite); } else if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(header) && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isIterable(header)) { let obj = {}, dest, key; for (const entry of header) { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(entry)) { throw TypeError('Object iterator must return a key-value pair'); } obj[(key = entry[0])] = (dest = obj[key]) ? _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1]; } setHeaders(obj, valueOrRewrite); } else { header != null && setHeader(valueOrRewrite, header, rewrite); } return this; } get(header, parser) { header = normalizeHeader(header); if (header) { const key = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].findKey(this, header); if (key) { const value = this[key]; if (!parser) { return value; } if (parser === true) { return parseTokens(value); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(parser)) { return parser.call(this, value, key); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isRegExp(parser)) { return parser.exec(value); } throw new TypeError('parser must be boolean|regexp|function'); } } } has(header, matcher) { header = normalizeHeader(header); if (header) { const key = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].findKey(this, header); return !!( key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)) ); } return false; } delete(header, matcher) { const self = this; let deleted = false; function deleteHeader(_header) { _header = normalizeHeader(_header); if (_header) { const key = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].findKey(self, _header); if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { delete self[key]; deleted = true; } } } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(header)) { header.forEach(deleteHeader); } else { deleteHeader(header); } return deleted; } clear(matcher) { const keys = Object.keys(this); let i = keys.length; let deleted = false; while (i--) { const key = keys[i]; if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { delete this[key]; deleted = true; } } return deleted; } normalize(format) { const self = this; const headers = {}; _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(this, (value, header) => { const key = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].findKey(headers, header); if (key) { self[key] = normalizeValue(value); delete self[header]; return; } const normalized = format ? formatHeader(header) : String(header).trim(); if (normalized !== header) { delete self[header]; } self[normalized] = normalizeValue(value); headers[normalized] = true; }); return this; } concat(...targets) { return this.constructor.concat(this, ...targets); } toJSON(asStrings) { const obj = Object.create(null); _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(this, (value, header) => { value != null && value !== false && (obj[header] = asStrings && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(value) ? value.join(', ') : value); }); return obj; } [Symbol.iterator]() { return Object.entries(this.toJSON())[Symbol.iterator](); } toString() { return Object.entries(this.toJSON()) .map(([header, value]) => header + ': ' + value) .join('\n'); } getSetCookie() { return this.get('set-cookie') || []; } get [Symbol.toStringTag]() { return 'AxiosHeaders'; } static from(thing) { return thing instanceof this ? thing : new this(thing); } static concat(first, ...targets) { const computed = new this(first); targets.forEach((target) => computed.set(target)); return computed; } static accessor(header) { const internals = (this[$internals] = this[$internals] = { accessors: {}, }); const accessors = internals.accessors; const prototype = this.prototype; function defineAccessor(_header) { const lHeader = normalizeHeader(_header); if (!accessors[lHeader]) { buildAccessors(prototype, _header); accessors[lHeader] = true; } } _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); return this; } } AxiosHeaders.accessor([ 'Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization', ]); // reserved names hotfix _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, set(headerValue) { this[mapped] = headerValue; }, }; }); _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].freezeMethods(AxiosHeaders); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AxiosHeaders); /***/ }, /***/ "./node_modules/axios/lib/core/InterceptorManager.js" /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); class InterceptorManager { constructor() { 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` * @param {Object} options The options for the interceptor, synchronous and runWhen * * @return {Number} An ID used to remove interceptor later */ use(fulfilled, rejected, options) { this.handlers.push({ fulfilled, 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` * * @returns {void} */ eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } /** * Clear all interceptors from the stack * * @returns {void} */ clear() { if (this.handlers) { this.handlers = []; } } /** * 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 * * @returns {void} */ forEach(fn) { _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); } } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (InterceptorManager); /***/ }, /***/ "./node_modules/axios/lib/core/buildFullPath.js" /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/buildFullPath.js ***! \******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ buildFullPath) /* harmony export */ }); /* harmony import */ var _helpers_isAbsoluteURL_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../helpers/isAbsoluteURL.js */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); /* harmony import */ var _helpers_combineURLs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../helpers/combineURLs.js */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * 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 */ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { let isRelativeUrl = !(0,_helpers_isAbsoluteURL_js__WEBPACK_IMPORTED_MODULE_0__["default"])(requestedURL); if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) { return (0,_helpers_combineURLs_js__WEBPACK_IMPORTED_MODULE_1__["default"])(baseURL, requestedURL); } return requestedURL; } /***/ }, /***/ "./node_modules/axios/lib/core/dispatchRequest.js" /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ dispatchRequest) /* harmony export */ }); /* harmony import */ var _transformData_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./transformData.js */ "./node_modules/axios/lib/core/transformData.js"); /* harmony import */ var _cancel_isCancel_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../cancel/isCancel.js */ "./node_modules/axios/lib/cancel/isCancel.js"); /* harmony import */ var _defaults_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../defaults/index.js */ "./node_modules/axios/lib/defaults/index.js"); /* harmony import */ var _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../cancel/CanceledError.js */ "./node_modules/axios/lib/cancel/CanceledError.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _adapters_adapters_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../adapters/adapters.js */ "./node_modules/axios/lib/adapters/adapters.js"); /** * Throws a `CanceledError` if cancellation has been requested. * * @param {Object} config The config that is to be used for the request * * @returns {void} */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_3__["default"](null, config); } } /** * 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 dispatchRequest(config) { throwIfCancellationRequested(config); config.headers = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_4__["default"].from(config.headers); // Transform request data config.data = _transformData_js__WEBPACK_IMPORTED_MODULE_0__["default"].call(config, config.transformRequest); if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { config.headers.setContentType('application/x-www-form-urlencoded', false); } const adapter = _adapters_adapters_js__WEBPACK_IMPORTED_MODULE_5__["default"].getAdapter(config.adapter || _defaults_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].adapter, config); return adapter(config).then( function onAdapterResolution(response) { throwIfCancellationRequested(config); // Expose the current response on config so that transformResponse can // attach it to any AxiosError it throws (e.g. on JSON parse failure). // We clean it up afterwards to avoid polluting the config object. config.response = response; try { response.data = _transformData_js__WEBPACK_IMPORTED_MODULE_0__["default"].call(config, config.transformResponse, response); } finally { delete config.response; } response.headers = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_4__["default"].from(response.headers); return response; }, function onAdapterRejection(reason) { if (!(0,_cancel_isCancel_js__WEBPACK_IMPORTED_MODULE_1__["default"])(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { config.response = reason.response; try { reason.response.data = _transformData_js__WEBPACK_IMPORTED_MODULE_0__["default"].call( config, config.transformResponse, reason.response ); } finally { delete config.response; } reason.response.headers = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_4__["default"].from(reason.response.headers); } } return Promise.reject(reason); } ); } /***/ }, /***/ "./node_modules/axios/lib/core/mergeConfig.js" /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ mergeConfig) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); const headersToObject = (thing) => (thing instanceof _AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_1__["default"] ? { ...thing } : thing); /** * 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 mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; // Use a null-prototype object so that downstream reads such as `config.auth` // or `config.baseURL` cannot inherit polluted values from Object.prototype. // `hasOwnProperty` is restored as a non-enumerable own slot to preserve // ergonomics for user code that relies on it. const config = Object.create(null); Object.defineProperty(config, 'hasOwnProperty', { // Null-proto descriptor so a polluted Object.prototype.get cannot turn // this data descriptor into an accessor descriptor on the way in. __proto__: null, value: Object.prototype.hasOwnProperty, enumerable: false, writable: true, configurable: true, }); function getMergedValue(target, source, prop, caseless) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(target) && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(source)) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].merge.call({ caseless }, target, source); } else if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(source)) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].merge({}, source); } else if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(a, b, prop, caseless) { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(b)) { return getMergedValue(a, b, prop, caseless); } else if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(a)) { return getMergedValue(undefined, a, prop, caseless); } } // eslint-disable-next-line consistent-return function valueFromConfig2(a, b) { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(b)) { return getMergedValue(undefined, b); } } // eslint-disable-next-line consistent-return function defaultToConfig2(a, b) { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(b)) { return getMergedValue(undefined, b); } else if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(a)) { return getMergedValue(undefined, a); } } // eslint-disable-next-line consistent-return function mergeDirectKeys(a, b, prop) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(config2, prop)) { return getMergedValue(a, b); } else if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(config1, prop)) { return getMergedValue(undefined, a); } } const mergeMap = { url: valueFromConfig2, method: valueFromConfig2, data: valueFromConfig2, baseURL: defaultToConfig2, transformRequest: defaultToConfig2, transformResponse: defaultToConfig2, paramsSerializer: defaultToConfig2, timeout: defaultToConfig2, timeoutMessage: defaultToConfig2, withCredentials: defaultToConfig2, withXSRFToken: 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, allowedSocketPaths: defaultToConfig2, responseEncoding: defaultToConfig2, validateStatus: mergeDirectKeys, headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true), }; _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) { if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return; const merge = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; const a = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(config1, prop) ? config1[prop] : undefined; const b = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(config2, prop) ? config2[prop] : undefined; const configValue = merge(a, b, prop); (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); }); return config; } /***/ }, /***/ "./node_modules/axios/lib/core/settle.js" /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ settle) /* harmony export */ }); /* harmony import */ var _AxiosError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /** * 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. * * @returns {object} The response. */ function settle(resolve, reject, response) { const validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(new _AxiosError_js__WEBPACK_IMPORTED_MODULE_0__["default"]( 'Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? _AxiosError_js__WEBPACK_IMPORTED_MODULE_0__["default"].ERR_BAD_REQUEST : _AxiosError_js__WEBPACK_IMPORTED_MODULE_0__["default"].ERR_BAD_RESPONSE, response.config, response.request, response )); } } /***/ }, /***/ "./node_modules/axios/lib/core/transformData.js" /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ transformData) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _defaults_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../defaults/index.js */ "./node_modules/axios/lib/defaults/index.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /** * Transform the data for a request or a response * * @param {Array|Function} fns A single function or Array of functions * @param {?Object} response The response object * * @returns {*} The resulting transformed data */ function transformData(fns, response) { const config = this || _defaults_index_js__WEBPACK_IMPORTED_MODULE_1__["default"]; const context = response || config; const headers = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_2__["default"].from(context.headers); let data = context.data; _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(fns, function transform(fn) { data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); }); headers.normalize(); return data; } /***/ }, /***/ "./node_modules/axios/lib/defaults/index.js" /*!**************************************************!*\ !*** ./node_modules/axios/lib/defaults/index.js ***! \**************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _transitional_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./transitional.js */ "./node_modules/axios/lib/defaults/transitional.js"); /* harmony import */ var _helpers_toFormData_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../helpers/toFormData.js */ "./node_modules/axios/lib/helpers/toFormData.js"); /* harmony import */ var _helpers_toURLEncodedForm_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../helpers/toURLEncodedForm.js */ "./node_modules/axios/lib/helpers/toURLEncodedForm.js"); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony import */ var _helpers_formDataToJSON_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../helpers/formDataToJSON.js */ "./node_modules/axios/lib/helpers/formDataToJSON.js"); const own = (obj, key) => (obj != null && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(obj, key) ? obj[key] : undefined); /** * It takes a string, tries to parse it, and if it fails, it returns the stringified version * of the input * * @param {any} rawValue - The value to be stringified. * @param {Function} parser - A function that parses a string into a JavaScript object. * @param {Function} encoder - A function that takes a value and returns a string. * * @returns {string} A stringified version of the rawValue. */ function stringifySafely(rawValue, parser, encoder) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } } } return (encoder || JSON.stringify)(rawValue); } const defaults = { transitional: _transitional_js__WEBPACK_IMPORTED_MODULE_2__["default"], adapter: ['xhr', 'http', 'fetch'], transformRequest: [ function transformRequest(data, headers) { const contentType = headers.getContentType() || ''; const hasJSONContentType = contentType.indexOf('application/json') > -1; const isObjectPayload = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(data); if (isObjectPayload && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isHTMLForm(data)) { data = new FormData(data); } const isFormData = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFormData(data); if (isFormData) { return hasJSONContentType ? JSON.stringify((0,_helpers_formDataToJSON_js__WEBPACK_IMPORTED_MODULE_6__["default"])(data)) : data; } if ( _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArrayBuffer(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBuffer(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isStream(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFile(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBlob(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isReadableStream(data) ) { return data; } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArrayBufferView(data)) { return data.buffer; } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isURLSearchParams(data)) { headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); return data.toString(); } let isFileList; if (isObjectPayload) { const formSerializer = own(this, 'formSerializer'); if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { return (0,_helpers_toURLEncodedForm_js__WEBPACK_IMPORTED_MODULE_4__["default"])(data, formSerializer).toString(); } if ( (isFileList = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFileList(data)) || contentType.indexOf('multipart/form-data') > -1 ) { const env = own(this, 'env'); const _FormData = env && env.FormData; return (0,_helpers_toFormData_js__WEBPACK_IMPORTED_MODULE_3__["default"])( isFileList ? { 'files[]': data } : data, _FormData && new _FormData(), formSerializer ); } } if (isObjectPayload || hasJSONContentType) { headers.setContentType('application/json', false); return stringifySafely(data); } return data; }, ], transformResponse: [ function transformResponse(data) { const transitional = own(this, 'transitional') || defaults.transitional; const forcedJSONParsing = transitional && transitional.forcedJSONParsing; const responseType = own(this, 'responseType'); const JSONRequested = responseType === 'json'; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isResponse(data) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isReadableStream(data)) { return data; } if ( data && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(data) && ((forcedJSONParsing && !responseType) || JSONRequested) ) { const silentJSONParsing = transitional && transitional.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; try { return JSON.parse(data, own(this, 'parseReviver')); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].from(e, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_BAD_RESPONSE, this, null, own(this, 'response')); } throw e; } } } return data; }, ], /** * 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: _platform_index_js__WEBPACK_IMPORTED_MODULE_5__["default"].classes.FormData, Blob: _platform_index_js__WEBPACK_IMPORTED_MODULE_5__["default"].classes.Blob, }, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; }, headers: { common: { Accept: 'application/json, text/plain, */*', 'Content-Type': undefined, }, }, }; _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => { defaults.headers[method] = {}; }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (defaults); /***/ }, /***/ "./node_modules/axios/lib/defaults/transitional.js" /*!*********************************************************!*\ !*** ./node_modules/axios/lib/defaults/transitional.js ***! \*********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false, legacyInterceptorReqResOrdering: true, }); /***/ }, /***/ "./node_modules/axios/lib/env/data.js" /*!********************************************!*\ !*** ./node_modules/axios/lib/env/data.js ***! \********************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ VERSION: () => (/* binding */ VERSION) /* harmony export */ }); const VERSION = "1.16.1"; /***/ }, /***/ "./node_modules/axios/lib/helpers/AxiosURLSearchParams.js" /*!****************************************************************!*\ !*** ./node_modules/axios/lib/helpers/AxiosURLSearchParams.js ***! \****************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _toFormData_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./toFormData.js */ "./node_modules/axios/lib/helpers/toFormData.js"); /** * It encodes a string by replacing all characters that are not in the unreserved set with * their percent-encoded equivalents * * @param {string} str - The string to encode. * * @returns {string} The encoded string. */ function encode(str) { const charMap = { '!': '%21', "'": '%27', '(': '%28', ')': '%29', '~': '%7E', '%20': '+', }; return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) { return charMap[match]; }); } /** * It takes a params object and converts it to a FormData object * * @param {Object} params - The parameters to be converted to a FormData object. * @param {Object} options - The options object passed to the Axios constructor. * * @returns {void} */ function AxiosURLSearchParams(params, options) { this._pairs = []; params && (0,_toFormData_js__WEBPACK_IMPORTED_MODULE_0__["default"])(params, this, options); } const prototype = AxiosURLSearchParams.prototype; prototype.append = function append(name, value) { this._pairs.push([name, value]); }; prototype.toString = function toString(encoder) { const _encode = encoder ? function (value) { return encoder.call(this, value, encode); } : encode; return this._pairs .map(function each(pair) { return _encode(pair[0]) + '=' + _encode(pair[1]); }, '') .join('&'); }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AxiosURLSearchParams); /***/ }, /***/ "./node_modules/axios/lib/helpers/HttpStatusCode.js" /*!**********************************************************!*\ !*** ./node_modules/axios/lib/helpers/HttpStatusCode.js ***! \**********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); const HttpStatusCode = { Continue: 100, SwitchingProtocols: 101, Processing: 102, EarlyHints: 103, Ok: 200, Created: 201, Accepted: 202, NonAuthoritativeInformation: 203, NoContent: 204, ResetContent: 205, PartialContent: 206, MultiStatus: 207, AlreadyReported: 208, ImUsed: 226, MultipleChoices: 300, MovedPermanently: 301, Found: 302, SeeOther: 303, NotModified: 304, UseProxy: 305, Unused: 306, TemporaryRedirect: 307, PermanentRedirect: 308, BadRequest: 400, Unauthorized: 401, PaymentRequired: 402, Forbidden: 403, NotFound: 404, MethodNotAllowed: 405, NotAcceptable: 406, ProxyAuthenticationRequired: 407, RequestTimeout: 408, Conflict: 409, Gone: 410, LengthRequired: 411, PreconditionFailed: 412, PayloadTooLarge: 413, UriTooLong: 414, UnsupportedMediaType: 415, RangeNotSatisfiable: 416, ExpectationFailed: 417, ImATeapot: 418, MisdirectedRequest: 421, UnprocessableEntity: 422, Locked: 423, FailedDependency: 424, TooEarly: 425, UpgradeRequired: 426, PreconditionRequired: 428, TooManyRequests: 429, RequestHeaderFieldsTooLarge: 431, UnavailableForLegalReasons: 451, InternalServerError: 500, NotImplemented: 501, BadGateway: 502, ServiceUnavailable: 503, GatewayTimeout: 504, HttpVersionNotSupported: 505, VariantAlsoNegotiates: 506, InsufficientStorage: 507, LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511, WebServerIsDown: 521, ConnectionTimedOut: 522, OriginIsUnreachable: 523, TimeoutOccurred: 524, SslHandshakeFailed: 525, InvalidSslCertificate: 526, }; Object.entries(HttpStatusCode).forEach(([key, value]) => { HttpStatusCode[value] = key; }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (HttpStatusCode); /***/ }, /***/ "./node_modules/axios/lib/helpers/bind.js" /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ bind) /* harmony export */ }); /** * Create a bound version of a function with a specified `this` context * * @param {Function} fn - The function to bind * @param {*} thisArg - The value to be passed as the `this` parameter * @returns {Function} A new function that will call the original function with the specified `this` context */ function bind(fn, thisArg) { return function wrap() { return fn.apply(thisArg, arguments); }; } /***/ }, /***/ "./node_modules/axios/lib/helpers/buildURL.js" /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ buildURL), /* harmony export */ encode: () => (/* binding */ encode) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _helpers_AxiosURLSearchParams_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../helpers/AxiosURLSearchParams.js */ "./node_modules/axios/lib/helpers/AxiosURLSearchParams.js"); /** * It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with * their plain counterparts (`:`, `$`, `,`, `+`). * * @param {string} val The value to be encoded. * * @returns {string} The encoded value. */ function encode(val) { return encodeURIComponent(val) .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ',') .replace(/%20/g, '+'); } /** * 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 * @param {?(object|Function)} options * * @returns {string} The formatted url */ function buildURL(url, params, options) { if (!params) { return url; } const _encode = (options && options.encode) || encode; const _options = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(options) ? { serialize: options, } : options; const serializeFn = _options && _options.serialize; let serializedParams; if (serializeFn) { serializedParams = serializeFn(params, _options); } else { serializedParams = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isURLSearchParams(params) ? params.toString() : new _helpers_AxiosURLSearchParams_js__WEBPACK_IMPORTED_MODULE_1__["default"](params, _options).toString(_encode); } if (serializedParams) { const hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; } /***/ }, /***/ "./node_modules/axios/lib/helpers/combineURLs.js" /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ combineURLs) /* harmony export */ }); /** * 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 */ function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; } /***/ }, /***/ "./node_modules/axios/lib/helpers/composeSignals.js" /*!**********************************************************!*\ !*** ./node_modules/axios/lib/helpers/composeSignals.js ***! \**********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../cancel/CanceledError.js */ "./node_modules/axios/lib/cancel/CanceledError.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); const composeSignals = (signals, timeout) => { signals = signals ? signals.filter(Boolean) : []; if (!timeout && !signals.length) { return; } const controller = new AbortController(); let aborted = false; const onabort = function (reason) { if (!aborted) { aborted = true; unsubscribe(); const err = reason instanceof Error ? reason : this.reason; controller.abort( err instanceof _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"] ? err : new _cancel_CanceledError_js__WEBPACK_IMPORTED_MODULE_0__["default"](err instanceof Error ? err.message : err) ); } }; let timer = timeout && setTimeout(() => { timer = null; onabort(new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"](`timeout of ${timeout}ms exceeded`, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ETIMEDOUT)); }, timeout); const unsubscribe = () => { if (!signals) { return; } timer && clearTimeout(timer); timer = null; signals.forEach((signal) => { signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); }); signals = null; }; signals.forEach((signal) => signal.addEventListener('abort', onabort)); const { signal } = controller; signal.unsubscribe = () => _utils_js__WEBPACK_IMPORTED_MODULE_2__["default"].asap(unsubscribe); return signal; }; /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (composeSignals); /***/ }, /***/ "./node_modules/axios/lib/helpers/cookies.js" /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_platform_index_js__WEBPACK_IMPORTED_MODULE_1__["default"].hasStandardBrowserEnv ? // Standard browser envs support document.cookie { write(name, value, expires, path, domain, secure, sameSite) { if (typeof document === 'undefined') return; const cookie = [`${name}=${encodeURIComponent(value)}`]; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isNumber(expires)) { cookie.push(`expires=${new Date(expires).toUTCString()}`); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(path)) { cookie.push(`path=${path}`); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(domain)) { cookie.push(`domain=${domain}`); } if (secure === true) { cookie.push('secure'); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(sameSite)) { cookie.push(`SameSite=${sameSite}`); } document.cookie = cookie.join('; '); }, read(name) { if (typeof document === 'undefined') return null; // Match name=value by splitting on the semicolon separator instead of building a // RegExp from `name` — interpolating an unescaped string into a RegExp would let // metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or // match the wrong cookie. Browsers may serialize cookie pairs as either ";" or // "; ", so ignore optional whitespace before each cookie name. const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].replace(/^\s+/, ''); const eq = cookie.indexOf('='); if (eq !== -1 && cookie.slice(0, eq) === name) { return decodeURIComponent(cookie.slice(eq + 1)); } } return null; }, remove(name) { this.write(name, '', Date.now() - 86400000, '/'); }, } : // Non-standard browser env (web workers, react-native) lack needed support. { write() {}, read() { return null; }, remove() {}, }); /***/ }, /***/ "./node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js" /*!***********************************************************************!*\ !*** ./node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js ***! \***********************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ estimateDataURLDecodedBytes) /* harmony export */ }); /** * Estimate decoded byte length of a data:// URL *without* allocating large buffers. * - For base64: compute exact decoded size using length and padding; * handle %XX at the character-count level (no string allocation). * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound. * * @param {string} url * @returns {number} */ function estimateDataURLDecodedBytes(url) { if (!url || typeof url !== 'string') return 0; if (!url.startsWith('data:')) return 0; const comma = url.indexOf(','); if (comma < 0) return 0; const meta = url.slice(5, comma); const body = url.slice(comma + 1); const isBase64 = /;base64/i.test(meta); if (isBase64) { let effectiveLen = body.length; const len = body.length; // cache length for (let i = 0; i < len; i++) { if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { const a = body.charCodeAt(i + 1); const b = body.charCodeAt(i + 2); const isHex = ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) && ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)); if (isHex) { effectiveLen -= 2; i += 2; } } } let pad = 0; let idx = len - 1; const tailIsPct3D = (j) => j >= 2 && body.charCodeAt(j - 2) === 37 && // '%' body.charCodeAt(j - 1) === 51 && // '3' (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' if (idx >= 0) { if (body.charCodeAt(idx) === 61 /* '=' */) { pad++; idx--; } else if (tailIsPct3D(idx)) { pad++; idx -= 3; } } if (pad === 1 && idx >= 0) { if (body.charCodeAt(idx) === 61 /* '=' */) { pad++; } else if (tailIsPct3D(idx)) { pad++; } } const groups = Math.floor(effectiveLen / 4); const bytes = groups * 3 - (pad || 0); return bytes > 0 ? bytes : 0; } if (typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function') { return Buffer.byteLength(body, 'utf8'); } // Compute UTF-8 byte length directly from UTF-16 code units without allocating // a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies). // Using body.length here would undercount non-ASCII (e.g. '€' is 1 code unit // but 3 UTF-8 bytes). let bytes = 0; for (let i = 0, len = body.length; i < len; i++) { const c = body.charCodeAt(i); if (c < 0x80) { bytes += 1; } else if (c < 0x800) { bytes += 2; } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) { const next = body.charCodeAt(i + 1); if (next >= 0xdc00 && next <= 0xdfff) { bytes += 4; i++; } else { bytes += 3; } } else { bytes += 3; } } return bytes; } /***/ }, /***/ "./node_modules/axios/lib/helpers/formDataToJSON.js" /*!**********************************************************!*\ !*** ./node_modules/axios/lib/helpers/formDataToJSON.js ***! \**********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /** * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] * * @param {string} name - The name of the property to get. * * @returns An array of strings. */ function parsePropPath(name) { // foo[x][y][z] // foo.x.y.z // foo-x-y-z // foo x y z return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].matchAll(/\w+|\[(\w*)]/g, name).map((match) => { return match[0] === '[]' ? '' : match[1] || match[0]; }); } /** * Convert an array to an object. * * @param {Array} arr - The array to convert to an object. * * @returns An object with the same keys and values as the array. */ function arrayToObject(arr) { const obj = {}; const keys = Object.keys(arr); let i; const len = keys.length; let key; for (i = 0; i < len; i++) { key = keys[i]; obj[key] = arr[key]; } return obj; } /** * It takes a FormData object and returns a JavaScript object * * @param {string} formData The FormData object to convert to JSON. * * @returns {Object | null} The converted object. */ function formDataToJSON(formData) { function buildPath(path, value, target, index) { let name = path[index++]; if (name === '__proto__') return true; const isNumericKey = Number.isFinite(+name); const isLast = index >= path.length; name = !name && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(target) ? target.length : name; if (isLast) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(target, name)) { target[name] = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(target[name]) ? target[name].concat(value) : [target[name], value]; } else { target[name] = value; } return !isNumericKey; } if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasOwnProp(target, name) || !_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(target[name])) { target[name] = []; } const result = buildPath(path, value, target[name], index); if (result && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(target[name])) { target[name] = arrayToObject(target[name]); } return !isNumericKey; } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFormData(formData) && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(formData.entries)) { const obj = {}; _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEachEntry(formData, (name, value) => { buildPath(parsePropPath(name), value, obj, 0); }); return obj; } return null; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (formDataToJSON); /***/ }, /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js" /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ isAbsoluteURL) /* harmony export */ }); /** * 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 */ function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" 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. if (typeof url !== 'string') { return false; } return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } /***/ }, /***/ "./node_modules/axios/lib/helpers/isAxiosError.js" /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***! \********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ isAxiosError) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /** * 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 */ function isAxiosError(payload) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(payload) && payload.isAxiosError === true; } /***/ }, /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js" /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { url = new URL(url, _platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].origin); return ( origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port) ); })( new URL(_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].origin), _platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].navigator && /(msie|trident)/i.test(_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].navigator.userAgent) ) : () => true); /***/ }, /***/ "./node_modules/axios/lib/helpers/null.js" /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/null.js ***! \************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); // eslint-disable-next-line strict /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (null); /***/ }, /***/ "./node_modules/axios/lib/helpers/parseHeaders.js" /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); // RawAxiosHeaders whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers const ignoreDuplicateOf = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toObjectSet([ '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} rawHeaders Headers needing to be parsed * * @returns {Object} Headers parsed into an object */ /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((rawHeaders) => { const parsed = {}; let key; let val; let i; rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { i = line.indexOf(':'); key = line.substring(0, i).trim().toLowerCase(); val = line.substring(i + 1).trim(); if (!key || (parsed[key] && ignoreDuplicateOf[key])) { return; } if (key === 'set-cookie') { if (parsed[key]) { parsed[key].push(val); } else { parsed[key] = [val]; } } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; }); (Object.getOwnPropertyDescriptor(__WEBPACK_DEFAULT_EXPORT__, "name") || {}).writable || Object.defineProperty(__WEBPACK_DEFAULT_EXPORT__, "name", { value: "default", configurable: true }); /***/ }, /***/ "./node_modules/axios/lib/helpers/parseProtocol.js" /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseProtocol.js ***! \*********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ parseProtocol) /* harmony export */ }); function parseProtocol(url) { const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url); return (match && match[1]) || ''; } /***/ }, /***/ "./node_modules/axios/lib/helpers/progressEventReducer.js" /*!****************************************************************!*\ !*** ./node_modules/axios/lib/helpers/progressEventReducer.js ***! \****************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ asyncDecorator: () => (/* binding */ asyncDecorator), /* harmony export */ progressEventDecorator: () => (/* binding */ progressEventDecorator), /* harmony export */ progressEventReducer: () => (/* binding */ progressEventReducer) /* harmony export */ }); /* harmony import */ var _speedometer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./speedometer.js */ "./node_modules/axios/lib/helpers/speedometer.js"); /* harmony import */ var _throttle_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./throttle.js */ "./node_modules/axios/lib/helpers/throttle.js"); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); const progressEventReducer = (listener, isDownloadStream, freq = 3) => { let bytesNotified = 0; const _speedometer = (0,_speedometer_js__WEBPACK_IMPORTED_MODULE_0__["default"])(50, 250); return (0,_throttle_js__WEBPACK_IMPORTED_MODULE_1__["default"])((e) => { if (!e || typeof e.loaded !== 'number') { return; } const rawLoaded = e.loaded; const total = e.lengthComputable ? e.total : undefined; const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded; const progressBytes = Math.max(0, loaded - bytesNotified); const rate = _speedometer(progressBytes); bytesNotified = Math.max(bytesNotified, loaded); const data = { loaded, total, progress: total ? loaded / total : undefined, bytes: progressBytes, rate: rate ? rate : undefined, estimated: rate && total ? (total - loaded) / rate : undefined, event: e, lengthComputable: total != null, [isDownloadStream ? 'download' : 'upload']: true, }; listener(data); }, freq); }; const progressEventDecorator = (total, throttled) => { const lengthComputable = total != null; return [ (loaded) => throttled[0]({ lengthComputable, total, loaded, }), throttled[1], ]; }; const asyncDecorator = (fn) => (...args) => _utils_js__WEBPACK_IMPORTED_MODULE_2__["default"].asap(() => fn(...args)); /***/ }, /***/ "./node_modules/axios/lib/helpers/resolveConfig.js" /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/resolveConfig.js ***! \*********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _isURLSameOrigin_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isURLSameOrigin.js */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); /* harmony import */ var _cookies_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./cookies.js */ "./node_modules/axios/lib/helpers/cookies.js"); /* harmony import */ var _core_buildFullPath_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../core/buildFullPath.js */ "./node_modules/axios/lib/core/buildFullPath.js"); /* harmony import */ var _core_mergeConfig_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../core/mergeConfig.js */ "./node_modules/axios/lib/core/mergeConfig.js"); /* harmony import */ var _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../core/AxiosHeaders.js */ "./node_modules/axios/lib/core/AxiosHeaders.js"); /* harmony import */ var _buildURL_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buildURL.js */ "./node_modules/axios/lib/helpers/buildURL.js"); const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length']; function setFormDataHeaders(headers, formHeaders, policy) { if (policy !== 'content-only') { headers.set(formHeaders); return; } Object.entries(formHeaders).forEach(([key, val]) => { if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) { headers.set(key, val); } }); } /** * Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern. * * @param {string} str The string to encode * * @returns {string} UTF-8 bytes as a Latin-1 string */ const encodeUTF8 = (str) => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)) ); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((config) => { const newConfig = (0,_core_mergeConfig_js__WEBPACK_IMPORTED_MODULE_5__["default"])({}, config); // Read only own properties to prevent prototype pollution gadgets // (e.g. Object.prototype.baseURL = 'https://evil.com'). const own = (key) => (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].hasOwnProp(newConfig, key) ? newConfig[key] : undefined); const data = own('data'); let withXSRFToken = own('withXSRFToken'); const xsrfHeaderName = own('xsrfHeaderName'); const xsrfCookieName = own('xsrfCookieName'); let headers = own('headers'); const auth = own('auth'); const baseURL = own('baseURL'); const allowAbsoluteUrls = own('allowAbsoluteUrls'); const url = own('url'); newConfig.headers = headers = _core_AxiosHeaders_js__WEBPACK_IMPORTED_MODULE_6__["default"].from(headers); newConfig.url = (0,_buildURL_js__WEBPACK_IMPORTED_MODULE_7__["default"])( (0,_core_buildFullPath_js__WEBPACK_IMPORTED_MODULE_4__["default"])(baseURL, url, allowAbsoluteUrls), config.params, config.paramsSerializer ); // HTTP basic authentication if (auth) { headers.set( 'Authorization', 'Basic ' + btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : '')) ); } if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isFormData(data)) { if (_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasStandardBrowserEnv || _platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasStandardBrowserWebWorkerEnv) { headers.setContentType(undefined); // browser handles it } else if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isFunction(data.getHeaders)) { // Node.js FormData (like form-data package) setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy')); } } // 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 (_platform_index_js__WEBPACK_IMPORTED_MODULE_0__["default"].hasStandardBrowserEnv) { if (_utils_js__WEBPACK_IMPORTED_MODULE_1__["default"].isFunction(withXSRFToken)) { withXSRFToken = withXSRFToken(newConfig); } // Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1) // and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking // the XSRF token cross-origin. const shouldSendXSRF = withXSRFToken === true || (withXSRFToken == null && (0,_isURLSameOrigin_js__WEBPACK_IMPORTED_MODULE_2__["default"])(newConfig.url)); if (shouldSendXSRF) { const xsrfValue = xsrfHeaderName && xsrfCookieName && _cookies_js__WEBPACK_IMPORTED_MODULE_3__["default"].read(xsrfCookieName); if (xsrfValue) { headers.set(xsrfHeaderName, xsrfValue); } } } return newConfig; }); (Object.getOwnPropertyDescriptor(__WEBPACK_DEFAULT_EXPORT__, "name") || {}).writable || Object.defineProperty(__WEBPACK_DEFAULT_EXPORT__, "name", { value: "default", configurable: true }); /***/ }, /***/ "./node_modules/axios/lib/helpers/sanitizeHeaderValue.js" /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/sanitizeHeaderValue.js ***! \***************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ sanitizeByteStringHeaderValue: () => (/* binding */ sanitizeByteStringHeaderValue), /* harmony export */ sanitizeHeaderValue: () => (/* binding */ sanitizeHeaderValue), /* harmony export */ toByteStringHeaderObject: () => (/* binding */ toByteStringHeaderObject) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); function trimSPorHTAB(str) { let start = 0; let end = str.length; while (start < end) { const code = str.charCodeAt(start); if (code !== 0x09 && code !== 0x20) { break; } start += 1; } while (end > start) { const code = str.charCodeAt(end - 1); if (code !== 0x09 && code !== 0x20) { break; } end -= 1; } return start === 0 && end === str.length ? str : str.slice(start, end); } // The control-code ranges are intentional: header sanitization strips C0/DEL bytes. // eslint-disable-next-line no-control-regex const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g'); // eslint-disable-next-line no-control-regex const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g'); function sanitizeValue(value, invalidChars) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(value)) { return value.map((item) => sanitizeValue(item, invalidChars)); } return trimSPorHTAB(String(value).replace(invalidChars, '')); } const sanitizeHeaderValue = (value) => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS); const sanitizeByteStringHeaderValue = (value) => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS); function toByteStringHeaderObject(headers) { const byteStringHeaders = Object.create(null); _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(headers.toJSON(), (value, header) => { byteStringHeaders[header] = sanitizeByteStringHeaderValue(value); }); return byteStringHeaders; } /***/ }, /***/ "./node_modules/axios/lib/helpers/speedometer.js" /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/speedometer.js ***! \*******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Calculate data maxRate * @param {Number} [samplesCount= 10] * @param {Number} [min= 1000] * @returns {Function} */ function speedometer(samplesCount, min) { samplesCount = samplesCount || 10; const bytes = new Array(samplesCount); const timestamps = new Array(samplesCount); let head = 0; let tail = 0; let firstSampleTS; min = min !== undefined ? min : 1000; return function push(chunkLength) { const now = Date.now(); const startedAt = timestamps[tail]; if (!firstSampleTS) { firstSampleTS = now; } bytes[head] = chunkLength; timestamps[head] = now; let i = tail; let bytesCount = 0; while (i !== head) { bytesCount += bytes[i++]; i = i % samplesCount; } head = (head + 1) % samplesCount; if (head === tail) { tail = (tail + 1) % samplesCount; } if (now - firstSampleTS < min) { return; } const passed = startedAt && now - startedAt; return passed ? Math.round((bytesCount * 1000) / passed) : undefined; }; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (speedometer); /***/ }, /***/ "./node_modules/axios/lib/helpers/spread.js" /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ spread) /* harmony export */ }); /** * 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) {} * const 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 spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; } /***/ }, /***/ "./node_modules/axios/lib/helpers/throttle.js" /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/throttle.js ***! \****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /** * Throttle decorator * @param {Function} fn * @param {Number} freq * @return {Function} */ function throttle(fn, freq) { let timestamp = 0; let threshold = 1000 / freq; let lastArgs; let timer; const invoke = (args, now = Date.now()) => { timestamp = now; lastArgs = null; if (timer) { clearTimeout(timer); timer = null; } fn(...args); }; const throttled = (...args) => { const now = Date.now(); const passed = now - timestamp; if (passed >= threshold) { invoke(args, now); } else { lastArgs = args; if (!timer) { timer = setTimeout(() => { timer = null; invoke(lastArgs); }, threshold - passed); } } }; const flush = () => lastArgs && invoke(lastArgs); return [throttled, flush]; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (throttle); /***/ }, /***/ "./node_modules/axios/lib/helpers/toFormData.js" /*!******************************************************!*\ !*** ./node_modules/axios/lib/helpers/toFormData.js ***! \******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); /* harmony import */ var _platform_node_classes_FormData_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/node/classes/FormData.js */ "./node_modules/axios/lib/helpers/null.js"); // temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored /** * Determines if the given thing is a array or js object. * * @param {string} thing - The object or array to be visited. * * @returns {boolean} */ function isVisitable(thing) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isPlainObject(thing) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(thing); } /** * It removes the brackets from the end of a string * * @param {string} key - The key of the parameter. * * @returns {string} the key without the brackets. */ function removeBrackets(key) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].endsWith(key, '[]') ? key.slice(0, -2) : key; } /** * It takes a path, a key, and a boolean, and returns a string * * @param {string} path - The path to the current key. * @param {string} key - The key of the current object being iterated over. * @param {string} dots - If true, the key will be rendered with dots instead of brackets. * * @returns {string} The path to the current key. */ function renderKey(path, key, dots) { if (!path) return key; return path .concat(key) .map(function each(token, i) { // eslint-disable-next-line no-param-reassign token = removeBrackets(token); return !dots && i ? '[' + token + ']' : token; }) .join(dots ? '.' : ''); } /** * If the array is an array and none of its elements are visitable, then it's a flat array. * * @param {Array} arr - The array to check * * @returns {boolean} */ function isFlatArray(arr) { return _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(arr) && !arr.some(isVisitable); } const predicates = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toFlatObject(_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"], {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); /** * Convert a data object to FormData * * @param {Object} obj * @param {?Object} [formData] * @param {?Object} [options] * @param {Function} [options.visitor] * @param {Boolean} [options.metaTokens = true] * @param {Boolean} [options.dots = false] * @param {?Boolean} [options.indexes = false] * * @returns {Object} **/ /** * It converts an object into a FormData object * * @param {Object} obj - The object to convert to form data. * @param {string} formData - The FormData object to append to. * @param {Object} options * * @returns */ function toFormData(obj, formData, options) { if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(obj)) { throw new TypeError('target must be an object'); } // eslint-disable-next-line no-param-reassign formData = formData || new (_platform_node_classes_FormData_js__WEBPACK_IMPORTED_MODULE_2__["default"] || FormData)(); // eslint-disable-next-line no-param-reassign options = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toFlatObject( options, { metaTokens: true, dots: false, indexes: false, }, false, function defined(option, source) { // eslint-disable-next-line no-eq-null,eqeqeq return !_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(source[option]); } ); const metaTokens = options.metaTokens; // eslint-disable-next-line no-use-before-define const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob); const maxDepth = options.maxDepth === undefined ? 100 : options.maxDepth; const useBlob = _Blob && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isSpecCompliantForm(formData); if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(visitor)) { throw new TypeError('visitor must be a function'); } function convertValue(value) { if (value === null) return ''; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isDate(value)) { return value.toISOString(); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBoolean(value)) { return value.toString(); } if (!useBlob && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBlob(value)) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]('Blob is not supported. Use a Buffer instead.'); } if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArrayBuffer(value) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isTypedArray(value)) { return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } return value; } /** * Default visitor. * * @param {*} value * @param {String|Number} key * @param {Array} path * @this {FormData} * * @returns {boolean} return true to visit the each prop of the value recursively */ function defaultVisitor(value, key, path) { let arr = value; if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isReactNative(formData) && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isReactNativeBlob(value)) { formData.append(renderKey(path, key, dots), convertValue(value)); return false; } if (value && !path && typeof value === 'object') { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].endsWith(key, '{}')) { // eslint-disable-next-line no-param-reassign key = metaTokens ? key : key.slice(0, -2); // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); } else if ( (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isArray(value) && isFlatArray(value)) || ((_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFileList(value) || _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].endsWith(key, '[]')) && (arr = _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].toArray(value))) ) { // eslint-disable-next-line no-param-reassign key = removeBrackets(key); arr.forEach(function each(el, index) { !(_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(el) || el === null) && formData.append( // eslint-disable-next-line no-nested-ternary indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el) ); }); return false; } } if (isVisitable(value)) { return true; } formData.append(renderKey(path, key, dots), convertValue(value)); return false; } const stack = []; const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, isVisitable, }); function build(value, path, depth = 0) { if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(value)) return; if (depth > maxDepth) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]( 'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_FORM_DATA_DEPTH_EXCEEDED ); } if (stack.indexOf(value) !== -1) { throw Error('Circular reference detected in ' + path.join('.')); } stack.push(value); _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].forEach(value, function each(el, key) { const result = !(_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isUndefined(el) || el === null) && visitor.call(formData, el, _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isString(key) ? key.trim() : key, path, exposedHelpers); if (result === true) { build(el, path ? path.concat(key) : [key], depth + 1); } }); stack.pop(); } if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isObject(obj)) { throw new TypeError('data must be an object'); } build(obj); return formData; } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (toFormData); /***/ }, /***/ "./node_modules/axios/lib/helpers/toURLEncodedForm.js" /*!************************************************************!*\ !*** ./node_modules/axios/lib/helpers/toURLEncodedForm.js ***! \************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ toURLEncodedForm) /* harmony export */ }); /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./node_modules/axios/lib/utils.js"); /* harmony import */ var _toFormData_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./toFormData.js */ "./node_modules/axios/lib/helpers/toFormData.js"); /* harmony import */ var _platform_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../platform/index.js */ "./node_modules/axios/lib/platform/index.js"); function toURLEncodedForm(data, options) { return (0,_toFormData_js__WEBPACK_IMPORTED_MODULE_1__["default"])(data, new _platform_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].classes.URLSearchParams(), { visitor: function (value, key, path, helpers) { if (_platform_index_js__WEBPACK_IMPORTED_MODULE_2__["default"].isNode && _utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isBuffer(value)) { this.append(key, value.toString('base64')); return false; } return helpers.defaultVisitor.apply(this, arguments); }, ...options, }); } /***/ }, /***/ "./node_modules/axios/lib/helpers/trackStream.js" /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/trackStream.js ***! \*******************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ readBytes: () => (/* binding */ readBytes), /* harmony export */ streamChunk: () => (/* binding */ streamChunk), /* harmony export */ trackStream: () => (/* binding */ trackStream) /* harmony export */ }); const streamChunk = function* (chunk, chunkSize) { let len = chunk.byteLength; if (!chunkSize || len < chunkSize) { yield chunk; return; } let pos = 0; let end; while (pos < len) { end = pos + chunkSize; yield chunk.slice(pos, end); pos = end; } }; const readBytes = async function* (iterable, chunkSize) { for await (const chunk of readStream(iterable)) { yield* streamChunk(chunk, chunkSize); } }; const readStream = async function* (stream) { if (stream[Symbol.asyncIterator]) { yield* stream; return; } const reader = stream.getReader(); try { for (;;) { const { done, value } = await reader.read(); if (done) { break; } yield value; } } finally { await reader.cancel(); } }; const trackStream = (stream, chunkSize, onProgress, onFinish) => { const iterator = readBytes(stream, chunkSize); let bytes = 0; let done; let _onFinish = (e) => { if (!done) { done = true; onFinish && onFinish(e); } }; return new ReadableStream( { async pull(controller) { try { const { done, value } = await iterator.next(); if (done) { _onFinish(); controller.close(); return; } let len = value.byteLength; if (onProgress) { let loadedBytes = (bytes += len); onProgress(loadedBytes); } controller.enqueue(new Uint8Array(value)); } catch (err) { _onFinish(err); throw err; } }, cancel(reason) { _onFinish(reason); return iterator.return(); }, }, { highWaterMark: 2, } ); }; /***/ }, /***/ "./node_modules/axios/lib/helpers/validator.js" /*!*****************************************************!*\ !*** ./node_modules/axios/lib/helpers/validator.js ***! \*****************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _env_data_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../env/data.js */ "./node_modules/axios/lib/env/data.js"); /* harmony import */ var _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../core/AxiosError.js */ "./node_modules/axios/lib/core/AxiosError.js"); const validators = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { validators[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); const deprecatedWarnings = {}; /** * 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' + _env_data_js__WEBPACK_IMPORTED_MODULE_0__.VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '') ); } // eslint-disable-next-line func-names return (value, opt, opts) => { if (validator === false) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_DEPRECATED ); } 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 validator ? validator(value, opt, opts) : true; }; }; validators.spelling = function spelling(correctSpelling) { return (value, opt) => { // eslint-disable-next-line no-console console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); return true; }; }; /** * Assert object's properties type * * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown * * @returns {object} */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]('options must be an object', _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; while (i-- > 0) { const opt = keys[i]; // Use hasOwnProperty so a polluted Object.prototype. cannot supply // a non-function validator and cause a TypeError. const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined; if (validator) { const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]( 'option ' + opt + ' must be ' + result, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_BAD_OPTION_VALUE ); } continue; } if (allowUnknown !== true) { throw new _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"]('Unknown option ' + opt, _core_AxiosError_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERR_BAD_OPTION); } } } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ assertOptions, validators, }); /***/ }, /***/ "./node_modules/axios/lib/platform/browser/classes/Blob.js" /*!*****************************************************************!*\ !*** ./node_modules/axios/lib/platform/browser/classes/Blob.js ***! \*****************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (typeof Blob !== 'undefined' ? Blob : null); /***/ }, /***/ "./node_modules/axios/lib/platform/browser/classes/FormData.js" /*!*********************************************************************!*\ !*** ./node_modules/axios/lib/platform/browser/classes/FormData.js ***! \*********************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (typeof FormData !== 'undefined' ? FormData : null); /***/ }, /***/ "./node_modules/axios/lib/platform/browser/classes/URLSearchParams.js" /*!****************************************************************************!*\ !*** ./node_modules/axios/lib/platform/browser/classes/URLSearchParams.js ***! \****************************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _helpers_AxiosURLSearchParams_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../helpers/AxiosURLSearchParams.js */ "./node_modules/axios/lib/helpers/AxiosURLSearchParams.js"); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (typeof URLSearchParams !== 'undefined' ? URLSearchParams : _helpers_AxiosURLSearchParams_js__WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }, /***/ "./node_modules/axios/lib/platform/browser/index.js" /*!**********************************************************!*\ !*** ./node_modules/axios/lib/platform/browser/index.js ***! \**********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _classes_URLSearchParams_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./classes/URLSearchParams.js */ "./node_modules/axios/lib/platform/browser/classes/URLSearchParams.js"); /* harmony import */ var _classes_FormData_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./classes/FormData.js */ "./node_modules/axios/lib/platform/browser/classes/FormData.js"); /* harmony import */ var _classes_Blob_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./classes/Blob.js */ "./node_modules/axios/lib/platform/browser/classes/Blob.js"); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ isBrowser: true, classes: { URLSearchParams: _classes_URLSearchParams_js__WEBPACK_IMPORTED_MODULE_0__["default"], FormData: _classes_FormData_js__WEBPACK_IMPORTED_MODULE_1__["default"], Blob: _classes_Blob_js__WEBPACK_IMPORTED_MODULE_2__["default"], }, protocols: ['http', 'https', 'file', 'blob', 'url', 'data'], }); /***/ }, /***/ "./node_modules/axios/lib/platform/common/utils.js" /*!*********************************************************!*\ !*** ./node_modules/axios/lib/platform/common/utils.js ***! \*********************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ hasBrowserEnv: () => (/* binding */ hasBrowserEnv), /* harmony export */ hasStandardBrowserEnv: () => (/* binding */ hasStandardBrowserEnv), /* harmony export */ hasStandardBrowserWebWorkerEnv: () => (/* binding */ hasStandardBrowserWebWorkerEnv), /* harmony export */ navigator: () => (/* binding */ _navigator), /* harmony export */ origin: () => (/* binding */ origin) /* harmony export */ }); const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; const _navigator = (typeof navigator === 'object' && navigator) || undefined; /** * 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' * * @returns {boolean} */ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); /** * Determine if we're running in a standard browser webWorker environment * * Although the `isStandardBrowserEnv` method indicates that * `allows axios to run in a web worker`, the WebWorker will still be * filtered out due to its judgment standard * `typeof window !== 'undefined' && typeof document !== 'undefined'`. * This leads to a problem when axios post `FormData` in webWorker */ const hasStandardBrowserWebWorkerEnv = (() => { return ( typeof WorkerGlobalScope !== 'undefined' && // eslint-disable-next-line no-undef self instanceof WorkerGlobalScope && typeof self.importScripts === 'function' ); })(); const origin = (hasBrowserEnv && window.location.href) || 'http://localhost'; /***/ }, /***/ "./node_modules/axios/lib/platform/index.js" /*!**************************************************!*\ !*** ./node_modules/axios/lib/platform/index.js ***! \**************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _node_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node/index.js */ "./node_modules/axios/lib/platform/browser/index.js"); /* harmony import */ var _common_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common/utils.js */ "./node_modules/axios/lib/platform/common/utils.js"); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ ..._common_utils_js__WEBPACK_IMPORTED_MODULE_1__, ..._node_index_js__WEBPACK_IMPORTED_MODULE_0__["default"], }); /***/ }, /***/ "./node_modules/axios/lib/utils.js" /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var _helpers_bind_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers/bind.js */ "./node_modules/axios/lib/helpers/bind.js"); // utils is a library of generic helper functions non-specific to axios const { toString } = Object.prototype; const { getPrototypeOf } = Object; const { iterator, toStringTag } = Symbol; const kindOf = ((cache) => (thing) => { const str = toString.call(thing); return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); })(Object.create(null)); const kindOfTest = (type) => { type = type.toLowerCase(); return (thing) => kindOf(thing) === type; }; const typeOfTest = (type) => (thing) => typeof thing === type; /** * Determine if a value is a non-null object * * @param {Object} val The value to test * * @returns {boolean} True if value is an Array, otherwise false */ const { isArray } = Array; /** * Determine if a value is undefined * * @param {*} val The value to test * * @returns {boolean} True if the value is undefined, otherwise false */ const isUndefined = typeOfTest('undefined'); /** * Determine if a value is a Buffer * * @param {*} 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) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val) ); } /** * Determine if a value is an ArrayBuffer * * @param {*} val The value to test * * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ const isArrayBuffer = kindOfTest('ArrayBuffer'); /** * Determine if a value is a view on an ArrayBuffer * * @param {*} val The value to test * * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { let 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 {*} val The value to test * * @returns {boolean} True if value is a String, otherwise false */ const isString = typeOfTest('string'); /** * Determine if a value is a Function * * @param {*} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ const isFunction = typeOfTest('function'); /** * Determine if a value is a Number * * @param {*} val The value to test * * @returns {boolean} True if value is a Number, otherwise false */ const isNumber = typeOfTest('number'); /** * Determine if a value is an Object * * @param {*} thing The value to test * * @returns {boolean} True if value is an Object, otherwise false */ const isObject = (thing) => thing !== null && typeof thing === 'object'; /** * Determine if a value is a Boolean * * @param {*} thing The value to test * @returns {boolean} True if value is a Boolean, otherwise false */ const isBoolean = (thing) => thing === true || thing === false; /** * Determine if a value is a plain Object * * @param {*} val The value to test * * @returns {boolean} True if value is a plain Object, otherwise false */ const isPlainObject = (val) => { if (kindOf(val) !== 'object') { return false; } const prototype = getPrototypeOf(val); return ( (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val) ); }; /** * Determine if a value is an empty object (safely handles Buffers) * * @param {*} val The value to test * * @returns {boolean} True if value is an empty object, otherwise false */ const isEmptyObject = (val) => { // Early return for non-objects or Buffers to prevent RangeError if (!isObject(val) || isBuffer(val)) { return false; } try { return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; } catch (e) { // Fallback for any other objects that might cause RangeError with Object.keys() return false; } }; /** * Determine if a value is a Date * * @param {*} val The value to test * * @returns {boolean} True if value is a Date, otherwise false */ const isDate = kindOfTest('Date'); /** * Determine if a value is a File * * @param {*} val The value to test * * @returns {boolean} True if value is a File, otherwise false */ const isFile = kindOfTest('File'); /** * Determine if a value is a React Native Blob * React Native "blob": an object with a `uri` attribute. Optionally, it can * also have a `name` and `type` attribute to specify filename and content type * * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71 * * @param {*} value The value to test * * @returns {boolean} True if value is a React Native Blob, otherwise false */ const isReactNativeBlob = (value) => { return !!(value && typeof value.uri !== 'undefined'); }; /** * Determine if environment is React Native * ReactNative `FormData` has a non-standard `getParts()` method * * @param {*} formData The formData to test * * @returns {boolean} True if environment is React Native, otherwise false */ const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined'; /** * Determine if a value is a Blob * * @param {*} val The value to test * * @returns {boolean} True if value is a Blob, otherwise false */ const isBlob = kindOfTest('Blob'); /** * Determine if a value is a FileList * * @param {*} val The value to test * * @returns {boolean} True if value is a FileList, otherwise false */ const isFileList = kindOfTest('FileList'); /** * Determine if a value is a Stream * * @param {*} val The value to test * * @returns {boolean} True if value is a Stream, otherwise false */ const isStream = (val) => isObject(val) && isFunction(val.pipe); /** * Determine if a value is a FormData * * @param {*} thing The value to test * * @returns {boolean} True if value is an FormData, otherwise false */ function getGlobal() { if (typeof globalThis !== 'undefined') return globalThis; if (typeof self !== 'undefined') return self; if (typeof window !== 'undefined') return window; if (typeof __webpack_require__.g !== 'undefined') return __webpack_require__.g; return {}; } const G = getGlobal(); const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined; const isFormData = (thing) => { if (!thing) return false; if (FormDataCtor && thing instanceof FormDataCtor) return true; // Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData. const proto = getPrototypeOf(thing); if (!proto || proto === Object.prototype) return false; if (!isFunction(thing.append)) return false; const kind = kindOf(thing); return ( kind === 'formdata' || // detect form-data instance (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') ); }; /** * Determine if a value is a URLSearchParams object * * @param {*} val The value to test * * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ const isURLSearchParams = kindOfTest('URLSearchParams'); const [isReadableStream, isRequest, isResponse, isHeaders] = [ 'ReadableStream', 'Request', 'Response', 'Headers', ].map(kindOfTest); /** * 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 */ const trim = (str) => { return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; /** * 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 * * @param {Object} [options] * @param {Boolean} [options.allOwnKeys = false] * @returns {any} */ function forEach(obj, fn, { allOwnKeys = false } = {}) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } let i; let l; // 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 (i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Buffer check if (isBuffer(obj)) { return; } // Iterate over object keys const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); const len = keys.length; let key; for (i = 0; i < len; i++) { key = keys[i]; fn.call(null, obj[key], key, obj); } } } /** * Finds a key in an object, case-insensitive, returning the actual key name. * Returns null if the object is a Buffer or if no match is found. * * @param {Object} obj - The object to search. * @param {string} key - The key to find (case-insensitive). * @returns {?string} The actual key name if found, otherwise null. */ function findKey(obj, key) { if (isBuffer(obj)) { return null; } key = key.toLowerCase(); const keys = Object.keys(obj); let i = keys.length; let _key; while (i-- > 0) { _key = keys[i]; if (key === _key.toLowerCase()) { return _key; } } return null; } const _global = (() => { /*eslint no-undef:0*/ if (typeof globalThis !== 'undefined') return globalThis; return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : __webpack_require__.g; })(); const isContextDefined = (context) => !isUndefined(context) && context !== _global; /** * 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 * const 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(...objs) { const { caseless, skipUndefined } = (isContextDefined(this) && this) || {}; const result = {}; const assignValue = (val, key) => { // Skip dangerous property names to prevent prototype pollution if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return; } const targetKey = (caseless && findKey(result, key)) || key; // Read via own-prop only — a bare `result[targetKey]` walks the prototype // chain, so a polluted Object.prototype value could surface here and get // copied into the merged result. const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined; if (isPlainObject(existing) && isPlainObject(val)) { result[targetKey] = merge(existing, val); } else if (isPlainObject(val)) { result[targetKey] = merge({}, val); } else if (isArray(val)) { result[targetKey] = val.slice(); } else if (!skipUndefined || !isUndefined(val)) { result[targetKey] = val; } }; for (let i = 0, l = objs.length; i < l; i++) { objs[i] && forEach(objs[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 * * @param {Object} [options] * @param {Boolean} [options.allOwnKeys] * @returns {Object} The resulting value of object a */ const extend = (a, b, thisArg, { allOwnKeys } = {}) => { forEach( b, (val, key) => { if (thisArg && isFunction(val)) { Object.defineProperty(a, key, { // Null-proto descriptor so a polluted Object.prototype.get cannot // hijack defineProperty's accessor-vs-data resolution. __proto__: null, value: (0,_helpers_bind_js__WEBPACK_IMPORTED_MODULE_0__["default"])(val, thisArg), writable: true, enumerable: true, configurable: true, }); } else { Object.defineProperty(a, key, { __proto__: null, value: val, writable: true, enumerable: true, configurable: true, }); } }, { allOwnKeys } ); return a; }; /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * * @returns {string} content value without BOM */ const 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] * * @returns {void} */ const inherits = (constructor, superConstructor, props, descriptors) => { constructor.prototype = Object.create(superConstructor.prototype, descriptors); Object.defineProperty(constructor.prototype, 'constructor', { __proto__: null, value: constructor, writable: true, enumerable: false, configurable: true, }); Object.defineProperty(constructor, 'super', { __proto__: null, value: superConstructor.prototype, }); 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|Boolean} [filter] * @param {Function} [propFilter] * * @returns {Object} */ const toFlatObject = (sourceObj, destObj, filter, propFilter) => { let props; let i; let prop; const merged = {}; destObj = destObj || {}; // eslint-disable-next-line no-eq-null,eqeqeq if (sourceObj == null) return destObj; do { props = Object.getOwnPropertyNames(sourceObj); i = props.length; while (i-- > 0) { prop = props[i]; if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = filter !== false && 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} */ const endsWith = (str, searchString, position) => { str = String(str); if (position === undefined || position > str.length) { position = str.length; } position -= searchString.length; const lastIndex = str.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; /** * Returns new array from array like object or null if failed * * @param {*} [thing] * * @returns {?Array} */ const toArray = (thing) => { if (!thing) return null; if (isArray(thing)) return thing; let i = thing.length; if (!isNumber(i)) return null; const arr = new Array(i); while (i-- > 0) { arr[i] = thing[i]; } return arr; }; /** * Checking if the Uint8Array exists and if it does, it returns a function that checks if the * thing passed in is an instance of Uint8Array * * @param {TypedArray} * * @returns {Array} */ // eslint-disable-next-line func-names const isTypedArray = ((TypedArray) => { // eslint-disable-next-line func-names return (thing) => { return TypedArray && thing instanceof TypedArray; }; })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); /** * For each entry in the object, call the function with the key and value. * * @param {Object} obj - The object to iterate over. * @param {Function} fn - The function to call for each entry. * * @returns {void} */ const forEachEntry = (obj, fn) => { const generator = obj && obj[iterator]; const _iterator = generator.call(obj); let result; while ((result = _iterator.next()) && !result.done) { const pair = result.value; fn.call(obj, pair[0], pair[1]); } }; /** * It takes a regular expression and a string, and returns an array of all the matches * * @param {string} regExp - The regular expression to match against. * @param {string} str - The string to search. * * @returns {Array} */ const matchAll = (regExp, str) => { let matches; const arr = []; while ((matches = regExp.exec(str)) !== null) { arr.push(matches); } return arr; }; /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ const isHTMLForm = kindOfTest('HTMLFormElement'); const toCamelCase = (str) => { return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { return p1.toUpperCase() + p2; }); }; /* Creating a function that will check if an object has a property. */ const hasOwnProperty = ( ({ hasOwnProperty }) => (obj, prop) => hasOwnProperty.call(obj, prop) )(Object.prototype); /** * Determine if a value is a RegExp object * * @param {*} val The value to test * * @returns {boolean} True if value is a RegExp object, otherwise false */ const isRegExp = kindOfTest('RegExp'); const reduceDescriptors = (obj, reducer) => { const descriptors = Object.getOwnPropertyDescriptors(obj); const reducedDescriptors = {}; forEach(descriptors, (descriptor, name) => { let ret; if ((ret = reducer(descriptor, name, obj)) !== false) { reducedDescriptors[name] = ret || descriptor; } }); Object.defineProperties(obj, reducedDescriptors); }; /** * Makes all methods read-only * @param {Object} obj */ const freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { // skip restricted props in strict mode if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) { return false; } const value = obj[name]; if (!isFunction(value)) return; descriptor.enumerable = false; if ('writable' in descriptor) { descriptor.writable = false; return; } if (!descriptor.set) { descriptor.set = () => { throw Error("Can not rewrite read-only method '" + name + "'"); }; } }); }; /** * Converts an array or a delimited string into an object set with values as keys and true as values. * Useful for fast membership checks. * * @param {Array|string} arrayOrString - The array or string to convert. * @param {string} delimiter - The delimiter to use if input is a string. * @returns {Object} An object with keys from the array or string, values set to true. */ const toObjectSet = (arrayOrString, delimiter) => { const obj = {}; const define = (arr) => { arr.forEach((value) => { obj[value] = true; }); }; isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); return obj; }; const noop = () => {}; const toFiniteNumber = (value, defaultValue) => { return value != null && Number.isFinite((value = +value)) ? value : defaultValue; }; /** * If the thing is a FormData object, return true, otherwise return false. * * @param {unknown} thing - The thing to check. * * @returns {boolean} */ function isSpecCompliantForm(thing) { return !!( thing && isFunction(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator] ); } /** * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers. * * @param {Object} obj - The object to convert. * @returns {Object} The JSON-compatible object. */ const toJSONObject = (obj) => { const visited = new WeakSet(); const visit = (source) => { if (isObject(source)) { if (visited.has(source)) { return; } //Buffer check if (isBuffer(source)) { return source; } if (!('toJSON' in source)) { // add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230). visited.add(source); const target = isArray(source) ? [] : {}; forEach(source, (value, key) => { const reducedValue = visit(value); !isUndefined(reducedValue) && (target[key] = reducedValue); }); visited.delete(source); return target; } } return source; }; return visit(obj); }; /** * Determines if a value is an async function. * * @param {*} thing - The value to test. * @returns {boolean} True if value is an async function, otherwise false. */ const isAsyncFn = kindOfTest('AsyncFunction'); /** * Determines if a value is thenable (has then and catch methods). * * @param {*} thing - The value to test. * @returns {boolean} True if value is thenable, otherwise false. */ const isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); // original code // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 /** * Provides a cross-platform setImmediate implementation. * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout. * * @param {boolean} setImmediateSupported - Whether setImmediate is supported. * @param {boolean} postMessageSupported - Whether postMessage is supported. * @returns {Function} A function to schedule a callback asynchronously. */ const _setImmediate = ((setImmediateSupported, postMessageSupported) => { if (setImmediateSupported) { return setImmediate; } return postMessageSupported ? ((token, callbacks) => { _global.addEventListener( 'message', ({ source, data }) => { if (source === _global && data === token) { callbacks.length && callbacks.shift()(); } }, false ); return (cb) => { callbacks.push(cb); _global.postMessage(token, '*'); }; })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); })(typeof setImmediate === 'function', isFunction(_global.postMessage)); /** * Schedules a microtask or asynchronous callback as soon as possible. * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate. * * @type {Function} */ const asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : (typeof process !== 'undefined' && process.nextTick) || _setImmediate; // ********************* const isIterable = (thing) => thing != null && isFunction(thing[iterator]); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ isArray, isArrayBuffer, isBuffer, isFormData, isArrayBufferView, isString, isNumber, isBoolean, isObject, isPlainObject, isEmptyObject, isReadableStream, isRequest, isResponse, isHeaders, isUndefined, isDate, isFile, isReactNativeBlob, isReactNative, isBlob, isRegExp, isFunction, isStream, isURLSearchParams, isTypedArray, isFileList, forEach, merge, extend, trim, stripBOM, inherits, toFlatObject, kindOf, kindOfTest, endsWith, toArray, forEachEntry, matchAll, isHTMLForm, hasOwnProperty, hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection reduceDescriptors, freezeMethods, toObjectSet, toCamelCase, noop, toFiniteNumber, findKey, global: _global, isContextDefined, isSpecCompliantForm, toJSONObject, isAsyncFn, isThenable, setImmediate: _setImmediate, asap, isIterable, }); /***/ }, /***/ "./node_modules/dompurify/dist/purify.es.mjs" /*!***************************************************!*\ !*** ./node_modules/dompurify/dist/purify.es.mjs ***! \***************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ purify) /* harmony export */ }); /*! @license DOMPurify 3.4.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.3/LICENSE */ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = true, o = false; try { if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = true, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } const entries = Object.entries, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; let freeze = Object.freeze, seal = Object.seal, create = Object.create; // eslint-disable-line import/no-mutable-exports let _ref = typeof Reflect !== 'undefined' && Reflect, apply = _ref.apply, construct = _ref.construct; if (!freeze) { freeze = function freeze(x) { return x; }; } if (!seal) { seal = function seal(x) { return x; }; } if (!apply) { apply = function apply(func, thisArg) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return func.apply(thisArg, args); }; } if (!construct) { construct = function construct(Func) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return new Func(...args); }; } const arrayForEach = unapply(Array.prototype.forEach); const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); const arrayPop = unapply(Array.prototype.pop); const arrayPush = unapply(Array.prototype.push); const arraySplice = unapply(Array.prototype.splice); const arrayIsArray = Array.isArray; const stringToLowerCase = unapply(String.prototype.toLowerCase); const stringToString = unapply(String.prototype.toString); const stringMatch = unapply(String.prototype.match); const stringReplace = unapply(String.prototype.replace); const stringIndexOf = unapply(String.prototype.indexOf); const stringTrim = unapply(String.prototype.trim); const numberToString = unapply(Number.prototype.toString); const booleanToString = unapply(Boolean.prototype.toString); const bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString); const symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString); const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); const objectToString = unapply(Object.prototype.toString); const regExpTest = unapply(RegExp.prototype.test); const typeErrorCreate = unconstruct(TypeError); /** * Creates a new function that calls the given function with a specified thisArg and arguments. * * @param func - The function to be wrapped and called. * @returns A new function that calls the given function with a specified thisArg and arguments. */ function unapply(func) { return function (thisArg) { if (thisArg instanceof RegExp) { thisArg.lastIndex = 0; } for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return apply(func, thisArg, args); }; } /** * Creates a new function that constructs an instance of the given constructor function with the provided arguments. * * @param func - The constructor function to be wrapped and called. * @returns A new function that constructs an instance of the given constructor function with the provided arguments. */ function unconstruct(Func) { return function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return construct(Func, args); }; } /** * Add properties to a lookup table * * @param set - The set to which elements will be added. * @param array - The array containing elements to be added to the set. * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set. * @returns The modified set with added elements. */ function addToSet(set, array) { let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase; if (setPrototypeOf) { // Make 'in' and truthy checks like Boolean(set.constructor) // independent of any properties defined on Object.prototype. // Prevent prototype setters from intercepting set as a this value. setPrototypeOf(set, null); } if (!arrayIsArray(array)) { return set; } let l = array.length; while (l--) { let element = array[l]; if (typeof element === 'string') { const lcElement = transformCaseFunc(element); if (lcElement !== element) { // Config presets (e.g. tags.js, attrs.js) are immutable. if (!isFrozen(array)) { array[l] = lcElement; } element = lcElement; } } set[element] = true; } return set; } /** * Clean up an array to harden against CSPP * * @param array - The array to be cleaned. * @returns The cleaned version of the array */ function cleanArray(array) { for (let index = 0; index < array.length; index++) { const isPropertyExist = objectHasOwnProperty(array, index); if (!isPropertyExist) { array[index] = null; } } return array; } /** * Shallow clone an object * * @param object - The object to be cloned. * @returns A new object that copies the original. */ function clone(object) { const newObject = create(null); for (const _ref2 of entries(object)) { var _ref3 = _slicedToArray(_ref2, 2); const property = _ref3[0]; const value = _ref3[1]; const isPropertyExist = objectHasOwnProperty(object, property); if (isPropertyExist) { if (arrayIsArray(value)) { newObject[property] = cleanArray(value); } else if (value && typeof value === 'object' && value.constructor === Object) { newObject[property] = clone(value); } else { newObject[property] = value; } } } return newObject; } /** * Convert non-node values into strings without depending on direct property access. * * @param value - The value to stringify. * @returns A string representation of the provided value. */ function stringifyValue(value) { switch (typeof value) { case 'string': { return value; } case 'number': { return numberToString(value); } case 'boolean': { return booleanToString(value); } case 'bigint': { return bigintToString ? bigintToString(value) : '0'; } case 'symbol': { return symbolToString ? symbolToString(value) : 'Symbol()'; } case 'undefined': { return objectToString(value); } case 'function': case 'object': { if (value === null) { return objectToString(value); } const valueAsRecord = value; const valueToString = lookupGetter(valueAsRecord, 'toString'); if (typeof valueToString === 'function') { const stringified = valueToString(valueAsRecord); return typeof stringified === 'string' ? stringified : objectToString(stringified); } return objectToString(value); } default: { return objectToString(value); } } } /** * This method automatically checks if the prop is function or getter and behaves accordingly. * * @param object - The object to look up the getter function in its prototype chain. * @param prop - The property name for which to find the getter function. * @returns The getter function found in the prototype chain or a fallback function. */ function lookupGetter(object, prop) { while (object !== null) { const desc = getOwnPropertyDescriptor(object, prop); if (desc) { if (desc.get) { return unapply(desc.get); } if (typeof desc.value === 'function') { return unapply(desc.value); } } object = getPrototypeOf(object); } function fallbackValue() { return null; } return fallbackValue; } function isRegex(value) { try { regExpTest(value, ''); return true; } catch (_unused) { return false; } } const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default. // We still need to know them so that we can do namespace // checks properly in case one wants to add them to // allow-list. const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']); // Similarly to SVG, we want to know all MathML elements, // even those that we disallow by default. const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); const text = freeze(['#text']); const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']); const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); const MUSTACHE_EXPR = seal(/{{[\w\W]*|^[\w\W]*}}/g); const ERB_EXPR = seal(/<%[\w\W]*|^[\w\W]*%>/g); const TMPLIT_EXPR = seal(/\${[\w\W]*/g); const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape ); const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex ); const DOCTYPE_NAME = seal(/^html$/i); const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); /* eslint-disable @typescript-eslint/indent */ // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType const NODE_TYPE = { element: 1, text: 3, // Deprecated progressingInstruction: 7, comment: 8, document: 9}; const getGlobal = function getGlobal() { return typeof window === 'undefined' ? null : window; }; /** * Creates a no-op policy for internal use only. * Don't export this function outside this module! * @param trustedTypes The policy factory. * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix). * @return The policy created (or null, if Trusted Types * are not supported or creating the policy failed). */ const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) { if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') { return null; } // Allow the callers to control the unique policy name // by adding a data-tt-policy-suffix to the script element with the DOMPurify. // Policy creation with duplicate names throws in Trusted Types. let suffix = null; const ATTR_NAME = 'data-tt-policy-suffix'; if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { suffix = purifyHostElement.getAttribute(ATTR_NAME); } const policyName = 'dompurify' + (suffix ? '#' + suffix : ''); try { return trustedTypes.createPolicy(policyName, { createHTML(html) { return html; }, createScriptURL(scriptUrl) { return scriptUrl; } }); } catch (_) { // Policy creation failed (most likely another DOMPurify script has // already run). Skip creating the policy, as this will only cause errors // if TT are enforced. console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); return null; } }; const _createHooksMap = function _createHooksMap() { return { afterSanitizeAttributes: [], afterSanitizeElements: [], afterSanitizeShadowDOM: [], beforeSanitizeAttributes: [], beforeSanitizeElements: [], beforeSanitizeShadowDOM: [], uponSanitizeAttribute: [], uponSanitizeElement: [], uponSanitizeShadowNode: [] }; }; function createDOMPurify() { let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); const DOMPurify = root => createDOMPurify(root); DOMPurify.version = '3.4.3'; DOMPurify.removed = []; if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) { // Not running in a browser, provide a factory function // so that you can pass your own Window DOMPurify.isSupported = false; return DOMPurify; } let document = window.document; const originalDocument = document; const currentScript = originalDocument.currentScript; const DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window.HTMLFormElement, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes; const ElementPrototype = Element.prototype; const cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); const remove = lookupGetter(ElementPrototype, 'remove'); const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); const getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); const getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a // new document created via createHTMLDocument. As per the spec // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) // a new empty registry is used when creating a template contents owner // document, so we use that as our parent document to ensure nothing // is inherited. if (typeof HTMLTemplateElement === 'function') { const template = document.createElement('template'); if (template.content && template.content.ownerDocument) { document = template.content.ownerDocument; } } let trustedTypesPolicy; let emptyHTML = ''; const _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName; const importNode = originalDocument.importNode; let hooks = _createHooksMap(); /** * Expose whether this browser supports running the full DOMPurify. */ DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined; const MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, TMPLIT_EXPR$1 = TMPLIT_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE, CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT; let IS_ALLOWED_URI$1 = IS_ALLOWED_URI; /** * We consider the elements and attributes below to be safe. Ideally * don't add any new ones but feel free to remove unwanted ones. */ /* allowed element names */ let ALLOWED_TAGS = null; const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); /* Allowed attribute names */ let ALLOWED_ATTR = null; const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); /* * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements. * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements) * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list) * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`. */ let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { tagNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeNameCheck: { writable: true, configurable: false, enumerable: true, value: null }, allowCustomizedBuiltInElements: { writable: true, configurable: false, enumerable: true, value: false } })); /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ let FORBID_TAGS = null; /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ let FORBID_ATTR = null; /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */ const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { tagCheck: { writable: true, configurable: false, enumerable: true, value: null }, attributeCheck: { writable: true, configurable: false, enumerable: true, value: null } })); /* Decide if ARIA attributes are okay */ let ALLOW_ARIA_ATTR = true; /* Decide if custom data attributes are okay */ let ALLOW_DATA_ATTR = true; /* Decide if unknown protocols are okay */ let ALLOW_UNKNOWN_PROTOCOLS = false; /* Decide if self-closing tags in attributes are allowed. * Usually removed due to a mXSS issue in jQuery 3.0 */ let ALLOW_SELF_CLOSE_IN_ATTR = true; /* Output should be safe for common template engines. * This means, DOMPurify removes data attributes, mustaches and ERB */ let SAFE_FOR_TEMPLATES = false; /* Output should be safe even for XML used within HTML and alike. * This means, DOMPurify removes comments when containing risky content. */ let SAFE_FOR_XML = true; /* Decide if document with ... should be returned */ let WHOLE_DOCUMENT = false; /* Track whether config is already set on this instance of DOMPurify. */ let SET_CONFIG = false; /* Decide if all elements (e.g. style, script) must be children of * document.body. By default, browsers might move them to document.head */ let FORCE_BODY = false; /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported). * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead */ let RETURN_DOM = false; /* Decide if a DOM `DocumentFragment` should be returned, instead of a html * string (or a TrustedHTML object if Trusted Types are supported) */ let RETURN_DOM_FRAGMENT = false; /* Try to return a Trusted Type object instead of a string, return a string in * case Trusted Types are not supported */ let RETURN_TRUSTED_TYPE = false; /* Output should be free from DOM clobbering attacks? * This sanitizes markups named with colliding, clobberable built-in DOM APIs. */ let SANITIZE_DOM = true; /* Achieve full DOM Clobbering protection by isolating the namespace of named * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules. * * HTML/DOM spec rules that enable DOM Clobbering: * - Named Access on Window (§7.3.3) * - DOM Tree Accessors (§3.1.5) * - Form Element Parent-Child Relations (§4.10.3) * - Iframe srcdoc / Nested WindowProxies (§4.8.5) * - HTMLCollection (§4.2.10.2) * * Namespace isolation is implemented by prefixing `id` and `name` attributes * with a constant string, i.e., `user-content-` */ let SANITIZE_NAMED_PROPS = false; const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-'; /* Keep element content when removing element? */ let KEEP_CONTENT = true; /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead * of importing it into a new Document and returning a sanitized copy */ let IN_PLACE = false; /* Allow usage of profiles like html, svg and mathMl */ let USE_PROFILES = {}; /* Tags to ignore content of when KEEP_CONTENT is true */ let FORBID_CONTENTS = null; const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); /* Tags that are safe for data: URIs */ let DATA_URI_TAGS = null; const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); /* Attributes safe for values like "javascript:" */ let URI_SAFE_ATTRIBUTES = null; const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; /* Document namespace */ let NAMESPACE = HTML_NAMESPACE; let IS_EMPTY_INPUT = false; /* Allowed XHTML+XML namespaces */ let ALLOWED_NAMESPACES = null; const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']); // Certain elements are allowed in both SVG and HTML // namespace. We need to specify them explicitly // so that they don't get erroneously deleted from // HTML namespace. const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']); /* Parsing of strict XHTML documents */ let PARSER_MEDIA_TYPE = null; const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html']; const DEFAULT_PARSER_MEDIA_TYPE = 'text/html'; let transformCaseFunc = null; /* Keep a reference to config to pass to hooks */ let CONFIG = null; /* Ideally, do not touch anything below this line */ /* ______________________________________________ */ const formElement = document.createElement('form'); const isRegexOrFunction = function isRegexOrFunction(testValue) { return testValue instanceof RegExp || testValue instanceof Function; }; /** * _parseConfig * * @param cfg optional config literal */ // eslint-disable-next-line complexity const _parseConfig = function _parseConfig() { let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (CONFIG && CONFIG === cfg) { return; } /* Shield configuration object from tampering */ if (!cfg || typeof cfg !== 'object') { cfg = {}; } /* Shield configuration object from prototype pollution */ cfg = clone(cfg); PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is. transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase; /* Set configuration parameters */ ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') && arrayIsArray(cfg.ALLOWED_TAGS) ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') && arrayIsArray(cfg.ALLOWED_ATTR) ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') && arrayIsArray(cfg.ALLOWED_NAMESPACES) ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR) ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') && arrayIsArray(cfg.ADD_DATA_URI_TAGS) ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS) ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') && arrayIsArray(cfg.FORBID_TAGS) ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({}); FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') && arrayIsArray(cfg.FORBID_ATTR) ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({}); USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false; ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false RETURN_DOM = cfg.RETURN_DOM || false; // Default false RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false FORCE_BODY = cfg.FORCE_BODY || false; // Default false SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true IN_PLACE = cfg.IN_PLACE || false; // Default false IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); // Default built-in map HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, ['annotation-xml']); // Default built-in map const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null); CUSTOM_ELEMENT_HANDLING = create(null); if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) { CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined } if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) { CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined } if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') { CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined } if (SAFE_FOR_TEMPLATES) { ALLOW_DATA_ATTR = false; } if (RETURN_DOM_FRAGMENT) { RETURN_DOM = true; } /* Parse profile info */ if (USE_PROFILES) { ALLOWED_TAGS = addToSet({}, text); ALLOWED_ATTR = create(null); if (USE_PROFILES.html === true) { addToSet(ALLOWED_TAGS, html$1); addToSet(ALLOWED_ATTR, html); } if (USE_PROFILES.svg === true) { addToSet(ALLOWED_TAGS, svg$1); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.svgFilters === true) { addToSet(ALLOWED_TAGS, svgFilters); addToSet(ALLOWED_ATTR, svg); addToSet(ALLOWED_ATTR, xml); } if (USE_PROFILES.mathMl === true) { addToSet(ALLOWED_TAGS, mathMl$1); addToSet(ALLOWED_ATTR, mathMl); addToSet(ALLOWED_ATTR, xml); } } /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent * leaking across calls when switching from function to array config */ EXTRA_ELEMENT_HANDLING.tagCheck = null; EXTRA_ELEMENT_HANDLING.attributeCheck = null; /* Merge configuration parameters */ if (objectHasOwnProperty(cfg, 'ADD_TAGS')) { if (typeof cfg.ADD_TAGS === 'function') { EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; } else if (arrayIsArray(cfg.ADD_TAGS)) { if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { ALLOWED_TAGS = clone(ALLOWED_TAGS); } addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); } } if (objectHasOwnProperty(cfg, 'ADD_ATTR')) { if (typeof cfg.ADD_ATTR === 'function') { EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; } else if (arrayIsArray(cfg.ADD_ATTR)) { if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { ALLOWED_ATTR = clone(ALLOWED_ATTR); } addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); } } if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) { addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); } if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) { if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { FORBID_CONTENTS = clone(FORBID_CONTENTS); } addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); } if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) { if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { FORBID_CONTENTS = clone(FORBID_CONTENTS); } addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); } /* Add #text in case KEEP_CONTENT is set to true */ if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; } /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ if (WHOLE_DOCUMENT) { addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); } /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ if (ALLOWED_TAGS.table) { addToSet(ALLOWED_TAGS, ['tbody']); delete FORBID_TAGS.tbody; } if (cfg.TRUSTED_TYPES_POLICY) { if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') { throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); } if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') { throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); } // Overwrite existing TrustedTypes policy. trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; // Sign local variables required by `sanitize`. emptyHTML = trustedTypesPolicy.createHTML(''); } else { // Uninitialized policy, attempt to initialize the internal dompurify policy. if (trustedTypesPolicy === undefined) { trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); } // If creating the internal policy succeeded sign internal variables. if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') { emptyHTML = trustedTypesPolicy.createHTML(''); } } // Prevent further manipulation of configuration. // Not available in IE8, Safari 5, etc. if (freeze) { freeze(cfg); } CONFIG = cfg; }; /* Keep track of all possible SVG and MathML tags * so that we can perform the namespace checks * correctly. */ const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); /** * @param element a DOM element whose namespace is being checked * @returns Return false if the element has a * namespace that a spec-compliant parser would never * return. Return true otherwise. */ const _checkValidNamespace = function _checkValidNamespace(element) { let parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode // can be null. We just simulate parent in this case. if (!parent || !parent.tagName) { parent = { namespaceURI: NAMESPACE, tagName: 'template' }; } const tagName = stringToLowerCase(element.tagName); const parentTagName = stringToLowerCase(parent.tagName); if (!ALLOWED_NAMESPACES[element.namespaceURI]) { return false; } if (element.namespaceURI === SVG_NAMESPACE) { // The only way to switch from HTML namespace to SVG // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'svg'; } // The only way to switch from MathML to SVG is via` // svg if parent is either or MathML // text integration points. if (parent.namespaceURI === MATHML_NAMESPACE) { return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); } // We only allow elements that are defined in SVG // spec. All others are disallowed in SVG namespace. return Boolean(ALL_SVG_TAGS[tagName]); } if (element.namespaceURI === MATHML_NAMESPACE) { // The only way to switch from HTML namespace to MathML // is via . If it happens via any other tag, then // it should be killed. if (parent.namespaceURI === HTML_NAMESPACE) { return tagName === 'math'; } // The only way to switch from SVG to MathML is via // and HTML integration points if (parent.namespaceURI === SVG_NAMESPACE) { return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; } // We only allow elements that are defined in MathML // spec. All others are disallowed in MathML namespace. return Boolean(ALL_MATHML_TAGS[tagName]); } if (element.namespaceURI === HTML_NAMESPACE) { // The only way to switch from SVG to HTML is via // HTML integration points, and from MathML to HTML // is via MathML text integration points if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { return false; } if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { return false; } // We disallow tags that are specific for MathML // or SVG and should never appear in HTML namespace return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); } // For XHTML and XML documents that support custom namespaces if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) { return true; } // The code should never reach this place (this means // that the element somehow got namespace that is not // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES). // Return false just in case. return false; }; /** * _forceRemove * * @param node a DOM node */ const _forceRemove = function _forceRemove(node) { arrayPush(DOMPurify.removed, { element: node }); try { // eslint-disable-next-line unicorn/prefer-dom-node-remove getParentNode(node).removeChild(node); } catch (_) { remove(node); } }; /** * _removeAttribute * * @param name an Attribute name * @param element a DOM node */ const _removeAttribute = function _removeAttribute(name, element) { try { arrayPush(DOMPurify.removed, { attribute: element.getAttributeNode(name), from: element }); } catch (_) { arrayPush(DOMPurify.removed, { attribute: null, from: element }); } element.removeAttribute(name); // We void attribute values for unremovable "is" attributes if (name === 'is') { if (RETURN_DOM || RETURN_DOM_FRAGMENT) { try { _forceRemove(element); } catch (_) {} } else { try { element.setAttribute(name, ''); } catch (_) {} } } }; /** * _initDocument * * @param dirty - a string of dirty markup * @return a DOM, filled with the dirty markup */ const _initDocument = function _initDocument(dirty) { /* Create a HTML document */ let doc = null; let leadingWhitespace = null; if (FORCE_BODY) { dirty = '' + dirty; } else { /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ const matches = stringMatch(dirty, /^[\r\n\t ]+/); leadingWhitespace = matches && matches[0]; } if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) { // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict) dirty = '' + dirty + ''; } const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; /* * Use the DOMParser API by default, fallback later if needs be * DOMParser not work for svg when has multiple root element. */ if (NAMESPACE === HTML_NAMESPACE) { try { doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); } catch (_) {} } /* Use createHTMLDocument in case DOMParser is not available */ if (!doc || !doc.documentElement) { doc = implementation.createDocument(NAMESPACE, 'template', null); try { doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; } catch (_) { // Syntax error if dirtyPayload is invalid xml } } const body = doc.body || doc.documentElement; if (dirty && leadingWhitespace) { body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); } /* Work on whole document or just its body */ if (NAMESPACE === HTML_NAMESPACE) { return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; } return WHOLE_DOCUMENT ? doc.documentElement : body; }; /** * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document. * * @param root The root element or node to start traversing on. * @return The created NodeIterator */ const _createNodeIterator = function _createNodeIterator(root) { return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null); }; /** * _isClobbered * * @param element element to check for clobbering attacks * @return true if clobbered, false if safe */ const _isClobbered = function _isClobbered(element) { return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function'); }; /** * Checks whether the given object is a DOM node. * * @param value object to check whether it's a DOM node * @return true is object is a DOM node */ const _isNode = function _isNode(value) { return typeof Node === 'function' && value instanceof Node; }; function _executeHooks(hooks, currentNode, data) { arrayForEach(hooks, hook => { hook.call(DOMPurify, currentNode, data, CONFIG); }); } /** * _sanitizeElements * * @protect nodeName * @protect textContent * @protect removeChild * @param currentNode to check for permission to exist * @return true if node was killed, false if left alive */ const _sanitizeElements = function _sanitizeElements(currentNode) { let content = null; /* Execute a hook if present */ _executeHooks(hooks.beforeSanitizeElements, currentNode, null); /* Check if element is clobbered or can clobber */ if (_isClobbered(currentNode)) { _forceRemove(currentNode); return true; } /* Now let's check the element's type and name */ const tagName = transformCaseFunc(currentNode.nodeName); /* Execute a hook if present */ _executeHooks(hooks.uponSanitizeElement, currentNode, { tagName, allowedTags: ALLOWED_TAGS }); /* Detect mXSS attempts abusing namespace confusion */ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) { _forceRemove(currentNode); return true; } /* Remove risky CSS construction leading to mXSS */ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) { _forceRemove(currentNode); return true; } /* Remove any occurrence of processing instructions */ if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { _forceRemove(currentNode); return true; } /* Remove any kind of possibly harmful comments */ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { _forceRemove(currentNode); return true; } /* Remove element if anything forbids its presence */ if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) { /* Check if we have a custom element to handle */ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { return false; } if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { return false; } } /* Keep content except for bad-listed elements */ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { const parentNode = getParentNode(currentNode) || currentNode.parentNode; const childNodes = getChildNodes(currentNode) || currentNode.childNodes; if (childNodes && parentNode) { const childCount = childNodes.length; for (let i = childCount - 1; i >= 0; --i) { const childClone = cloneNode(childNodes[i], true); parentNode.insertBefore(childClone, getNextSibling(currentNode)); } } } _forceRemove(currentNode); return true; } /* Check whether element has a valid namespace */ if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { _forceRemove(currentNode); return true; } /* Make sure that older browsers don't get fallback-tag mXSS */ if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { _forceRemove(currentNode); return true; } /* Sanitize element content to be template-safe */ if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { /* Get the element's text content */ content = currentNode.textContent; arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { content = stringReplace(content, expr, ' '); }); if (currentNode.textContent !== content) { arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() }); currentNode.textContent = content; } } /* Execute a hook if present */ _executeHooks(hooks.afterSanitizeElements, currentNode, null); return false; }; /** * _isValidAttribute * * @param lcTag Lowercase tag name of containing element. * @param lcName Lowercase attribute name. * @param value Attribute value. * @return Returns true if `value` is valid, otherwise false. */ // eslint-disable-next-line complexity const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) { /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */ if (FORBID_ATTR[lcName]) { return false; } /* Make sure attribute cannot clobber */ if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) { return false; } const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag); /* Allow valid data-* attributes: At least one character after "-" (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) We don't need to check the value; it's always URI safe. */ if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted || FORBID_ATTR[lcName]) { if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || // Alternative, second condition checks if it's an `is`-attribute, AND // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else { return false; } /* Check value is safe. First, is attr inert? If so, is safe */ } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) { return false; } else ; return true; }; /* Names the HTML spec reserves from valid-custom-element-name; these must * never be treated as basic custom elements even when a permissive * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */ const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']); /** * _isBasicCustomElement * checks if at least one dash is included in tagName, and it's not the first char * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name * * @param tagName name of the tag of the node to sanitize * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false. */ const _isBasicCustomElement = function _isBasicCustomElement(tagName) { return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName); }; /** * _sanitizeAttributes * * @protect attributes * @protect nodeName * @protect removeAttribute * @protect setAttribute * * @param currentNode to sanitize */ const _sanitizeAttributes = function _sanitizeAttributes(currentNode) { /* Execute a hook if present */ _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); const attributes = currentNode.attributes; /* Check if we have attributes; if not we might have a text node */ if (!attributes || _isClobbered(currentNode)) { return; } const hookEvent = { attrName: '', attrValue: '', keepAttr: true, allowedAttributes: ALLOWED_ATTR, forceKeepAttr: undefined }; let l = attributes.length; /* Go backwards over all attributes; safely remove bad ones */ while (l--) { const attr = attributes[l]; const name = attr.name, namespaceURI = attr.namespaceURI, attrValue = attr.value; const lcName = transformCaseFunc(name); const initValue = attrValue; let value = name === 'value' ? initValue : stringTrim(initValue); /* Execute a hook if present */ hookEvent.attrName = lcName; hookEvent.attrValue = value; hookEvent.keepAttr = true; hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); value = hookEvent.attrValue; /* Full DOM Clobbering protection via namespace isolation, * Prefix id and name attributes with `user-content-` */ if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) { // Remove the attribute with this value _removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value value = SANITIZE_NAMED_PROPS_PREFIX + value; } // Else: already prefixed, leave the attribute alone — the prefix is // itself the clobbering protection, and re-applying it is incorrect. /* Work around a security issue with comments inside attributes */ if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) { _removeAttribute(name, currentNode); continue; } /* Make sure we cannot easily use animated hrefs, even if animations are allowed */ if (lcName === 'attributename' && stringMatch(value, 'href')) { _removeAttribute(name, currentNode); continue; } /* Did the hooks approve of the attribute? */ if (hookEvent.forceKeepAttr) { continue; } /* Did the hooks approve of the attribute? */ if (!hookEvent.keepAttr) { _removeAttribute(name, currentNode); continue; } /* Work around a security issue in jQuery 3.0 */ if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { _removeAttribute(name, currentNode); continue; } /* Sanitize attribute content to be template-safe */ if (SAFE_FOR_TEMPLATES) { arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { value = stringReplace(value, expr, ' '); }); } /* Is `value` valid for this attribute? */ const lcTag = transformCaseFunc(currentNode.nodeName); if (!_isValidAttribute(lcTag, lcName, value)) { _removeAttribute(name, currentNode); continue; } /* Handle attributes that require Trusted Types */ if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') { if (namespaceURI) ; else { switch (trustedTypes.getAttributeType(lcTag, lcName)) { case 'TrustedHTML': { value = trustedTypesPolicy.createHTML(value); break; } case 'TrustedScriptURL': { value = trustedTypesPolicy.createScriptURL(value); break; } } } } /* Handle invalid data-* attribute set by try-catching it */ if (value !== initValue) { try { if (namespaceURI) { currentNode.setAttributeNS(namespaceURI, name, value); } else { /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */ currentNode.setAttribute(name, value); } if (_isClobbered(currentNode)) { _forceRemove(currentNode); } else { arrayPop(DOMPurify.removed); } } catch (_) { _removeAttribute(name, currentNode); } } } /* Execute a hook if present */ _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); }; /** * _sanitizeShadowDOM * * @param fragment to iterate over recursively */ const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) { let shadowNode = null; const shadowIterator = _createNodeIterator(fragment); /* Execute a hook if present */ _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); while (shadowNode = shadowIterator.nextNode()) { /* Execute a hook if present */ _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); /* Sanitize tags and elements */ _sanitizeElements(shadowNode); /* Check attributes next */ _sanitizeAttributes(shadowNode); /* Deep shadow DOM detected */ if (shadowNode.content instanceof DocumentFragment) { _sanitizeShadowDOM2(shadowNode.content); } } /* Execute a hook if present */ _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); }; /** * _sanitizeAttachedShadowRoots * * Walks `root` and feeds every attached shadow root we encounter into * the existing _sanitizeShadowDOM pipeline. The default node iterator * does not descend into shadow trees, so nodes inside an attached * shadow root would otherwise be skipped entirely. * * Two real input paths put attached shadow roots in front of us: * 1. IN_PLACE on a DOM node that already has shadow roots attached. * 2. DOM-node input where importNode(dirty, true) deep-clones the * shadow root because it was created with `clonable: true`. * * This pass runs once, up front, so the main iteration loop (and the * existing _sanitizeShadowDOM template-content recursion) stay * untouched — string-input paths are not affected. * * @param root the subtree root to walk for attached shadow roots */ const _sanitizeAttachedShadowRoots2 = function _sanitizeAttachedShadowRoots(root) { if (root.nodeType === NODE_TYPE.element && root.shadowRoot instanceof DocumentFragment) { const sr = root.shadowRoot; // Recurse first so that nested shadow roots are reached even if // _sanitizeShadowDOM removes hosts at this level. _sanitizeAttachedShadowRoots2(sr); _sanitizeShadowDOM2(sr); } // Snapshot children before recursing. Sanitization of one subtree // (e.g. via an uponSanitizeShadowNode hook) may detach siblings, // and naive nextSibling traversal would silently skip the rest of // the list once a node is detached. const childNodes = root.childNodes; if (!childNodes) { return; } const snapshot = []; arrayForEach(childNodes, child => { arrayPush(snapshot, child); }); for (const child of snapshot) { _sanitizeAttachedShadowRoots2(child); } }; // eslint-disable-next-line complexity DOMPurify.sanitize = function (dirty) { let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let body = null; let importedNode = null; let currentNode = null; let returnNode = null; /* Make sure we have a string to sanitize. DO NOT return early, as this will return the wrong type if the user has requested a DOM object rather than a string */ IS_EMPTY_INPUT = !dirty; if (IS_EMPTY_INPUT) { dirty = ''; } /* Stringify, in case dirty is an object */ if (typeof dirty !== 'string' && !_isNode(dirty)) { dirty = stringifyValue(dirty); if (typeof dirty !== 'string') { throw typeErrorCreate('dirty is not a string, aborting'); } } /* Return dirty HTML if DOMPurify cannot run */ if (!DOMPurify.isSupported) { return dirty; } /* Assign config vars */ if (!SET_CONFIG) { _parseConfig(cfg); } /* Clean up removed elements */ DOMPurify.removed = []; /* Check if dirty is correctly typed for IN_PLACE */ if (typeof dirty === 'string') { IN_PLACE = false; } if (IN_PLACE) { /* Do some early pre-sanitization to avoid unsafe root nodes */ const nn = dirty.nodeName; if (typeof nn === 'string') { const tagName = transformCaseFunc(nn); if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place'); } } /* Sanitize attached shadow roots before the main iterator runs. The iterator does not descend into shadow trees. */ _sanitizeAttachedShadowRoots2(dirty); } else if (dirty instanceof Node) { /* If dirty is a DOM element, append to an empty document to avoid elements being stripped by the parser */ body = _initDocument(''); importedNode = body.ownerDocument.importNode(dirty, true); if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') { /* Node is already a body, use as is */ body = importedNode; } else if (importedNode.nodeName === 'HTML') { body = importedNode; } else { // eslint-disable-next-line unicorn/prefer-dom-node-append body.appendChild(importedNode); } /* Clonable shadow roots are deep-cloned by importNode(); sanitize them before the main iterator runs, since the iterator does not descend into shadow trees. */ _sanitizeAttachedShadowRoots2(importedNode); } else { /* Exit directly if we have nothing to do */ if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes dirty.indexOf('<') === -1) { return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; } /* Initialize the document to work on */ body = _initDocument(dirty); /* Check we have a DOM node from the data */ if (!body) { return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ''; } } /* Remove first element node (ours) if FORCE_BODY is set */ if (body && FORCE_BODY) { _forceRemove(body.firstChild); } /* Get node iterator */ const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); /* Now start iterating over the created document */ while (currentNode = nodeIterator.nextNode()) { /* Sanitize tags and elements */ _sanitizeElements(currentNode); /* Check attributes next */ _sanitizeAttributes(currentNode); /* Shadow DOM detected, sanitize it */ if (currentNode.content instanceof DocumentFragment) { _sanitizeShadowDOM2(currentNode.content); } } /* If we sanitized `dirty` in-place, return it. */ if (IN_PLACE) { return dirty; } /* Return sanitized string or DOM */ if (RETURN_DOM) { if (SAFE_FOR_TEMPLATES) { body.normalize(); let html = body.innerHTML; arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { html = stringReplace(html, expr, ' '); }); body.innerHTML = html; } if (RETURN_DOM_FRAGMENT) { returnNode = createDocumentFragment.call(body.ownerDocument); while (body.firstChild) { // eslint-disable-next-line unicorn/prefer-dom-node-append returnNode.appendChild(body.firstChild); } } else { returnNode = body; } if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { /* AdoptNode() is not used because internal state is not reset (e.g. the past names map of a HTMLFormElement), this is safe in theory but we would rather not risk another attack vector. The state that is cloned by importNode() is explicitly defined by the specs. */ returnNode = importNode.call(originalDocument, returnNode, true); } return returnNode; } let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; /* Serialize doctype if allowed */ if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { serializedHTML = '\n' + serializedHTML; } /* Sanitize final string template-safe */ if (SAFE_FOR_TEMPLATES) { arrayForEach([MUSTACHE_EXPR$1, ERB_EXPR$1, TMPLIT_EXPR$1], expr => { serializedHTML = stringReplace(serializedHTML, expr, ' '); }); } return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; }; DOMPurify.setConfig = function () { let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _parseConfig(cfg); SET_CONFIG = true; }; DOMPurify.clearConfig = function () { CONFIG = null; SET_CONFIG = false; }; DOMPurify.isValidAttribute = function (tag, attr, value) { /* Initialize shared config vars if necessary. */ if (!CONFIG) { _parseConfig({}); } const lcTag = transformCaseFunc(tag); const lcName = transformCaseFunc(attr); return _isValidAttribute(lcTag, lcName, value); }; DOMPurify.addHook = function (entryPoint, hookFunction) { if (typeof hookFunction !== 'function') { return; } arrayPush(hooks[entryPoint], hookFunction); }; DOMPurify.removeHook = function (entryPoint, hookFunction) { if (hookFunction !== undefined) { const index = arrayLastIndexOf(hooks[entryPoint], hookFunction); return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0]; } return arrayPop(hooks[entryPoint]); }; DOMPurify.removeHooks = function (entryPoint) { hooks[entryPoint] = []; }; DOMPurify.removeAllHooks = function () { hooks = _createHooksMap(); }; return DOMPurify; } var purify = createDOMPurify(); //# sourceMappingURL=purify.es.mjs.map /***/ }, /***/ "./node_modules/react-router/dist/development/chunk-5KNZJZUH.mjs" /*!***********************************************************************!*\ !*** ./node_modules/react-router/dist/development/chunk-5KNZJZUH.mjs ***! \***********************************************************************/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { "use strict"; var react__WEBPACK_IMPORTED_MODULE_0___namespace_cache; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ Action: () => (/* binding */ Action), /* harmony export */ Await: () => (/* binding */ Await), /* harmony export */ AwaitContextProvider: () => (/* binding */ AwaitContextProvider), /* harmony export */ BrowserRouter: () => (/* binding */ BrowserRouter), /* harmony export */ CRITICAL_CSS_DATA_ATTRIBUTE: () => (/* binding */ CRITICAL_CSS_DATA_ATTRIBUTE), /* harmony export */ DataRouterContext: () => (/* binding */ DataRouterContext), /* harmony export */ DataRouterStateContext: () => (/* binding */ DataRouterStateContext), /* harmony export */ ENABLE_DEV_WARNINGS: () => (/* binding */ ENABLE_DEV_WARNINGS), /* harmony export */ ErrorResponseImpl: () => (/* binding */ ErrorResponseImpl), /* harmony export */ FetchersContext: () => (/* binding */ FetchersContext), /* harmony export */ Form: () => (/* binding */ Form), /* harmony export */ FrameworkContext: () => (/* binding */ FrameworkContext), /* harmony export */ HashRouter: () => (/* binding */ HashRouter), /* harmony export */ HistoryRouter: () => (/* binding */ HistoryRouter), /* harmony export */ IDLE_BLOCKER: () => (/* binding */ IDLE_BLOCKER), /* harmony export */ IDLE_FETCHER: () => (/* binding */ IDLE_FETCHER), /* harmony export */ IDLE_NAVIGATION: () => (/* binding */ IDLE_NAVIGATION), /* harmony export */ Link: () => (/* binding */ Link), /* harmony export */ Links: () => (/* binding */ Links), /* harmony export */ LocationContext: () => (/* binding */ LocationContext), /* harmony export */ MemoryRouter: () => (/* binding */ MemoryRouter), /* harmony export */ Meta: () => (/* binding */ Meta), /* harmony export */ NO_BODY_STATUS_CODES: () => (/* binding */ NO_BODY_STATUS_CODES), /* harmony export */ NavLink: () => (/* binding */ NavLink), /* harmony export */ Navigate: () => (/* binding */ Navigate), /* harmony export */ NavigationContext: () => (/* binding */ NavigationContext), /* harmony export */ Outlet: () => (/* binding */ Outlet), /* harmony export */ PrefetchPageLinks: () => (/* binding */ PrefetchPageLinks), /* harmony export */ RSCRouterContext: () => (/* binding */ RSCRouterContext), /* harmony export */ RemixErrorBoundary: () => (/* binding */ RemixErrorBoundary), /* harmony export */ Route: () => (/* binding */ Route), /* harmony export */ RouteContext: () => (/* binding */ RouteContext), /* harmony export */ Router: () => (/* binding */ Router), /* harmony export */ RouterContextProvider: () => (/* binding */ RouterContextProvider), /* harmony export */ RouterProvider: () => (/* binding */ RouterProvider), /* harmony export */ Routes: () => (/* binding */ Routes), /* harmony export */ SINGLE_FETCH_REDIRECT_STATUS: () => (/* binding */ SINGLE_FETCH_REDIRECT_STATUS), /* harmony export */ Scripts: () => (/* binding */ Scripts), /* harmony export */ ScrollRestoration: () => (/* binding */ ScrollRestoration), /* harmony export */ SingleFetchRedirectSymbol: () => (/* binding */ SingleFetchRedirectSymbol), /* harmony export */ StaticRouter: () => (/* binding */ StaticRouter), /* harmony export */ StaticRouterProvider: () => (/* binding */ StaticRouterProvider), /* harmony export */ StreamTransfer: () => (/* binding */ StreamTransfer), /* harmony export */ URL_LIMIT: () => (/* binding */ URL_LIMIT), /* harmony export */ ViewTransitionContext: () => (/* binding */ ViewTransitionContext), /* harmony export */ WithComponentProps: () => (/* binding */ WithComponentProps), /* harmony export */ WithErrorBoundaryProps: () => (/* binding */ WithErrorBoundaryProps), /* harmony export */ WithHydrateFallbackProps: () => (/* binding */ WithHydrateFallbackProps), /* harmony export */ convertRoutesToDataRoutes: () => (/* binding */ convertRoutesToDataRoutes), /* harmony export */ createBrowserHistory: () => (/* binding */ createBrowserHistory), /* harmony export */ createBrowserRouter: () => (/* binding */ createBrowserRouter), /* harmony export */ createClientRoutes: () => (/* binding */ createClientRoutes), /* harmony export */ createClientRoutesWithHMRRevalidationOptOut: () => (/* binding */ createClientRoutesWithHMRRevalidationOptOut), /* harmony export */ createContext: () => (/* binding */ createContext), /* harmony export */ createHashHistory: () => (/* binding */ createHashHistory), /* harmony export */ createHashRouter: () => (/* binding */ createHashRouter), /* harmony export */ createMemoryHistory: () => (/* binding */ createMemoryHistory), /* harmony export */ createMemoryRouter: () => (/* binding */ createMemoryRouter), /* harmony export */ createPath: () => (/* binding */ createPath), /* harmony export */ createRequestInit: () => (/* binding */ createRequestInit), /* harmony export */ createRouter: () => (/* binding */ createRouter), /* harmony export */ createRoutesFromChildren: () => (/* binding */ createRoutesFromChildren), /* harmony export */ createRoutesFromElements: () => (/* binding */ createRoutesFromElements), /* harmony export */ createSearchParams: () => (/* binding */ createSearchParams), /* harmony export */ createServerRoutes: () => (/* binding */ createServerRoutes), /* harmony export */ createStaticHandler: () => (/* binding */ createStaticHandler), /* harmony export */ createStaticHandler2: () => (/* binding */ createStaticHandler2), /* harmony export */ createStaticRouter: () => (/* binding */ createStaticRouter), /* harmony export */ data: () => (/* binding */ data), /* harmony export */ decodeRedirectErrorDigest: () => (/* binding */ decodeRedirectErrorDigest), /* harmony export */ decodeRouteErrorResponseDigest: () => (/* binding */ decodeRouteErrorResponseDigest), /* harmony export */ decodeViaTurboStream: () => (/* binding */ decodeViaTurboStream), /* harmony export */ encode: () => (/* binding */ encode), /* harmony export */ escapeHtml: () => (/* binding */ escapeHtml), /* harmony export */ generatePath: () => (/* binding */ generatePath), /* harmony export */ getManifestPath: () => (/* binding */ getManifestPath), /* harmony export */ getPatchRoutesOnNavigationFunction: () => (/* binding */ getPatchRoutesOnNavigationFunction), /* harmony export */ getSingleFetchDataStrategyImpl: () => (/* binding */ getSingleFetchDataStrategyImpl), /* harmony export */ getStaticContextFromError: () => (/* binding */ getStaticContextFromError), /* harmony export */ getTurboStreamSingleFetchDataStrategy: () => (/* binding */ getTurboStreamSingleFetchDataStrategy), /* harmony export */ hydrationRouteProperties: () => (/* binding */ hydrationRouteProperties), /* harmony export */ instrumentHandler: () => (/* binding */ instrumentHandler), /* harmony export */ invalidProtocols: () => (/* binding */ invalidProtocols), /* harmony export */ invariant: () => (/* binding */ invariant), /* harmony export */ isDataWithResponseInit: () => (/* binding */ isDataWithResponseInit), /* harmony export */ isMutationMethod: () => (/* binding */ isMutationMethod), /* harmony export */ isRedirectResponse: () => (/* binding */ isRedirectResponse), /* harmony export */ isRedirectStatusCode: () => (/* binding */ isRedirectStatusCode), /* harmony export */ isResponse: () => (/* binding */ isResponse), /* harmony export */ isRouteErrorResponse: () => (/* binding */ isRouteErrorResponse), /* harmony export */ mapRouteProperties: () => (/* binding */ mapRouteProperties), /* harmony export */ matchPath: () => (/* binding */ matchPath), /* harmony export */ matchRoutes: () => (/* binding */ matchRoutes), /* harmony export */ matchRoutesImpl: () => (/* binding */ matchRoutesImpl), /* harmony export */ noActionDefinedError: () => (/* binding */ noActionDefinedError), /* harmony export */ parsePath: () => (/* binding */ parsePath), /* harmony export */ redirect: () => (/* binding */ redirect), /* harmony export */ redirectDocument: () => (/* binding */ redirectDocument), /* harmony export */ renderMatches: () => (/* binding */ renderMatches), /* harmony export */ replace: () => (/* binding */ replace), /* harmony export */ resolvePath: () => (/* binding */ resolvePath), /* harmony export */ setIsHydrated: () => (/* binding */ setIsHydrated), /* harmony export */ shouldHydrateRouteLoader: () => (/* binding */ shouldHydrateRouteLoader), /* harmony export */ singleFetchUrl: () => (/* binding */ singleFetchUrl), /* harmony export */ stripBasename: () => (/* binding */ stripBasename), /* harmony export */ stripIndexParam: () => (/* binding */ stripIndexParam), /* harmony export */ useActionData: () => (/* binding */ useActionData), /* harmony export */ useAsyncError: () => (/* binding */ useAsyncError), /* harmony export */ useAsyncValue: () => (/* binding */ useAsyncValue), /* harmony export */ useBeforeUnload: () => (/* binding */ useBeforeUnload), /* harmony export */ useBlocker: () => (/* binding */ useBlocker), /* harmony export */ useFetcher: () => (/* binding */ useFetcher), /* harmony export */ useFetchers: () => (/* binding */ useFetchers), /* harmony export */ useFogOFWarDiscovery: () => (/* binding */ useFogOFWarDiscovery), /* harmony export */ useFormAction: () => (/* binding */ useFormAction), /* harmony export */ useHref: () => (/* binding */ useHref), /* harmony export */ useInRouterContext: () => (/* binding */ useInRouterContext), /* harmony export */ useLinkClickHandler: () => (/* binding */ useLinkClickHandler), /* harmony export */ useLoaderData: () => (/* binding */ useLoaderData), /* harmony export */ useLocation: () => (/* binding */ useLocation), /* harmony export */ useMatch: () => (/* binding */ useMatch), /* harmony export */ useMatches: () => (/* binding */ useMatches), /* harmony export */ useNavigate: () => (/* binding */ useNavigate), /* harmony export */ useNavigation: () => (/* binding */ useNavigation), /* harmony export */ useNavigationType: () => (/* binding */ useNavigationType), /* harmony export */ useOutlet: () => (/* binding */ useOutlet), /* harmony export */ useOutletContext: () => (/* binding */ useOutletContext), /* harmony export */ useParams: () => (/* binding */ useParams), /* harmony export */ usePrompt: () => (/* binding */ usePrompt), /* harmony export */ useResolvedPath: () => (/* binding */ useResolvedPath), /* harmony export */ useRevalidator: () => (/* binding */ useRevalidator), /* harmony export */ useRoute: () => (/* binding */ useRoute), /* harmony export */ useRouteError: () => (/* binding */ useRouteError), /* harmony export */ useRouteLoaderData: () => (/* binding */ useRouteLoaderData), /* harmony export */ useRoutes: () => (/* binding */ useRoutes), /* harmony export */ useScrollRestoration: () => (/* binding */ useScrollRestoration), /* harmony export */ useSearchParams: () => (/* binding */ useSearchParams), /* harmony export */ useSubmit: () => (/* binding */ useSubmit), /* harmony export */ useViewTransitionState: () => (/* binding */ useViewTransitionState), /* harmony export */ warnOnce: () => (/* binding */ warnOnce), /* harmony export */ withComponentProps: () => (/* binding */ withComponentProps), /* harmony export */ withErrorBoundaryProps: () => (/* binding */ withErrorBoundaryProps), /* harmony export */ withHydrateFallbackProps: () => (/* binding */ withHydrateFallbackProps) /* harmony export */ }); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); /** * react-router v7.15.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */ var __typeError = (msg) => { throw TypeError(msg); }; var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); // lib/router/history.ts var Action = /* @__PURE__ */ ((Action2) => { Action2["Pop"] = "POP"; Action2["Push"] = "PUSH"; Action2["Replace"] = "REPLACE"; return Action2; })(Action || {}); var PopStateEventType = "popstate"; function isLocation(obj) { return typeof obj === "object" && obj != null && "pathname" in obj && "search" in obj && "hash" in obj && "state" in obj && "key" in obj; } function createMemoryHistory(options = {}) { let { initialEntries = ["/"], initialIndex, v5Compat = false } = options; let entries; entries = initialEntries.map( (entry, index2) => createMemoryLocation( entry, typeof entry === "string" ? null : entry.state, index2 === 0 ? "default" : void 0, typeof entry === "string" ? void 0 : entry.mask ) ); let index = clampIndex( initialIndex == null ? entries.length - 1 : initialIndex ); let action = "POP" /* Pop */; let listener = null; function clampIndex(n) { return Math.min(Math.max(n, 0), entries.length - 1); } function getCurrentLocation() { return entries[index]; } function createMemoryLocation(to, state = null, key, mask) { let location = createLocation( entries ? getCurrentLocation().pathname : "/", to, state, key, mask ); warning( location.pathname.charAt(0) === "/", `relative pathnames are not supported in memory history: ${JSON.stringify( to )}` ); return location; } function createHref2(to) { return typeof to === "string" ? to : createPath(to); } let history = { get index() { return index; }, get action() { return action; }, get location() { return getCurrentLocation(); }, createHref: createHref2, createURL(to) { return new URL(createHref2(to), "http://localhost"); }, encodeLocation(to) { let path = typeof to === "string" ? parsePath(to) : to; return { pathname: path.pathname || "", search: path.search || "", hash: path.hash || "" }; }, push(to, state) { action = "PUSH" /* Push */; let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state); index += 1; entries.splice(index, entries.length, nextLocation); if (v5Compat && listener) { listener({ action, location: nextLocation, delta: 1 }); } }, replace(to, state) { action = "REPLACE" /* Replace */; let nextLocation = isLocation(to) ? to : createMemoryLocation(to, state); entries[index] = nextLocation; if (v5Compat && listener) { listener({ action, location: nextLocation, delta: 0 }); } }, go(delta) { action = "POP" /* Pop */; let nextIndex = clampIndex(index + delta); let nextLocation = entries[nextIndex]; index = nextIndex; if (listener) { listener({ action, location: nextLocation, delta }); } }, listen(fn) { listener = fn; return () => { listener = null; }; } }; return history; } function createBrowserHistory(options = {}) { function createBrowserLocation(window2, globalHistory) { let maskedLocation = globalHistory.state?.masked; let { pathname, search, hash } = maskedLocation || window2.location; return createLocation( "", { pathname, search, hash }, // state defaults to `null` because `window.history.state` does globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default", maskedLocation ? { pathname: window2.location.pathname, search: window2.location.search, hash: window2.location.hash } : void 0 ); } function createBrowserHref(window2, to) { return typeof to === "string" ? to : createPath(to); } return getUrlBasedHistory( createBrowserLocation, createBrowserHref, null, options ); } function createHashHistory(options = {}) { function createHashLocation(window2, globalHistory) { let { pathname = "/", search = "", hash = "" } = parsePath(window2.location.hash.substring(1)); if (!pathname.startsWith("/") && !pathname.startsWith(".")) { pathname = "/" + pathname; } return createLocation( "", { pathname, search, hash }, // state defaults to `null` because `window.history.state` does globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default" ); } function createHashHref(window2, to) { let base = window2.document.querySelector("base"); let href = ""; if (base && base.getAttribute("href")) { let url = window2.location.href; let hashIndex = url.indexOf("#"); href = hashIndex === -1 ? url : url.slice(0, hashIndex); } return href + "#" + (typeof to === "string" ? to : createPath(to)); } function validateHashLocation(location, to) { warning( location.pathname.charAt(0) === "/", `relative pathnames are not supported in hash history.push(${JSON.stringify( to )})` ); } return getUrlBasedHistory( createHashLocation, createHashHref, validateHashLocation, options ); } function invariant(value, message) { if (value === false || value === null || typeof value === "undefined") { throw new Error(message); } } function warning(cond, message) { if (!cond) { if (typeof console !== "undefined") console.warn(message); try { throw new Error(message); } catch (e) { } } } function createKey() { return Math.random().toString(36).substring(2, 10); } function getHistoryState(location, index) { return { usr: location.state, key: location.key, idx: index, masked: location.mask ? { pathname: location.pathname, search: location.search, hash: location.hash } : void 0 }; } function createLocation(current, to, state = null, key, mask) { let location = { pathname: typeof current === "string" ? current : current.pathname, search: "", hash: "", ...typeof to === "string" ? parsePath(to) : to, state, // TODO: This could be cleaned up. push/replace should probably just take // full Locations now and avoid the need to run through this flow at all // But that's a pretty big refactor to the current test suite so going to // keep as is for the time being and just let any incoming keys take precedence key: to && to.key || key || createKey(), mask }; return location; } function createPath({ pathname = "/", search = "", hash = "" }) { if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; return pathname; } function parsePath(path) { let parsedPath = {}; if (path) { let hashIndex = path.indexOf("#"); if (hashIndex >= 0) { parsedPath.hash = path.substring(hashIndex); path = path.substring(0, hashIndex); } let searchIndex = path.indexOf("?"); if (searchIndex >= 0) { parsedPath.search = path.substring(searchIndex); path = path.substring(0, searchIndex); } if (path) { parsedPath.pathname = path; } } return parsedPath; } function getUrlBasedHistory(getLocation, createHref2, validateLocation, options = {}) { let { window: window2 = document.defaultView, v5Compat = false } = options; let globalHistory = window2.history; let action = "POP" /* Pop */; let listener = null; let index = getIndex(); if (index == null) { index = 0; globalHistory.replaceState({ ...globalHistory.state, idx: index }, ""); } function getIndex() { let state = globalHistory.state || { idx: null }; return state.idx; } function handlePop() { action = "POP" /* Pop */; let nextIndex = getIndex(); let delta = nextIndex == null ? null : nextIndex - index; index = nextIndex; if (listener) { listener({ action, location: history.location, delta }); } } function push(to, state) { action = "PUSH" /* Push */; let location = isLocation(to) ? to : createLocation(history.location, to, state); if (validateLocation) validateLocation(location, to); index = getIndex() + 1; let historyState = getHistoryState(location, index); let url = history.createHref(location.mask || location); try { globalHistory.pushState(historyState, "", url); } catch (error) { if (error instanceof DOMException && error.name === "DataCloneError") { throw error; } window2.location.assign(url); } if (v5Compat && listener) { listener({ action, location: history.location, delta: 1 }); } } function replace2(to, state) { action = "REPLACE" /* Replace */; let location = isLocation(to) ? to : createLocation(history.location, to, state); if (validateLocation) validateLocation(location, to); index = getIndex(); let historyState = getHistoryState(location, index); let url = history.createHref(location.mask || location); globalHistory.replaceState(historyState, "", url); if (v5Compat && listener) { listener({ action, location: history.location, delta: 0 }); } } function createURL(to) { return createBrowserURLImpl(to); } let history = { get action() { return action; }, get location() { return getLocation(window2, globalHistory); }, listen(fn) { if (listener) { throw new Error("A history only accepts one active listener"); } window2.addEventListener(PopStateEventType, handlePop); listener = fn; return () => { window2.removeEventListener(PopStateEventType, handlePop); listener = null; }; }, createHref(to) { return createHref2(window2, to); }, createURL, encodeLocation(to) { let url = createURL(to); return { pathname: url.pathname, search: url.search, hash: url.hash }; }, push, replace: replace2, go(n) { return globalHistory.go(n); } }; return history; } function createBrowserURLImpl(to, isAbsolute = false) { let base = "http://localhost"; if (typeof window !== "undefined") { base = window.location.origin !== "null" ? window.location.origin : window.location.href; } invariant(base, "No window.location.(origin|href) available to create URL"); let href = typeof to === "string" ? to : createPath(to); href = href.replace(/ $/, "%20"); if (!isAbsolute && href.startsWith("//")) { href = base + href; } return new URL(href, base); } // lib/router/utils.ts function createContext(defaultValue) { return { defaultValue }; } var _map; var RouterContextProvider = class { /** * Create a new `RouterContextProvider` instance * @param init An optional initial context map to populate the provider with */ constructor(init) { __privateAdd(this, _map, /* @__PURE__ */ new Map()); if (init) { for (let [context, value] of init) { this.set(context, value); } } } /** * Access a value from the context. If no value has been set for the context, * it will return the context's `defaultValue` if provided, or throw an error * if no `defaultValue` was set. * @param context The context to get the value for * @returns The value for the context, or the context's `defaultValue` if no * value was set */ get(context) { if (__privateGet(this, _map).has(context)) { return __privateGet(this, _map).get(context); } if (context.defaultValue !== void 0) { return context.defaultValue; } throw new Error("No value found for context"); } /** * Set a value for the context. If the context already has a value set, this * will overwrite it. * * @param context The context to set the value for * @param value The value to set for the context * @returns {void} */ set(context, value) { __privateGet(this, _map).set(context, value); } }; _map = new WeakMap(); var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([ "lazy", "caseSensitive", "path", "id", "index", "children" ]); function isUnsupportedLazyRouteObjectKey(key) { return unsupportedLazyRouteObjectKeys.has( key ); } var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([ "lazy", "caseSensitive", "path", "id", "index", "middleware", "children" ]); function isUnsupportedLazyRouteFunctionKey(key) { return unsupportedLazyRouteFunctionKeys.has( key ); } function isIndexRoute(route) { return route.index === true; } function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}, allowInPlaceMutations = false) { return routes.map((route, index) => { let treePath = [...parentPath, String(index)]; let id = typeof route.id === "string" ? route.id : treePath.join("-"); invariant( route.index !== true || !route.children, `Cannot specify children on an index route` ); invariant( allowInPlaceMutations || !manifest[id], `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages` ); if (isIndexRoute(route)) { let indexRoute = { ...route, id }; manifest[id] = mergeRouteUpdates( indexRoute, mapRouteProperties2(indexRoute) ); return indexRoute; } else { let pathOrLayoutRoute = { ...route, id, children: void 0 }; manifest[id] = mergeRouteUpdates( pathOrLayoutRoute, mapRouteProperties2(pathOrLayoutRoute) ); if (route.children) { pathOrLayoutRoute.children = convertRoutesToDataRoutes( route.children, mapRouteProperties2, treePath, manifest, allowInPlaceMutations ); } return pathOrLayoutRoute; } }); } function mergeRouteUpdates(route, updates) { return Object.assign(route, { ...updates, ...typeof updates.lazy === "object" && updates.lazy != null ? { lazy: { ...route.lazy, ...updates.lazy } } : {} }); } function matchRoutes(routes, locationArg, basename = "/") { return matchRoutesImpl(routes, locationArg, basename, false); } function matchRoutesImpl(routes, locationArg, basename, allowPartial, precomputedBranches) { let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; let pathname = stripBasename(location.pathname || "/", basename); if (pathname == null) { return null; } let branches = precomputedBranches ?? flattenAndRankRoutes(routes); let matches = null; let decoded = decodePath(pathname); for (let i = 0; matches == null && i < branches.length; ++i) { matches = matchRouteBranch( branches[i], decoded, allowPartial ); } return matches; } function convertRouteMatchToUiMatch(match, loaderData) { let { route, pathname, params } = match; return { id: route.id, pathname, params, data: loaderData[route.id], loaderData: loaderData[route.id], handle: route.handle }; } function flattenAndRankRoutes(routes) { let branches = flattenRoutes(routes); rankRouteBranches(branches); return branches; } function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "", _hasParentOptionalSegments = false) { let flattenRoute = (route, index, hasParentOptionalSegments = _hasParentOptionalSegments, relativePath) => { let meta = { relativePath: relativePath === void 0 ? route.path || "" : relativePath, caseSensitive: route.caseSensitive === true, childrenIndex: index, route }; if (meta.relativePath.startsWith("/")) { if (!meta.relativePath.startsWith(parentPath) && hasParentOptionalSegments) { return; } invariant( meta.relativePath.startsWith(parentPath), `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.` ); meta.relativePath = meta.relativePath.slice(parentPath.length); } let path = joinPaths([parentPath, meta.relativePath]); let routesMeta = parentsMeta.concat(meta); if (route.children && route.children.length > 0) { invariant( // Our types know better, but runtime JS may not! // @ts-expect-error route.index !== true, `Index routes must not have child routes. Please remove all child routes from route path "${path}".` ); flattenRoutes( route.children, branches, routesMeta, path, hasParentOptionalSegments ); } if (route.path == null && !route.index) { return; } branches.push({ path, score: computeScore(path, route.index), routesMeta }); }; routes.forEach((route, index) => { if (route.path === "" || !route.path?.includes("?")) { flattenRoute(route, index); } else { for (let exploded of explodeOptionalSegments(route.path)) { flattenRoute(route, index, true, exploded); } } }); return branches; } function explodeOptionalSegments(path) { let segments = path.split("/"); if (segments.length === 0) return []; let [first, ...rest] = segments; let isOptional = first.endsWith("?"); let required = first.replace(/\?$/, ""); if (rest.length === 0) { return isOptional ? [required, ""] : [required]; } let restExploded = explodeOptionalSegments(rest.join("/")); let result = []; result.push( ...restExploded.map( (subpath) => subpath === "" ? required : [required, subpath].join("/") ) ); if (isOptional) { result.push(...restExploded); } return result.map( (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded ); } function rankRouteBranches(branches) { branches.sort( (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes( a.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex) ) ); } var paramRe = /^:[\w-]+$/; var dynamicSegmentValue = 3; var indexRouteValue = 2; var emptySegmentValue = 1; var staticSegmentValue = 10; var splatPenalty = -2; var isSplat = (s) => s === "*"; function computeScore(path, index) { let segments = path.split("/"); let initialScore = segments.length; if (segments.some(isSplat)) { initialScore += splatPenalty; } if (index) { initialScore += indexRouteValue; } return segments.filter((s) => !isSplat(s)).reduce( (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore ); } function compareIndexes(a, b) { let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); return siblings ? ( // If two routes are siblings, we should try to match the earlier sibling // first. This allows people to have fine-grained control over the matching // behavior by simply putting routes with identical paths in the order they // want them tried. a[a.length - 1] - b[b.length - 1] ) : ( // Otherwise, it doesn't really make sense to rank non-siblings by index, // so they sort equally. 0 ); } function matchRouteBranch(branch, pathname, allowPartial = false) { let { routesMeta } = branch; let matchedParams = {}; let matchedPathname = "/"; let matches = []; for (let i = 0; i < routesMeta.length; ++i) { let meta = routesMeta[i]; let end = i === routesMeta.length - 1; let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; let match = matchPath( { path: meta.relativePath, caseSensitive: meta.caseSensitive, end }, remainingPathname ); let route = meta.route; if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) { match = matchPath( { path: meta.relativePath, caseSensitive: meta.caseSensitive, end: false }, remainingPathname ); } if (!match) { return null; } Object.assign(matchedParams, match.params); matches.push({ // TODO: Can this as be avoided? params: matchedParams, pathname: joinPaths([matchedPathname, match.pathname]), pathnameBase: normalizePathname( joinPaths([matchedPathname, match.pathnameBase]) ), route }); if (match.pathnameBase !== "/") { matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); } } return matches; } function generatePath(originalPath, params = {}) { let path = originalPath; if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { warning( false, `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".` ); path = path.replace(/\*$/, "/*"); } const prefix = path.startsWith("/") ? "/" : ""; const stringify2 = (p) => p == null ? "" : typeof p === "string" ? p : String(p); const segments = path.split(/\/+/).map((segment, index, array) => { const isLastSegment = index === array.length - 1; if (isLastSegment && segment === "*") { return stringify2(params["*"]); } const keyMatch = segment.match(/^:([\w-]+)(\??)(.*)/); if (keyMatch) { const [, key, optional, suffix] = keyMatch; let param = params[key]; invariant(optional === "?" || param != null, `Missing ":${key}" param`); return encodeURIComponent(stringify2(param)) + suffix; } return segment.replace(/\?$/g, ""); }).filter((segment) => !!segment); return prefix + segments.join("/"); } function matchPath(pattern, pathname) { if (typeof pattern === "string") { pattern = { path: pattern, caseSensitive: false, end: true }; } let [matcher, compiledParams] = compilePath( pattern.path, pattern.caseSensitive, pattern.end ); let match = pathname.match(matcher); if (!match) return null; let matchedPathname = match[0]; let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); let captureGroups = match.slice(1); let params = compiledParams.reduce( (memo2, { paramName, isOptional }, index) => { if (paramName === "*") { let splatValue = captureGroups[index] || ""; pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); } const value = captureGroups[index]; if (isOptional && !value) { memo2[paramName] = void 0; } else { memo2[paramName] = (value || "").replace(/%2F/g, "/"); } return memo2; }, {} ); return { params, pathname: matchedPathname, pathnameBase, pattern }; } function compilePath(path, caseSensitive = false, end = true) { warning( path === "*" || !path.endsWith("*") || path.endsWith("/*"), `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".` ); let params = []; let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace( /\/:([\w-]+)(\?)?/g, (match, paramName, isOptional, index, str) => { params.push({ paramName, isOptional: isOptional != null }); if (isOptional) { let nextChar = str.charAt(index + match.length); if (nextChar && nextChar !== "/") { return "/([^\\/]*)"; } return "(?:/([^\\/]*))?"; } return "/([^\\/]+)"; } ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2"); if (path.endsWith("*")) { params.push({ paramName: "*" }); regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$"; } else if (end) { regexpSource += "\\/*$"; } else if (path !== "" && path !== "/") { regexpSource += "(?:(?=\\/|$))"; } else { } let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i"); return [matcher, params]; } function decodePath(value) { try { return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/"); } catch (error) { warning( false, `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).` ); return value; } } function stripBasename(pathname, basename) { if (basename === "/") return pathname; if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { return null; } let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; let nextChar = pathname.charAt(startIndex); if (nextChar && nextChar !== "/") { return null; } return pathname.slice(startIndex) || "/"; } function prependBasename({ basename, pathname }) { return pathname === "/" ? basename : joinPaths([basename, pathname]); } var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; var isAbsoluteUrl = (url) => ABSOLUTE_URL_REGEX.test(url); function resolvePath(to, fromPathname = "/") { let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(to) : to; let pathname; if (toPathname) { toPathname = removeDoubleSlashes(toPathname); if (toPathname.startsWith("/")) { pathname = resolvePathname(toPathname.substring(1), "/"); } else { pathname = resolvePathname(toPathname, fromPathname); } } else { pathname = fromPathname; } return { pathname, search: normalizeSearch(search), hash: normalizeHash(hash) }; } function resolvePathname(relativePath, fromPathname) { let segments = removeTrailingSlash(fromPathname).split("/"); let relativeSegments = relativePath.split("/"); relativeSegments.forEach((segment) => { if (segment === "..") { if (segments.length > 1) segments.pop(); } else if (segment !== ".") { segments.push(segment); } }); return segments.length > 1 ? segments.join("/") : "/"; } function getInvalidPathError(char, field, dest, path) { return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify( path )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`; } function getPathContributingMatches(matches) { return matches.filter( (match, index) => index === 0 || match.route.path && match.route.path.length > 0 ); } function getResolveToMatches(matches) { let pathMatches = getPathContributingMatches(matches); return pathMatches.map( (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase ); } function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) { let to; if (typeof toArg === "string") { to = parsePath(toArg); } else { to = { ...toArg }; invariant( !to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to) ); invariant( !to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to) ); invariant( !to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to) ); } let isEmptyPath = toArg === "" || to.pathname === ""; let toPathname = isEmptyPath ? "/" : to.pathname; let from; if (toPathname == null) { from = locationPathname; } else { let routePathnameIndex = routePathnames.length - 1; if (!isPathRelative && toPathname.startsWith("..")) { let toSegments = toPathname.split("/"); while (toSegments[0] === "..") { toSegments.shift(); routePathnameIndex -= 1; } to.pathname = toSegments.join("/"); } from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; } let path = resolvePath(to, from); let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { path.pathname += "/"; } return path; } var removeDoubleSlashes = (path) => path.replace(/\/\/+/g, "/"); var joinPaths = (paths) => removeDoubleSlashes(paths.join("/")); var removeTrailingSlash = (path) => path.replace(/\/+$/, ""); var normalizePathname = (pathname) => removeTrailingSlash(pathname).replace(/^\/*/, "/"); var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; var DataWithResponseInit = class { constructor(data2, init) { this.type = "DataWithResponseInit"; this.data = data2; this.init = init || null; } }; function data(data2, init) { return new DataWithResponseInit( data2, typeof init === "number" ? { status: init } : init ); } var redirect = (url, init = 302) => { let responseInit = init; if (typeof responseInit === "number") { responseInit = { status: responseInit }; } else if (typeof responseInit.status === "undefined") { responseInit.status = 302; } let headers = new Headers(responseInit.headers); headers.set("Location", url); return new Response(null, { ...responseInit, headers }); }; var redirectDocument = (url, init) => { let response = redirect(url, init); response.headers.set("X-Remix-Reload-Document", "true"); return response; }; var replace = (url, init) => { let response = redirect(url, init); response.headers.set("X-Remix-Replace", "true"); return response; }; var ErrorResponseImpl = class { constructor(status, statusText, data2, internal = false) { this.status = status; this.statusText = statusText || ""; this.internal = internal; if (data2 instanceof Error) { this.data = data2.toString(); this.error = data2; } else { this.data = data2; } } }; function isRouteErrorResponse(error) { return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; } function getRoutePattern(matches) { let parts = matches.map((m) => m.route.path).filter(Boolean); return joinPaths(parts) || "/"; } var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"; function parseToInfo(_to, basename) { let to = _to; if (typeof to !== "string" || !ABSOLUTE_URL_REGEX.test(to)) { return { absoluteURL: void 0, isExternal: false, to }; } let absoluteURL = to; let isExternal = false; if (isBrowser) { try { let currentUrl = new URL(window.location.href); let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to); let path = stripBasename(targetUrl.pathname, basename); if (targetUrl.origin === currentUrl.origin && path != null) { to = path + targetUrl.search + targetUrl.hash; } else { isExternal = true; } } catch (e) { warning( false, ` contains an invalid URL which will probably break when clicked - please update to a valid URL path.` ); } } return { absoluteURL, isExternal, to }; } // lib/router/instrumentation.ts var UninstrumentedSymbol = Symbol("Uninstrumented"); function getRouteInstrumentationUpdates(fns, route) { let aggregated = { lazy: [], "lazy.loader": [], "lazy.action": [], "lazy.middleware": [], middleware: [], loader: [], action: [] }; fns.forEach( (fn) => fn({ id: route.id, index: route.index, path: route.path, instrument(i) { let keys = Object.keys(aggregated); for (let key of keys) { if (i[key]) { aggregated[key].push(i[key]); } } } }) ); let updates = {}; if (typeof route.lazy === "function" && aggregated.lazy.length > 0) { let instrumented = wrapImpl(aggregated.lazy, route.lazy, () => void 0); if (instrumented) { updates.lazy = instrumented; } } if (typeof route.lazy === "object") { let lazyObject = route.lazy; ["middleware", "loader", "action"].forEach((key) => { let lazyFn = lazyObject[key]; let instrumentations = aggregated[`lazy.${key}`]; if (typeof lazyFn === "function" && instrumentations.length > 0) { let instrumented = wrapImpl(instrumentations, lazyFn, () => void 0); if (instrumented) { updates.lazy = Object.assign(updates.lazy || {}, { [key]: instrumented }); } } }); } ["loader", "action"].forEach((key) => { let handler = route[key]; if (typeof handler === "function" && aggregated[key].length > 0) { let original = handler[UninstrumentedSymbol] ?? handler; let instrumented = wrapImpl( aggregated[key], original, (...args) => getHandlerInfo(args[0]) ); if (instrumented) { if (key === "loader" && original.hydrate === true) { instrumented.hydrate = true; } instrumented[UninstrumentedSymbol] = original; updates[key] = instrumented; } } }); if (route.middleware && route.middleware.length > 0 && aggregated.middleware.length > 0) { updates.middleware = route.middleware.map((middleware) => { let original = middleware[UninstrumentedSymbol] ?? middleware; let instrumented = wrapImpl( aggregated.middleware, original, (...args) => getHandlerInfo(args[0]) ); if (instrumented) { instrumented[UninstrumentedSymbol] = original; return instrumented; } return middleware; }); } return updates; } function instrumentClientSideRouter(router, fns) { let aggregated = { navigate: [], fetch: [] }; fns.forEach( (fn) => fn({ instrument(i) { let keys = Object.keys(i); for (let key of keys) { if (i[key]) { aggregated[key].push(i[key]); } } } }) ); if (aggregated.navigate.length > 0) { let navigate = router.navigate[UninstrumentedSymbol] ?? router.navigate; let instrumentedNavigate = wrapImpl( aggregated.navigate, navigate, (...args) => { let [to, opts] = args; return { to: typeof to === "number" || typeof to === "string" ? to : to ? createPath(to) : ".", ...getRouterInfo(router, opts ?? {}) }; } ); if (instrumentedNavigate) { instrumentedNavigate[UninstrumentedSymbol] = navigate; router.navigate = instrumentedNavigate; } } if (aggregated.fetch.length > 0) { let fetch2 = router.fetch[UninstrumentedSymbol] ?? router.fetch; let instrumentedFetch = wrapImpl(aggregated.fetch, fetch2, (...args) => { let [key, , href, opts] = args; return { href: href ?? ".", fetcherKey: key, ...getRouterInfo(router, opts ?? {}) }; }); if (instrumentedFetch) { instrumentedFetch[UninstrumentedSymbol] = fetch2; router.fetch = instrumentedFetch; } } return router; } function instrumentHandler(handler, fns) { let aggregated = { request: [] }; fns.forEach( (fn) => fn({ instrument(i) { let keys = Object.keys(i); for (let key of keys) { if (i[key]) { aggregated[key].push(i[key]); } } } }) ); let instrumentedHandler = handler; if (aggregated.request.length > 0) { instrumentedHandler = wrapImpl(aggregated.request, handler, (...args) => { let [request, context] = args; return { request: getReadonlyRequest(request), context: context != null ? getReadonlyContext(context) : context }; }); } return instrumentedHandler; } function wrapImpl(impls, handler, getInfo) { if (impls.length === 0) { return null; } return async (...args) => { let result = await recurseRight( impls, getInfo(...args), () => handler(...args), impls.length - 1 ); if (result.type === "error") { throw result.value; } return result.value; }; } async function recurseRight(impls, info, handler, index) { let impl = impls[index]; let result; if (!impl) { try { let value = await handler(); result = { type: "success", value }; } catch (e) { result = { type: "error", value: e }; } } else { let handlerPromise = void 0; let callHandler = async () => { if (handlerPromise) { console.error("You cannot call instrumented handlers more than once"); } else { handlerPromise = recurseRight(impls, info, handler, index - 1); } result = await handlerPromise; invariant(result, "Expected a result"); if (result.type === "error" && result.value instanceof Error) { return { status: "error", error: result.value }; } return { status: "success", error: void 0 }; }; try { await impl(callHandler, info); } catch (e) { console.error("An instrumentation function threw an error:", e); } if (!handlerPromise) { await callHandler(); } await handlerPromise; } if (result) { return result; } return { type: "error", value: new Error("No result assigned in instrumentation chain.") }; } function getHandlerInfo(args) { let { request, context, params, pattern } = args; return { request: getReadonlyRequest(request), params: { ...params }, pattern, context: getReadonlyContext(context) }; } function getRouterInfo(router, opts) { return { currentUrl: createPath(router.state.location), ..."formMethod" in opts ? { formMethod: opts.formMethod } : {}, ..."formEncType" in opts ? { formEncType: opts.formEncType } : {}, ..."formData" in opts ? { formData: opts.formData } : {}, ..."body" in opts ? { body: opts.body } : {} }; } function getReadonlyRequest(request) { return { method: request.method, url: request.url, headers: { get: (...args) => request.headers.get(...args) } }; } function getReadonlyContext(context) { if (isPlainObject(context)) { let frozen = { ...context }; Object.freeze(frozen); return frozen; } else { return { get: (ctx) => context.get(ctx) }; } } var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); function isPlainObject(thing) { if (thing === null || typeof thing !== "object") { return false; } const proto = Object.getPrototypeOf(thing); return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames; } // lib/router/router.ts var validMutationMethodsArr = [ "POST", "PUT", "PATCH", "DELETE" ]; var validMutationMethods = new Set( validMutationMethodsArr ); var validRequestMethodsArr = [ "GET", ...validMutationMethodsArr ]; var validRequestMethods = new Set(validRequestMethodsArr); var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]); var IDLE_NAVIGATION = { state: "idle", location: void 0, formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0 }; var IDLE_FETCHER = { state: "idle", data: void 0, formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0 }; var IDLE_BLOCKER = { state: "unblocked", proceed: void 0, reset: void 0, location: void 0 }; var defaultMapRouteProperties = (route) => ({ hasErrorBoundary: Boolean(route.hasErrorBoundary) }); var TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; var ResetLoaderDataSymbol = Symbol("ResetLoaderData"); var _routes, _branches, _hmrRoutes, _hmrBranches; var DataRoutes = class { constructor(routes) { __privateAdd(this, _routes); __privateAdd(this, _branches); __privateAdd(this, _hmrRoutes); __privateAdd(this, _hmrBranches); __privateSet(this, _routes, routes); __privateSet(this, _branches, flattenAndRankRoutes(routes)); } /** The stable route tree */ get stableRoutes() { return __privateGet(this, _routes); } /** The in-flight route tree if one is active, otherwise the stable tree */ get activeRoutes() { return __privateGet(this, _hmrRoutes) ?? __privateGet(this, _routes); } /** Pre-computed branches */ get branches() { return __privateGet(this, _hmrBranches) ?? __privateGet(this, _branches); } get hasHMRRoutes() { return __privateGet(this, _hmrRoutes) != null; } /** Replace the stable route tree and recompute its branches */ setRoutes(routes) { __privateSet(this, _routes, routes); __privateSet(this, _branches, flattenAndRankRoutes(routes)); } /** Set a new in-flight route tree and recompute its branches */ setHmrRoutes(routes) { __privateSet(this, _hmrRoutes, routes); __privateSet(this, _hmrBranches, flattenAndRankRoutes(routes)); } /** Commit in-flight routes/branches to the stable slot and clear in-flight */ commitHmrRoutes() { if (__privateGet(this, _hmrRoutes)) { __privateSet(this, _routes, __privateGet(this, _hmrRoutes)); __privateSet(this, _branches, __privateGet(this, _hmrBranches)); __privateSet(this, _hmrRoutes, void 0); __privateSet(this, _hmrBranches, void 0); } } }; _routes = new WeakMap(); _branches = new WeakMap(); _hmrRoutes = new WeakMap(); _hmrBranches = new WeakMap(); function createRouter(init) { const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0; const isBrowser3 = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; invariant( init.routes.length > 0, "You must provide a non-empty routes array to createRouter" ); let hydrationRouteProperties2 = init.hydrationRouteProperties || []; let _mapRouteProperties = init.mapRouteProperties || defaultMapRouteProperties; let mapRouteProperties2 = _mapRouteProperties; if (init.instrumentations) { let instrumentations = init.instrumentations; mapRouteProperties2 = (route) => { return { ..._mapRouteProperties(route), ...getRouteInstrumentationUpdates( instrumentations.map((i) => i.route).filter(Boolean), route ) }; }; } let manifest = {}; let dataRoutes = new DataRoutes( convertRoutesToDataRoutes( init.routes, mapRouteProperties2, void 0, manifest ) ); let basename = init.basename || "/"; if (!basename.startsWith("/")) { basename = `/${basename}`; } let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware; let future = { ...init.future }; let unlistenHistory = null; let subscribers = /* @__PURE__ */ new Set(); let savedScrollPositions2 = null; let getScrollRestorationKey2 = null; let getScrollPosition = null; let initialScrollRestored = init.hydrationData != null; let initialMatches = matchRoutesImpl( dataRoutes.activeRoutes, init.history.location, basename, false, dataRoutes.branches ); let initialMatchesIsFOW = false; let initialErrors = null; let initialized; let renderFallback; if (initialMatches == null && !init.patchRoutesOnNavigation) { let error = getInternalRouterError(404, { pathname: init.history.location.pathname }); let { matches, route } = getShortCircuitMatches(dataRoutes.activeRoutes); initialized = true; renderFallback = !initialized; initialMatches = matches; initialErrors = { [route.id]: error }; } else { if (initialMatches && !init.hydrationData) { let fogOfWar = checkFogOfWar( initialMatches, dataRoutes.activeRoutes, init.history.location.pathname ); if (fogOfWar.active) { initialMatches = null; } } if (!initialMatches) { initialized = false; renderFallback = !initialized; initialMatches = []; let fogOfWar = checkFogOfWar( null, dataRoutes.activeRoutes, init.history.location.pathname ); if (fogOfWar.active && fogOfWar.matches) { initialMatchesIsFOW = true; initialMatches = fogOfWar.matches; } } else if (initialMatches.some((m) => m.route.lazy)) { initialized = false; renderFallback = !initialized; } else if (!initialMatches.some((m) => routeHasLoaderOrMiddleware(m.route))) { initialized = true; renderFallback = !initialized; } else { let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; let errors = init.hydrationData ? init.hydrationData.errors : null; let relevantMatches = initialMatches; if (errors) { let idx = initialMatches.findIndex( (m) => errors[m.route.id] !== void 0 ); relevantMatches = relevantMatches.slice(0, idx + 1); } renderFallback = false; initialized = true; relevantMatches.forEach((m) => { let status = getRouteHydrationStatus(m.route, loaderData, errors); renderFallback = renderFallback || status.renderFallback; initialized = initialized && !status.shouldLoad; }); } } let router; let state = { historyAction: init.history.action, location: init.history.location, matches: initialMatches, initialized, renderFallback, navigation: IDLE_NAVIGATION, // Don't restore on initial updateState() if we were SSR'd restoreScrollPosition: init.hydrationData != null ? false : null, preventScrollReset: false, revalidation: "idle", loaderData: init.hydrationData && init.hydrationData.loaderData || {}, actionData: init.hydrationData && init.hydrationData.actionData || null, errors: init.hydrationData && init.hydrationData.errors || initialErrors, fetchers: /* @__PURE__ */ new Map(), blockers: /* @__PURE__ */ new Map() }; let pendingAction = "POP" /* Pop */; let pendingPopstateNavigationDfd = null; let pendingPreventScrollReset = false; let pendingNavigationController; let pendingViewTransitionEnabled = false; let appliedViewTransitions = /* @__PURE__ */ new Map(); let removePageHideEventListener = null; let isUninterruptedRevalidation = false; let isRevalidationRequired = false; let cancelledFetcherLoads = /* @__PURE__ */ new Set(); let fetchControllers = /* @__PURE__ */ new Map(); let incrementingLoadId = 0; let pendingNavigationLoadId = -1; let fetchReloadIds = /* @__PURE__ */ new Map(); let fetchRedirectIds = /* @__PURE__ */ new Set(); let fetchLoadMatches = /* @__PURE__ */ new Map(); let activeFetchers = /* @__PURE__ */ new Map(); let fetchersQueuedForDeletion = /* @__PURE__ */ new Set(); let blockerFunctions = /* @__PURE__ */ new Map(); let unblockBlockerHistoryUpdate = void 0; let pendingRevalidationDfd = null; function initialize() { unlistenHistory = init.history.listen( ({ action: historyAction, location, delta }) => { if (unblockBlockerHistoryUpdate) { unblockBlockerHistoryUpdate(); unblockBlockerHistoryUpdate = void 0; return; } warning( blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL." ); let blockerKey = shouldBlockNavigation({ currentLocation: state.location, nextLocation: location, historyAction }); if (blockerKey && delta != null) { let nextHistoryUpdatePromise = new Promise((resolve) => { unblockBlockerHistoryUpdate = resolve; }); init.history.go(delta * -1); updateBlocker(blockerKey, { state: "blocked", location, proceed() { updateBlocker(blockerKey, { state: "proceeding", proceed: void 0, reset: void 0, location }); nextHistoryUpdatePromise.then(() => init.history.go(delta)); }, reset() { let blockers = new Map(state.blockers); blockers.set(blockerKey, IDLE_BLOCKER); updateState({ blockers }); } }); pendingPopstateNavigationDfd?.resolve(); pendingPopstateNavigationDfd = null; return; } return startNavigation(historyAction, location); } ); if (isBrowser3) { restoreAppliedTransitions(routerWindow, appliedViewTransitions); let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); routerWindow.addEventListener("pagehide", _saveAppliedTransitions); removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); } if (!state.initialized) { startNavigation("POP" /* Pop */, state.location, { initialHydration: true }); } return router; } function dispose() { if (unlistenHistory) { unlistenHistory(); } if (removePageHideEventListener) { removePageHideEventListener(); } subscribers.clear(); pendingNavigationController && pendingNavigationController.abort(); state.fetchers.forEach((_, key) => deleteFetcher(key)); state.blockers.forEach((_, key) => deleteBlocker(key)); } function subscribe(fn) { subscribers.add(fn); return () => subscribers.delete(fn); } function updateState(newState, opts = {}) { if (newState.matches) { newState.matches = newState.matches.map((m) => { let route = manifest[m.route.id]; let matchRoute = m.route; if (matchRoute.element !== route.element || matchRoute.errorElement !== route.errorElement || matchRoute.hydrateFallbackElement !== route.hydrateFallbackElement) { return { ...m, route }; } return m; }); } state = { ...state, ...newState }; let unmountedFetchers = []; let mountedFetchers = []; state.fetchers.forEach((fetcher, key) => { if (fetcher.state === "idle") { if (fetchersQueuedForDeletion.has(key)) { unmountedFetchers.push(key); } else { mountedFetchers.push(key); } } }); fetchersQueuedForDeletion.forEach((key) => { if (!state.fetchers.has(key) && !fetchControllers.has(key)) { unmountedFetchers.push(key); } }); [...subscribers].forEach( (subscriber) => subscriber(state, { deletedFetchers: unmountedFetchers, newErrors: newState.errors ?? null, viewTransitionOpts: opts.viewTransitionOpts, flushSync: opts.flushSync === true }) ); unmountedFetchers.forEach((key) => deleteFetcher(key)); mountedFetchers.forEach((key) => state.fetchers.delete(key)); } function completeNavigation(location, newState, { flushSync } = {}) { let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && location.state?._isRedirect !== true; let actionData; if (newState.actionData) { if (Object.keys(newState.actionData).length > 0) { actionData = newState.actionData; } else { actionData = null; } } else if (isActionReload) { actionData = state.actionData; } else { actionData = null; } let loaderData = newState.loaderData ? mergeLoaderData( state.loaderData, newState.loaderData, newState.matches || [], newState.errors ) : state.loaderData; let blockers = state.blockers; if (blockers.size > 0) { blockers = new Map(blockers); blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); } let restoreScrollPosition = isUninterruptedRevalidation ? false : getSavedScrollPosition(location, newState.matches || state.matches); let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && location.state?._isRedirect !== true; dataRoutes.commitHmrRoutes(); if (isUninterruptedRevalidation) { } else if (pendingAction === "POP" /* Pop */) { } else if (pendingAction === "PUSH" /* Push */) { init.history.push(location, location.state); } else if (pendingAction === "REPLACE" /* Replace */) { init.history.replace(location, location.state); } let viewTransitionOpts; if (pendingAction === "POP" /* Pop */) { let priorPaths = appliedViewTransitions.get(state.location.pathname); if (priorPaths && priorPaths.has(location.pathname)) { viewTransitionOpts = { currentLocation: state.location, nextLocation: location }; } else if (appliedViewTransitions.has(location.pathname)) { viewTransitionOpts = { currentLocation: location, nextLocation: state.location }; } } else if (pendingViewTransitionEnabled) { let toPaths = appliedViewTransitions.get(state.location.pathname); if (toPaths) { toPaths.add(location.pathname); } else { toPaths = /* @__PURE__ */ new Set([location.pathname]); appliedViewTransitions.set(state.location.pathname, toPaths); } viewTransitionOpts = { currentLocation: state.location, nextLocation: location }; } updateState( { ...newState, // matches, errors, fetchers go through as-is actionData, loaderData, historyAction: pendingAction, location, initialized: true, renderFallback: false, navigation: IDLE_NAVIGATION, revalidation: "idle", restoreScrollPosition, preventScrollReset, blockers }, { viewTransitionOpts, flushSync: flushSync === true } ); pendingAction = "POP" /* Pop */; pendingPreventScrollReset = false; pendingViewTransitionEnabled = false; isUninterruptedRevalidation = false; isRevalidationRequired = false; pendingPopstateNavigationDfd?.resolve(); pendingPopstateNavigationDfd = null; pendingRevalidationDfd?.resolve(); pendingRevalidationDfd = null; } async function navigate(to, opts) { pendingPopstateNavigationDfd?.resolve(); pendingPopstateNavigationDfd = null; if (typeof to === "number") { if (!pendingPopstateNavigationDfd) { pendingPopstateNavigationDfd = createDeferred(); } let promise = pendingPopstateNavigationDfd.promise; init.history.go(to); return promise; } let normalizedPath = normalizeTo( state.location, state.matches, basename, to, opts?.fromRouteId, opts?.relative ); let { path, submission, error } = normalizeNavigateOptions( false, normalizedPath, opts ); let maskPath; if (opts?.mask) { let partialPath = typeof opts.mask === "string" ? parsePath(opts.mask) : { ...state.location.mask, ...opts.mask }; maskPath = { pathname: "", search: "", hash: "", ...partialPath }; } let currentLocation = state.location; let nextLocation = createLocation( currentLocation, path, opts && opts.state, void 0, maskPath ); nextLocation = { ...nextLocation, ...init.history.encodeLocation(nextLocation) }; let userReplace = opts && opts.replace != null ? opts.replace : void 0; let historyAction = "PUSH" /* Push */; if (userReplace === true) { historyAction = "REPLACE" /* Replace */; } else if (userReplace === false) { } else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { historyAction = "REPLACE" /* Replace */; } let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0; let flushSync = (opts && opts.flushSync) === true; let blockerKey = shouldBlockNavigation({ currentLocation, nextLocation, historyAction }); if (blockerKey) { updateBlocker(blockerKey, { state: "blocked", location: nextLocation, proceed() { updateBlocker(blockerKey, { state: "proceeding", proceed: void 0, reset: void 0, location: nextLocation }); navigate(to, opts); }, reset() { let blockers = new Map(state.blockers); blockers.set(blockerKey, IDLE_BLOCKER); updateState({ blockers }); } }); return; } await startNavigation(historyAction, nextLocation, { submission, // Send through the formData serialization error if we have one so we can // render at the right error boundary after we match routes pendingError: error, preventScrollReset, replace: opts && opts.replace, enableViewTransition: opts && opts.viewTransition, flushSync, callSiteDefaultShouldRevalidate: opts && opts.defaultShouldRevalidate }); } function revalidate() { if (!pendingRevalidationDfd) { pendingRevalidationDfd = createDeferred(); } interruptActiveLoads(); updateState({ revalidation: "loading" }); let promise = pendingRevalidationDfd.promise; if (state.navigation.state === "submitting") { return promise; } if (state.navigation.state === "idle") { startNavigation(state.historyAction, state.location, { startUninterruptedRevalidation: true }); return promise; } startNavigation( pendingAction || state.historyAction, state.navigation.location, { overrideNavigation: state.navigation, // Proxy through any rending view transition enableViewTransition: pendingViewTransitionEnabled === true } ); return promise; } async function startNavigation(historyAction, location, opts) { pendingNavigationController && pendingNavigationController.abort(); pendingNavigationController = null; pendingAction = historyAction; isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; saveScrollPosition(state.location, state.matches); pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; let routesToUse = dataRoutes.activeRoutes; let loadingNavigation = opts && opts.overrideNavigation; let matches = opts?.initialHydration && state.matches && state.matches.length > 0 && !initialMatchesIsFOW ? ( // `matchRoutes()` has already been called if we're in here via `router.initialize()` state.matches ) : matchRoutesImpl( routesToUse, location, basename, false, dataRoutes.branches ); let flushSync = (opts && opts.flushSync) === true; if (matches && state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { completeNavigation(location, { matches }, { flushSync }); return; } let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname); if (fogOfWar.active && fogOfWar.matches) { matches = fogOfWar.matches; } if (!matches) { let { error, notFoundMatches, route } = handleNavigational404( location.pathname ); completeNavigation( location, { matches: notFoundMatches, loaderData: {}, errors: { [route.id]: error } }, { flushSync } ); return; } pendingNavigationController = new AbortController(); let request = createClientSideRequest( init.history, location, pendingNavigationController.signal, opts && opts.submission ); let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider(); let pendingActionResult; if (opts && opts.pendingError) { pendingActionResult = [ findNearestBoundary(matches).route.id, { type: "error" /* error */, error: opts.pendingError } ]; } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { let actionResult = await handleAction( request, location, opts.submission, matches, scopedContext, fogOfWar.active, opts && opts.initialHydration === true, { replace: opts.replace, flushSync } ); if (actionResult.shortCircuited) { return; } if (actionResult.pendingActionResult) { let [routeId, result] = actionResult.pendingActionResult; if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) { pendingNavigationController = null; completeNavigation(location, { matches: actionResult.matches, loaderData: {}, errors: { [routeId]: result.error } }); return; } } matches = actionResult.matches || matches; pendingActionResult = actionResult.pendingActionResult; loadingNavigation = getLoadingNavigation(location, opts.submission); flushSync = false; fogOfWar.active = false; request = createClientSideRequest( init.history, request.url, request.signal ); } let { shortCircuited, matches: updatedMatches, loaderData, errors } = await handleLoaders( request, location, matches, scopedContext, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult, opts && opts.callSiteDefaultShouldRevalidate ); if (shortCircuited) { return; } pendingNavigationController = null; completeNavigation(location, { matches: updatedMatches || matches, ...getActionDataForCommit(pendingActionResult), loaderData, errors }); } async function handleAction(request, location, submission, matches, scopedContext, isFogOfWar, initialHydration, opts = {}) { interruptActiveLoads(); let navigation = getSubmittingNavigation(location, submission); updateState({ navigation }, { flushSync: opts.flushSync === true }); if (isFogOfWar) { let discoverResult = await discoverRoutes( matches, location.pathname, request.signal ); if (discoverResult.type === "aborted") { return { shortCircuited: true }; } else if (discoverResult.type === "error") { if (discoverResult.partialMatches.length === 0) { let { matches: matches2, route } = getShortCircuitMatches( dataRoutes.activeRoutes ); return { matches: matches2, pendingActionResult: [ route.id, { type: "error" /* error */, error: discoverResult.error } ] }; } let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id; return { matches: discoverResult.partialMatches, pendingActionResult: [ boundaryId, { type: "error" /* error */, error: discoverResult.error } ] }; } else if (!discoverResult.matches) { let { notFoundMatches, error, route } = handleNavigational404( location.pathname ); return { matches: notFoundMatches, pendingActionResult: [ route.id, { type: "error" /* error */, error } ] }; } else { matches = discoverResult.matches; } } let result; let actionMatch = getTargetMatch(matches, location); if (!actionMatch.route.action && !actionMatch.route.lazy) { result = { type: "error" /* error */, error: getInternalRouterError(405, { method: request.method, pathname: location.pathname, routeId: actionMatch.route.id }) }; } else { let dsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, request, location, matches, actionMatch, initialHydration ? [] : hydrationRouteProperties2, scopedContext ); let results = await callDataStrategy( request, location, dsMatches, scopedContext, null ); result = results[actionMatch.route.id]; if (!result) { for (let match of matches) { if (results[match.route.id]) { result = results[match.route.id]; break; } } } if (request.signal.aborted) { return { shortCircuited: true }; } } if (isRedirectResult(result)) { let replace2; if (opts && opts.replace != null) { replace2 = opts.replace; } else { let location2 = normalizeRedirectLocation( result.response.headers.get("Location"), new URL(request.url), basename, init.history ); replace2 = location2 === state.location.pathname + state.location.search; } await startRedirectNavigation(request, result, true, { submission, replace: replace2 }); return { shortCircuited: true }; } if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); if ((opts && opts.replace) !== true) { pendingAction = "PUSH" /* Push */; } return { matches, pendingActionResult: [ boundaryMatch.route.id, result, actionMatch.route.id ] }; } return { matches, pendingActionResult: [actionMatch.route.id, result] }; } async function handleLoaders(request, location, matches, scopedContext, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult, callSiteDefaultShouldRevalidate) { let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); let shouldUpdateNavigationState = !isUninterruptedRevalidation && !initialHydration; if (isFogOfWar) { if (shouldUpdateNavigationState) { let actionData = getUpdatedActionData(pendingActionResult); updateState( { navigation: loadingNavigation, ...actionData !== void 0 ? { actionData } : {} }, { flushSync } ); } let discoverResult = await discoverRoutes( matches, location.pathname, request.signal ); if (discoverResult.type === "aborted") { return { shortCircuited: true }; } else if (discoverResult.type === "error") { if (discoverResult.partialMatches.length === 0) { let { matches: matches2, route } = getShortCircuitMatches( dataRoutes.activeRoutes ); return { matches: matches2, loaderData: {}, errors: { [route.id]: discoverResult.error } }; } let boundaryId = findNearestBoundary(discoverResult.partialMatches).route.id; return { matches: discoverResult.partialMatches, loaderData: {}, errors: { [boundaryId]: discoverResult.error } }; } else if (!discoverResult.matches) { let { error, notFoundMatches, route } = handleNavigational404( location.pathname ); return { matches: notFoundMatches, loaderData: {}, errors: { [route.id]: error } }; } else { matches = discoverResult.matches; } } let routesToUse = dataRoutes.activeRoutes; let { dsMatches, revalidatingFetchers } = getMatchesToLoad( request, scopedContext, mapRouteProperties2, manifest, init.history, state, matches, activeSubmission, location, initialHydration ? [] : hydrationRouteProperties2, initialHydration === true, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, init.patchRoutesOnNavigation != null, dataRoutes.branches, pendingActionResult, callSiteDefaultShouldRevalidate ); pendingNavigationLoadId = ++incrementingLoadId; if (!init.dataStrategy && !dsMatches.some((m) => m.shouldLoad) && !dsMatches.some( (m) => m.route.middleware && m.route.middleware.length > 0 ) && revalidatingFetchers.length === 0) { let updatedFetchers2 = markFetchRedirectsDone(); completeNavigation( location, { matches, loaderData: {}, // Commit pending error if we're short circuiting errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null, ...getActionDataForCommit(pendingActionResult), ...updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {} }, { flushSync } ); return { shortCircuited: true }; } if (shouldUpdateNavigationState) { let updates = {}; if (!isFogOfWar) { updates.navigation = loadingNavigation; let actionData = getUpdatedActionData(pendingActionResult); if (actionData !== void 0) { updates.actionData = actionData; } } if (revalidatingFetchers.length > 0) { updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers); } updateState(updates, { flushSync }); } revalidatingFetchers.forEach((rf) => { abortFetcher(rf.key); if (rf.controller) { fetchControllers.set(rf.key, rf.controller); } }); let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key)); if (pendingNavigationController) { pendingNavigationController.signal.addEventListener( "abort", abortPendingFetchRevalidations ); } let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData( dsMatches, revalidatingFetchers, request, location, scopedContext ); if (request.signal.aborted) { return { shortCircuited: true }; } if (pendingNavigationController) { pendingNavigationController.signal.removeEventListener( "abort", abortPendingFetchRevalidations ); } revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key)); let redirect2 = findRedirect(loaderResults); if (redirect2) { await startRedirectNavigation(request, redirect2.result, true, { replace: replace2 }); return { shortCircuited: true }; } redirect2 = findRedirect(fetcherResults); if (redirect2) { fetchRedirectIds.add(redirect2.key); await startRedirectNavigation(request, redirect2.result, true, { replace: replace2 }); return { shortCircuited: true }; } let { loaderData, errors } = processLoaderData( state, matches, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults ); if (initialHydration && state.errors) { errors = { ...state.errors, ...errors }; } let updatedFetchers = markFetchRedirectsDone(); let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; return { matches, loaderData, errors, ...shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {} }; } function getUpdatedActionData(pendingActionResult) { if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { return { [pendingActionResult[0]]: pendingActionResult[1].data }; } else if (state.actionData) { if (Object.keys(state.actionData).length === 0) { return null; } else { return state.actionData; } } } function getUpdatedRevalidatingFetchers(revalidatingFetchers) { revalidatingFetchers.forEach((rf) => { let fetcher = state.fetchers.get(rf.key); let revalidatingFetcher = getLoadingFetcher( void 0, fetcher ? fetcher.data : void 0 ); state.fetchers.set(rf.key, revalidatingFetcher); }); return new Map(state.fetchers); } async function fetch2(key, routeId, href, opts) { abortFetcher(key); let flushSync = (opts && opts.flushSync) === true; let routesToUse = dataRoutes.activeRoutes; let normalizedPath = normalizeTo( state.location, state.matches, basename, href, routeId, opts?.relative ); let matches = matchRoutesImpl( routesToUse, normalizedPath, basename, false, dataRoutes.branches ); let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath); if (fogOfWar.active && fogOfWar.matches) { matches = fogOfWar.matches; } if (!matches) { setFetcherError( key, routeId, getInternalRouterError(404, { pathname: normalizedPath }), { flushSync } ); return; } let { path, submission, error } = normalizeNavigateOptions( true, normalizedPath, opts ); if (error) { setFetcherError(key, routeId, error, { flushSync }); return; } let scopedContext = init.getContext ? await init.getContext() : new RouterContextProvider(); let preventScrollReset = (opts && opts.preventScrollReset) === true; if (submission && isMutationMethod(submission.formMethod)) { await handleFetcherAction( key, routeId, path, matches, scopedContext, fogOfWar.active, flushSync, preventScrollReset, submission, opts && opts.defaultShouldRevalidate ); return; } fetchLoadMatches.set(key, { routeId, path }); await handleFetcherLoader( key, routeId, path, matches, scopedContext, fogOfWar.active, flushSync, preventScrollReset, submission ); } async function handleFetcherAction(key, routeId, path, requestMatches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission, callSiteDefaultShouldRevalidate) { interruptActiveLoads(); fetchLoadMatches.delete(key); let existingFetcher = state.fetchers.get(key); updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { flushSync }); let abortController = new AbortController(); let fetchRequest = createClientSideRequest( init.history, path, abortController.signal, submission ); if (isFogOfWar) { let discoverResult = await discoverRoutes( requestMatches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key ); if (discoverResult.type === "aborted") { return; } else if (discoverResult.type === "error") { setFetcherError(key, routeId, discoverResult.error, { flushSync }); return; } else if (!discoverResult.matches) { setFetcherError( key, routeId, getInternalRouterError(404, { pathname: path }), { flushSync } ); return; } else { requestMatches = discoverResult.matches; } } let match = getTargetMatch(requestMatches, path); if (!match.route.action && !match.route.lazy) { let error = getInternalRouterError(405, { method: submission.formMethod, pathname: path, routeId }); setFetcherError(key, routeId, error, { flushSync }); return; } fetchControllers.set(key, abortController); let originatingLoadId = incrementingLoadId; let fetchMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, fetchRequest, path, requestMatches, match, hydrationRouteProperties2, scopedContext ); let actionResults = await callDataStrategy( fetchRequest, path, fetchMatches, scopedContext, key ); let actionResult = actionResults[match.route.id]; if (!actionResult) { for (let match2 of fetchMatches) { if (actionResults[match2.route.id]) { actionResult = actionResults[match2.route.id]; break; } } } if (fetchRequest.signal.aborted) { if (fetchControllers.get(key) === abortController) { fetchControllers.delete(key); } return; } if (fetchersQueuedForDeletion.has(key)) { if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { updateFetcherState(key, getDoneFetcher(void 0)); return; } } else { if (isRedirectResult(actionResult)) { fetchControllers.delete(key); if (pendingNavigationLoadId > originatingLoadId) { updateFetcherState(key, getDoneFetcher(void 0)); return; } else { fetchRedirectIds.add(key); updateFetcherState(key, getLoadingFetcher(submission)); return startRedirectNavigation(fetchRequest, actionResult, false, { fetcherSubmission: submission, preventScrollReset }); } } if (isErrorResult(actionResult)) { setFetcherError(key, routeId, actionResult.error); return; } } let nextLocation = state.navigation.location || state.location; let revalidationRequest = createClientSideRequest( init.history, nextLocation, abortController.signal ); let routesToUse = dataRoutes.activeRoutes; let matches = state.navigation.state !== "idle" ? matchRoutesImpl( routesToUse, state.navigation.location, basename, false, dataRoutes.branches ) : state.matches; invariant(matches, "Didn't find any matches after fetcher action"); let loadId = ++incrementingLoadId; fetchReloadIds.set(key, loadId); let loadFetcher = getLoadingFetcher(submission, actionResult.data); state.fetchers.set(key, loadFetcher); let { dsMatches, revalidatingFetchers } = getMatchesToLoad( revalidationRequest, scopedContext, mapRouteProperties2, manifest, init.history, state, matches, submission, nextLocation, hydrationRouteProperties2, false, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, init.patchRoutesOnNavigation != null, dataRoutes.branches, [match.route.id, actionResult], callSiteDefaultShouldRevalidate ); revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => { let staleKey = rf.key; let existingFetcher2 = state.fetchers.get(staleKey); let revalidatingFetcher = getLoadingFetcher( void 0, existingFetcher2 ? existingFetcher2.data : void 0 ); state.fetchers.set(staleKey, revalidatingFetcher); abortFetcher(staleKey); if (rf.controller) { fetchControllers.set(staleKey, rf.controller); } }); updateState({ fetchers: new Map(state.fetchers) }); let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key)); abortController.signal.addEventListener( "abort", abortPendingFetchRevalidations ); let { loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData( dsMatches, revalidatingFetchers, revalidationRequest, nextLocation, scopedContext ); if (abortController.signal.aborted) { return; } abortController.signal.removeEventListener( "abort", abortPendingFetchRevalidations ); fetchReloadIds.delete(key); fetchControllers.delete(key); revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key)); if (state.fetchers.has(key)) { let doneFetcher = getDoneFetcher(actionResult.data); state.fetchers.set(key, doneFetcher); } let redirect2 = findRedirect(loaderResults); if (redirect2) { return startRedirectNavigation( revalidationRequest, redirect2.result, false, { preventScrollReset } ); } redirect2 = findRedirect(fetcherResults); if (redirect2) { fetchRedirectIds.add(redirect2.key); return startRedirectNavigation( revalidationRequest, redirect2.result, false, { preventScrollReset } ); } let { loaderData, errors } = processLoaderData( state, matches, loaderResults, void 0, revalidatingFetchers, fetcherResults ); abortStaleFetchLoads(loadId); if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { invariant(pendingAction, "Expected pending action"); pendingNavigationController && pendingNavigationController.abort(); completeNavigation(state.navigation.location, { matches, loaderData, errors, fetchers: new Map(state.fetchers) }); } else { updateState({ errors, loaderData: mergeLoaderData( state.loaderData, loaderData, matches, errors ), fetchers: new Map(state.fetchers) }); isRevalidationRequired = false; } } async function handleFetcherLoader(key, routeId, path, matches, scopedContext, isFogOfWar, flushSync, preventScrollReset, submission) { let existingFetcher = state.fetchers.get(key); updateFetcherState( key, getLoadingFetcher( submission, existingFetcher ? existingFetcher.data : void 0 ), { flushSync } ); let abortController = new AbortController(); let fetchRequest = createClientSideRequest( init.history, path, abortController.signal ); if (isFogOfWar) { let discoverResult = await discoverRoutes( matches, new URL(fetchRequest.url).pathname, fetchRequest.signal, key ); if (discoverResult.type === "aborted") { return; } else if (discoverResult.type === "error") { setFetcherError(key, routeId, discoverResult.error, { flushSync }); return; } else if (!discoverResult.matches) { setFetcherError( key, routeId, getInternalRouterError(404, { pathname: path }), { flushSync } ); return; } else { matches = discoverResult.matches; } } let match = getTargetMatch(matches, path); fetchControllers.set(key, abortController); let originatingLoadId = incrementingLoadId; let dsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, fetchRequest, path, matches, match, hydrationRouteProperties2, scopedContext ); let results = await callDataStrategy( fetchRequest, path, dsMatches, scopedContext, key ); let result = results[match.route.id]; if (!result) { for (let match2 of matches) { if (results[match2.route.id]) { result = results[match2.route.id]; break; } } } if (fetchControllers.get(key) === abortController) { fetchControllers.delete(key); } if (fetchRequest.signal.aborted) { return; } if (fetchersQueuedForDeletion.has(key)) { updateFetcherState(key, getDoneFetcher(void 0)); return; } if (isRedirectResult(result)) { if (pendingNavigationLoadId > originatingLoadId) { updateFetcherState(key, getDoneFetcher(void 0)); return; } else { fetchRedirectIds.add(key); await startRedirectNavigation(fetchRequest, result, false, { preventScrollReset }); return; } } if (isErrorResult(result)) { setFetcherError(key, routeId, result.error); return; } updateFetcherState(key, getDoneFetcher(result.data)); } async function startRedirectNavigation(request, redirect2, isNavigation, { submission, fetcherSubmission, preventScrollReset, replace: replace2 } = {}) { if (!isNavigation) { pendingPopstateNavigationDfd?.resolve(); pendingPopstateNavigationDfd = null; } if (redirect2.response.headers.has("X-Remix-Revalidate")) { isRevalidationRequired = true; } let location = redirect2.response.headers.get("Location"); invariant(location, "Expected a Location header on the redirect Response"); location = normalizeRedirectLocation( location, new URL(request.url), basename, init.history ); let redirectLocation = createLocation(state.location, location, { _isRedirect: true }); if (isBrowser3) { let isDocumentReload = false; if (redirect2.response.headers.has("X-Remix-Reload-Document")) { isDocumentReload = true; } else if (isAbsoluteUrl(location)) { const url = createBrowserURLImpl(location, true); isDocumentReload = // Hard reload if it's an absolute URL to a new origin url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename stripBasename(url.pathname, basename) == null; } if (isDocumentReload) { if (replace2) { routerWindow.location.replace(location); } else { routerWindow.location.assign(location); } return; } } pendingNavigationController = null; let redirectNavigationType = replace2 === true || redirect2.response.headers.has("X-Remix-Replace") ? "REPLACE" /* Replace */ : "PUSH" /* Push */; let { formMethod, formAction, formEncType } = state.navigation; if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { submission = getSubmissionFromNavigation(state.navigation); } let activeSubmission = submission || fetcherSubmission; if (redirectPreserveMethodStatusCodes.has(redirect2.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { await startNavigation(redirectNavigationType, redirectLocation, { submission: { ...activeSubmission, formAction: location }, // Preserve these flags across redirects preventScrollReset: preventScrollReset || pendingPreventScrollReset, enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0 }); } else { let overrideNavigation = getLoadingNavigation( redirectLocation, submission ); await startNavigation(redirectNavigationType, redirectLocation, { overrideNavigation, // Send fetcher submissions through for shouldRevalidate fetcherSubmission, // Preserve these flags across redirects preventScrollReset: preventScrollReset || pendingPreventScrollReset, enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0 }); } } async function callDataStrategy(request, path, matches, scopedContext, fetcherKey) { let results; let dataResults = {}; try { results = await callDataStrategyImpl( dataStrategyImpl, request, path, matches, fetcherKey, scopedContext, false ); } catch (e) { matches.filter((m) => m.shouldLoad).forEach((m) => { dataResults[m.route.id] = { type: "error" /* error */, error: e }; }); return dataResults; } if (request.signal.aborted) { return dataResults; } if (!isMutationMethod(request.method)) { for (let match of matches) { if (results[match.route.id]?.type === "error" /* error */) { break; } if (!results.hasOwnProperty(match.route.id) && !state.loaderData.hasOwnProperty(match.route.id) && (!state.errors || !state.errors.hasOwnProperty(match.route.id)) && match.shouldCallHandler()) { results[match.route.id] = { type: "error" /* error */, result: new Error( `No result returned from dataStrategy for route ${match.route.id}` ) }; } } } for (let [routeId, result] of Object.entries(results)) { if (isRedirectDataStrategyResult(result)) { let response = result.result; dataResults[routeId] = { type: "redirect" /* redirect */, response: normalizeRelativeRoutingRedirectResponse( response, request, routeId, matches, basename ) }; } else { dataResults[routeId] = await convertDataStrategyResultToDataResult(result); } } return dataResults; } async function callLoadersAndMaybeResolveData(matches, fetchersToLoad, request, location, scopedContext) { let loaderResultsPromise = callDataStrategy( request, location, matches, scopedContext, null ); let fetcherResultsPromise = Promise.all( fetchersToLoad.map(async (f) => { if (f.matches && f.match && f.request && f.controller) { let results = await callDataStrategy( f.request, f.path, f.matches, scopedContext, f.key ); let result = results[f.match.route.id]; return { [f.key]: result }; } else { return Promise.resolve({ [f.key]: { type: "error" /* error */, error: getInternalRouterError(404, { pathname: f.path }) } }); } }) ); let loaderResults = await loaderResultsPromise; let fetcherResults = (await fetcherResultsPromise).reduce( (acc, r) => Object.assign(acc, r), {} ); return { loaderResults, fetcherResults }; } function interruptActiveLoads() { isRevalidationRequired = true; fetchLoadMatches.forEach((_, key) => { if (fetchControllers.has(key)) { cancelledFetcherLoads.add(key); } abortFetcher(key); }); } function updateFetcherState(key, fetcher, opts = {}) { state.fetchers.set(key, fetcher); updateState( { fetchers: new Map(state.fetchers) }, { flushSync: (opts && opts.flushSync) === true } ); } function setFetcherError(key, routeId, error, opts = {}) { let boundaryMatch = findNearestBoundary(state.matches, routeId); deleteFetcher(key); updateState( { errors: { [boundaryMatch.route.id]: error }, fetchers: new Map(state.fetchers) }, { flushSync: (opts && opts.flushSync) === true } ); } function getFetcher(key) { activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); if (fetchersQueuedForDeletion.has(key)) { fetchersQueuedForDeletion.delete(key); } return state.fetchers.get(key) || IDLE_FETCHER; } function resetFetcher(key, opts) { abortFetcher(key, opts?.reason); updateFetcherState(key, getDoneFetcher(null)); } function deleteFetcher(key) { let fetcher = state.fetchers.get(key); if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { abortFetcher(key); } fetchLoadMatches.delete(key); fetchReloadIds.delete(key); fetchRedirectIds.delete(key); fetchersQueuedForDeletion.delete(key); cancelledFetcherLoads.delete(key); state.fetchers.delete(key); } function queueFetcherForDeletion(key) { let count = (activeFetchers.get(key) || 0) - 1; if (count <= 0) { activeFetchers.delete(key); fetchersQueuedForDeletion.add(key); } else { activeFetchers.set(key, count); } updateState({ fetchers: new Map(state.fetchers) }); } function abortFetcher(key, reason) { let controller = fetchControllers.get(key); if (controller) { controller.abort(reason); fetchControllers.delete(key); } } function markFetchersDone(keys) { for (let key of keys) { let fetcher = getFetcher(key); let doneFetcher = getDoneFetcher(fetcher.data); state.fetchers.set(key, doneFetcher); } } function markFetchRedirectsDone() { let doneKeys = []; let updatedFetchers = false; for (let key of fetchRedirectIds) { let fetcher = state.fetchers.get(key); invariant(fetcher, `Expected fetcher: ${key}`); if (fetcher.state === "loading") { fetchRedirectIds.delete(key); doneKeys.push(key); updatedFetchers = true; } } markFetchersDone(doneKeys); return updatedFetchers; } function abortStaleFetchLoads(landedId) { let yeetedKeys = []; for (let [key, id] of fetchReloadIds) { if (id < landedId) { let fetcher = state.fetchers.get(key); invariant(fetcher, `Expected fetcher: ${key}`); if (fetcher.state === "loading") { abortFetcher(key); fetchReloadIds.delete(key); yeetedKeys.push(key); } } } markFetchersDone(yeetedKeys); return yeetedKeys.length > 0; } function getBlocker(key, fn) { let blocker = state.blockers.get(key) || IDLE_BLOCKER; if (blockerFunctions.get(key) !== fn) { blockerFunctions.set(key, fn); } return blocker; } function deleteBlocker(key) { state.blockers.delete(key); blockerFunctions.delete(key); } function updateBlocker(key, newBlocker) { let blocker = state.blockers.get(key) || IDLE_BLOCKER; invariant( blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}` ); let blockers = new Map(state.blockers); blockers.set(key, newBlocker); updateState({ blockers }); } function shouldBlockNavigation({ currentLocation, nextLocation, historyAction }) { if (blockerFunctions.size === 0) { return; } if (blockerFunctions.size > 1) { warning(false, "A router only supports one blocker at a time"); } let entries = Array.from(blockerFunctions.entries()); let [blockerKey, blockerFunction] = entries[entries.length - 1]; let blocker = state.blockers.get(blockerKey); if (blocker && blocker.state === "proceeding") { return; } if (blockerFunction({ currentLocation, nextLocation, historyAction })) { return blockerKey; } } function handleNavigational404(pathname) { let error = getInternalRouterError(404, { pathname }); let routesToUse = dataRoutes.activeRoutes; let { matches, route } = getShortCircuitMatches(routesToUse); return { notFoundMatches: matches, route, error }; } function enableScrollRestoration(positions, getPosition, getKey) { savedScrollPositions2 = positions; getScrollPosition = getPosition; getScrollRestorationKey2 = getKey || null; if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { initialScrollRestored = true; let y = getSavedScrollPosition(state.location, state.matches); if (y != null) { updateState({ restoreScrollPosition: y }); } } return () => { savedScrollPositions2 = null; getScrollPosition = null; getScrollRestorationKey2 = null; }; } function getScrollKey(location, matches) { if (getScrollRestorationKey2) { let key = getScrollRestorationKey2( location, matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData)) ); return key || location.key; } return location.key; } function saveScrollPosition(location, matches) { if (savedScrollPositions2 && getScrollPosition) { let key = getScrollKey(location, matches); savedScrollPositions2[key] = getScrollPosition(); } } function getSavedScrollPosition(location, matches) { if (savedScrollPositions2) { let key = getScrollKey(location, matches); let y = savedScrollPositions2[key]; if (typeof y === "number") { return y; } } return null; } function checkFogOfWar(matches, routesToUse, pathname) { if (init.patchRoutesOnNavigation) { let activeBranches = dataRoutes.branches; if (!matches) { let fogMatches = matchRoutesImpl( routesToUse, pathname, basename, true, activeBranches ); return { active: true, matches: fogMatches || [] }; } else { if (Object.keys(matches[0].params).length > 0) { let partialMatches = matchRoutesImpl( routesToUse, pathname, basename, true, activeBranches ); return { active: true, matches: partialMatches }; } } } return { active: false, matches: null }; } async function discoverRoutes(matches, pathname, signal, fetcherKey) { if (!init.patchRoutesOnNavigation) { return { type: "success", matches }; } let partialMatches = matches; while (true) { let localManifest = manifest; try { await init.patchRoutesOnNavigation({ signal, path: pathname, matches: partialMatches, fetcherKey, patch: (routeId, children) => { if (signal.aborted) return; patchRoutesImpl( routeId, children, dataRoutes, localManifest, mapRouteProperties2, false ); } }); } catch (e) { return { type: "error", error: e, partialMatches }; } if (signal.aborted) { return { type: "aborted" }; } let activeBranches = dataRoutes.branches; let newMatches = matchRoutesImpl( dataRoutes.activeRoutes, pathname, basename, false, activeBranches ); let newPartialMatches = null; if (newMatches) { if (Object.keys(newMatches[0].params).length === 0) { return { type: "success", matches: newMatches }; } else { newPartialMatches = matchRoutesImpl( dataRoutes.activeRoutes, pathname, basename, true, activeBranches ); let matchedDeeper = newPartialMatches && partialMatches.length < newPartialMatches.length && compareMatches( partialMatches, newPartialMatches.slice(0, partialMatches.length) ); if (!matchedDeeper) { return { type: "success", matches: newMatches }; } } } if (!newPartialMatches) { newPartialMatches = matchRoutesImpl( dataRoutes.activeRoutes, pathname, basename, true, activeBranches ); } if (!newPartialMatches || compareMatches(partialMatches, newPartialMatches)) { return { type: "success", matches: null }; } partialMatches = newPartialMatches; } } function compareMatches(a, b) { return a.length === b.length && a.every((m, i) => m.route.id === b[i].route.id); } function _internalSetRoutes(newRoutes) { manifest = {}; dataRoutes.setHmrRoutes( convertRoutesToDataRoutes( newRoutes, mapRouteProperties2, void 0, manifest ) ); } function patchRoutes(routeId, children, unstable_allowElementMutations = false) { patchRoutesImpl( routeId, children, dataRoutes, manifest, mapRouteProperties2, unstable_allowElementMutations ); if (!dataRoutes.hasHMRRoutes) { updateState({}); } } router = { get basename() { return basename; }, get future() { return future; }, get state() { return state; }, get routes() { return dataRoutes.stableRoutes; }, get branches() { return dataRoutes.branches; }, get manifest() { return manifest; }, get window() { return routerWindow; }, initialize, subscribe, enableScrollRestoration, navigate, fetch: fetch2, revalidate, // Passthrough to history-aware createHref used by useHref so we get proper // hash-aware URLs in DOM paths createHref: (to) => init.history.createHref(to), encodeLocation: (to) => init.history.encodeLocation(to), getFetcher, resetFetcher, deleteFetcher: queueFetcherForDeletion, dispose, getBlocker, deleteBlocker, patchRoutes, _internalFetchControllers: fetchControllers, // TODO: Remove setRoutes, it's temporary to avoid dealing with // updating the tree while validating the update algorithm. _internalSetRoutes, _internalSetStateDoNotUseOrYouWillBreakYourApp(newState) { updateState(newState); } }; if (init.instrumentations) { router = instrumentClientSideRouter( router, init.instrumentations.map((i) => i.router).filter(Boolean) ); } return router; } function createStaticHandler(routes, opts) { invariant( routes.length > 0, "You must provide a non-empty routes array to createStaticHandler" ); let manifest = {}; let basename = (opts ? opts.basename : null) || "/"; let _mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties; let mapRouteProperties2 = _mapRouteProperties; let future = { ...opts?.future }; if (opts?.instrumentations) { let instrumentations = opts.instrumentations; mapRouteProperties2 = (route) => { return { ..._mapRouteProperties(route), ...getRouteInstrumentationUpdates( instrumentations.map((i) => i.route).filter(Boolean), route ) }; }; } let dataRoutes = convertRoutesToDataRoutes( routes, mapRouteProperties2, void 0, manifest ); let routeBranches = flattenAndRankRoutes(dataRoutes); async function query(request, { requestContext, filterMatchesToLoad, skipLoaderErrorBubbling, skipRevalidation, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) { let normalizePathImpl = normalizePath || defaultNormalizePath; let method = request.method; let location = createLocation( "", normalizePathImpl(request), null, "default" ); let matches = matchRoutesImpl( dataRoutes, location, basename, false, routeBranches ); requestContext = requestContext != null ? requestContext : new RouterContextProvider(); if (!isValidMethod(method) && method !== "HEAD") { let error = getInternalRouterError(405, { method }); let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes); let staticContext = { basename, location, matches: methodNotAllowedMatches, loaderData: {}, actionData: null, errors: { [route.id]: error }, statusCode: error.status, loaderHeaders: {}, actionHeaders: {} }; return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext; } else if (!matches) { let error = getInternalRouterError(404, { pathname: location.pathname }); let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes); let staticContext = { basename, location, matches: notFoundMatches, loaderData: {}, actionData: null, errors: { [route.id]: error }, statusCode: error.status, loaderHeaders: {}, actionHeaders: {} }; return generateMiddlewareResponse ? generateMiddlewareResponse(() => Promise.resolve(staticContext)) : staticContext; } if (generateMiddlewareResponse) { invariant( requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `RouterContextProvider`" ); try { await loadLazyMiddlewareForMatches( matches, manifest, mapRouteProperties2 ); let renderedStaticContext; let response = await runServerMiddlewarePipeline( { request, url: createDataFunctionUrl(request, location), pattern: getRoutePattern(matches), matches, params: matches[0].params, // If we're calling middleware then it must be enabled so we can cast // this to the proper type knowing it's not an `AppLoadContext` context: requestContext }, async () => { let res = await generateMiddlewareResponse( async (revalidationRequest, opts2 = {}) => { let result2 = await queryImpl( revalidationRequest, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, "filterMatchesToLoad" in opts2 ? opts2.filterMatchesToLoad ?? null : filterMatchesToLoad ?? null, skipRevalidation === true ); if (isResponse(result2)) { return result2; } renderedStaticContext = { location, basename, ...result2 }; return renderedStaticContext; } ); return res; }, async (error, routeId) => { if (isRedirectResponse(error)) { return error; } if (isResponse(error)) { try { error = new ErrorResponseImpl( error.status, error.statusText, await parseResponseBody(error) ); } catch (e) { error = e; } } if (isDataWithResponseInit(error)) { error = dataWithResponseInitToErrorResponse(error); } if (renderedStaticContext) { if (routeId in renderedStaticContext.loaderData) { renderedStaticContext.loaderData[routeId] = void 0; } let staticContext = getStaticContextFromError( dataRoutes, renderedStaticContext, error, skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id ); return generateMiddlewareResponse( () => Promise.resolve(staticContext) ); } else { let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary( matches, matches.find( (m) => m.route.id === routeId || m.route.loader )?.route.id || routeId ).route.id; let staticContext = { matches, location, basename, loaderData: {}, actionData: null, errors: { [boundaryRouteId]: error }, statusCode: isRouteErrorResponse(error) ? error.status : 500, actionHeaders: {}, loaderHeaders: {} }; return generateMiddlewareResponse( () => Promise.resolve(staticContext) ); } } ); invariant(isResponse(response), "Expected a response in query()"); return response; } catch (e) { if (isResponse(e)) { return e; } throw e; } } let result = await queryImpl( request, location, matches, requestContext, dataStrategy || null, skipLoaderErrorBubbling === true, null, filterMatchesToLoad || null, skipRevalidation === true ); if (isResponse(result)) { return result; } return { location, basename, ...result }; } async function queryRoute(request, { routeId, requestContext, dataStrategy, generateMiddlewareResponse, normalizePath } = {}) { let normalizePathImpl = normalizePath || defaultNormalizePath; let method = request.method; let location = createLocation( "", normalizePathImpl(request), null, "default" ); let matches = matchRoutesImpl( dataRoutes, location, basename, false, routeBranches ); requestContext = requestContext != null ? requestContext : new RouterContextProvider(); if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { throw getInternalRouterError(405, { method }); } else if (!matches) { throw getInternalRouterError(404, { pathname: location.pathname }); } let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location); if (routeId && !match) { throw getInternalRouterError(403, { pathname: location.pathname, routeId }); } else if (!match) { throw getInternalRouterError(404, { pathname: location.pathname }); } if (generateMiddlewareResponse) { invariant( requestContext instanceof RouterContextProvider, "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `RouterContextProvider`" ); await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2); let response = await runServerMiddlewarePipeline( { request, url: createDataFunctionUrl(request, location), pattern: getRoutePattern(matches), matches, params: matches[0].params, // If we're calling middleware then it must be enabled so we can cast // this to the proper type knowing it's not an `AppLoadContext` context: requestContext }, async () => { let res = await generateMiddlewareResponse( async (innerRequest) => { let result2 = await queryImpl( innerRequest, location, matches, requestContext, dataStrategy || null, false, match, null, false ); let processed = handleQueryResult(result2); return isResponse(processed) ? processed : typeof processed === "string" ? new Response(processed) : Response.json(processed); } ); return res; }, (error) => { if (isDataWithResponseInit(error)) { return Promise.resolve(dataWithResponseInitToResponse(error)); } if (isResponse(error)) { return Promise.resolve(error); } throw error; } ); return response; } let result = await queryImpl( request, location, matches, requestContext, dataStrategy || null, false, match, null, false ); return handleQueryResult(result); function handleQueryResult(result2) { if (isResponse(result2)) { return result2; } let error = result2.errors ? Object.values(result2.errors)[0] : void 0; if (error !== void 0) { throw error; } if (result2.actionData) { return Object.values(result2.actionData)[0]; } if (result2.loaderData) { return Object.values(result2.loaderData)[0]; } return void 0; } } async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) { invariant( request.signal, "query()/queryRoute() requests must contain an AbortController signal" ); try { if (isMutationMethod(request.method)) { let result2 = await submit( request, location, matches, routeMatch || getTargetMatch(matches, location), requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch != null, filterMatchesToLoad, skipRevalidation ); return result2; } let result = await loadRouteData( request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad ); return isResponse(result) ? result : { ...result, actionData: null, actionHeaders: {} }; } catch (e) { if (isDataStrategyResult(e) && isResponse(e.result)) { if (e.type === "error" /* error */) { throw e.result; } return e.result; } if (isRedirectResponse(e)) { return e; } throw e; } } async function submit(request, location, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) { let result; if (!actionMatch.route.action && !actionMatch.route.lazy) { let error = getInternalRouterError(405, { method: request.method, pathname: new URL(request.url).pathname, routeId: actionMatch.route.id }); if (isRouteRequest) { throw error; } result = { type: "error" /* error */, error }; } else { let dsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, request, location, matches, actionMatch, [], requestContext ); let results = await callDataStrategy( request, location, dsMatches, isRouteRequest, requestContext, dataStrategy ); result = results[actionMatch.route.id]; if (request.signal.aborted) { throwStaticHandlerAbortedError(request, isRouteRequest); } } if (isRedirectResult(result)) { throw new Response(null, { status: result.response.status, headers: { Location: result.response.headers.get("Location") } }); } if (isRouteRequest) { if (isErrorResult(result)) { throw result.error; } return { matches: [actionMatch], loaderData: {}, actionData: { [actionMatch.route.id]: result.data }, errors: null, // Note: statusCode + headers are unused here since queryRoute will // return the raw Response or value statusCode: 200, loaderHeaders: {}, actionHeaders: {} }; } if (skipRevalidation) { if (isErrorResult(result)) { let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); return { statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, actionData: null, actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} }, matches, loaderData: {}, errors: { [boundaryMatch.route.id]: result.error }, loaderHeaders: {} }; } else { return { actionData: { [actionMatch.route.id]: result.data }, actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}, matches, loaderData: {}, errors: null, statusCode: result.statusCode || 200, loaderHeaders: {} }; } } let loaderRequest = new Request(request.url, { headers: request.headers, redirect: request.redirect, signal: request.signal }); if (isErrorResult(result)) { let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); let handlerContext2 = await loadRouteData( loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad, [boundaryMatch.route.id, result] ); return { ...handlerContext2, statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, actionData: null, actionHeaders: { ...result.headers ? { [actionMatch.route.id]: result.headers } : {} } }; } let handlerContext = await loadRouteData( loaderRequest, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, null, filterMatchesToLoad ); return { ...handlerContext, actionData: { [actionMatch.route.id]: result.data }, // action status codes take precedence over loader status codes ...result.statusCode ? { statusCode: result.statusCode } : {}, actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {} }; } async function loadRouteData(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) { let isRouteRequest = routeMatch != null; if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) { throw getInternalRouterError(400, { method: request.method, pathname: new URL(request.url).pathname, routeId: routeMatch?.route.id }); } let dsMatches; if (routeMatch) { dsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, request, location, matches, routeMatch, [], requestContext ); } else { let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? ( // Up to but not including the boundary matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1 ) : void 0; let pattern = getRoutePattern(matches); dsMatches = matches.map((match, index) => { if (maxIdx != null && index > maxIdx) { return getDataStrategyMatch( mapRouteProperties2, manifest, request, location, pattern, match, [], requestContext, false ); } return getDataStrategyMatch( mapRouteProperties2, manifest, request, location, pattern, match, [], requestContext, (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match)) ); }); } if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) { return { matches, loaderData: {}, errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { [pendingActionResult[0]]: pendingActionResult[1].error } : null, statusCode: 200, loaderHeaders: {} }; } let results = await callDataStrategy( request, location, dsMatches, isRouteRequest, requestContext, dataStrategy ); if (request.signal.aborted) { throwStaticHandlerAbortedError(request, isRouteRequest); } let handlerContext = processRouteLoaderData( matches, results, pendingActionResult, true, skipLoaderErrorBubbling ); return { ...handlerContext, matches }; } async function callDataStrategy(request, location, matches, isRouteRequest, requestContext, dataStrategy) { let results = await callDataStrategyImpl( dataStrategy || defaultDataStrategy, request, location, matches, null, requestContext, true ); let dataResults = {}; await Promise.all( matches.map(async (match) => { if (!(match.route.id in results)) { return; } let result = results[match.route.id]; if (isRedirectDataStrategyResult(result)) { let response = result.result; throw normalizeRelativeRoutingRedirectResponse( response, request, match.route.id, matches, basename ); } if (isRouteRequest) { if (isResponse(result.result)) { throw result; } else if (isDataWithResponseInit(result.result)) { throw dataWithResponseInitToResponse(result.result); } } dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result); }) ); return dataResults; } return { dataRoutes, _internalRouteBranches: routeBranches, query, queryRoute }; } function getStaticContextFromError(routes, handlerContext, error, boundaryId) { let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id; return { ...handlerContext, statusCode: isRouteErrorResponse(error) ? error.status : 500, errors: { [errorBoundaryId]: error } }; } function throwStaticHandlerAbortedError(request, isRouteRequest) { if (request.signal.reason !== void 0) { throw request.signal.reason; } let method = isRouteRequest ? "queryRoute" : "query"; throw new Error( `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}` ); } function isSubmissionNavigation(opts) { return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0); } function defaultNormalizePath(request) { let url = new URL(request.url); return { pathname: url.pathname, search: url.search, hash: url.hash }; } function normalizeTo(location, matches, basename, to, fromRouteId, relative) { let contextualMatches; let activeRouteMatch; if (fromRouteId) { contextualMatches = []; for (let match of matches) { contextualMatches.push(match); if (match.route.id === fromRouteId) { activeRouteMatch = match; break; } } } else { contextualMatches = matches; activeRouteMatch = matches[matches.length - 1]; } let path = resolveTo( to ? to : ".", getResolveToMatches(contextualMatches), stripBasename(location.pathname, basename) || location.pathname, relative === "path" ); if (to == null) { path.search = location.search; path.hash = location.hash; } if ((to == null || to === "" || to === ".") && activeRouteMatch) { let nakedIndex = hasNakedIndexQuery(path.search); if (activeRouteMatch.route.index && !nakedIndex) { path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; } else if (!activeRouteMatch.route.index && nakedIndex) { let params = new URLSearchParams(path.search); let indexValues = params.getAll("index"); params.delete("index"); indexValues.filter((v) => v).forEach((v) => params.append("index", v)); let qs = params.toString(); path.search = qs ? `?${qs}` : ""; } } if (basename !== "/") { path.pathname = prependBasename({ basename, pathname: path.pathname }); } return createPath(path); } function normalizeNavigateOptions(isFetcher, path, opts) { if (!opts || !isSubmissionNavigation(opts)) { return { path }; } if (opts.formMethod && !isValidMethod(opts.formMethod)) { return { path, error: getInternalRouterError(405, { method: opts.formMethod }) }; } let getInvalidBodyError = () => ({ path, error: getInternalRouterError(400, { type: "invalid-body" }) }); let rawFormMethod = opts.formMethod || "get"; let formMethod = rawFormMethod.toUpperCase(); let formAction = stripHashFromPath(path); if (opts.body !== void 0) { if (opts.formEncType === "text/plain") { if (!isMutationMethod(formMethod)) { return getInvalidBodyError(); } let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? ( // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data Array.from(opts.body.entries()).reduce( (acc, [name, value]) => `${acc}${name}=${value} `, "" ) ) : String(opts.body); return { path, submission: { formMethod, formAction, formEncType: opts.formEncType, formData: void 0, json: void 0, text } }; } else if (opts.formEncType === "application/json") { if (!isMutationMethod(formMethod)) { return getInvalidBodyError(); } try { let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; return { path, submission: { formMethod, formAction, formEncType: opts.formEncType, formData: void 0, json, text: void 0 } }; } catch (e) { return getInvalidBodyError(); } } } invariant( typeof FormData === "function", "FormData is not available in this environment" ); let searchParams; let formData; if (opts.formData) { searchParams = convertFormDataToSearchParams(opts.formData); formData = opts.formData; } else if (opts.body instanceof FormData) { searchParams = convertFormDataToSearchParams(opts.body); formData = opts.body; } else if (opts.body instanceof URLSearchParams) { searchParams = opts.body; formData = convertSearchParamsToFormData(searchParams); } else if (opts.body == null) { searchParams = new URLSearchParams(); formData = new FormData(); } else { try { searchParams = new URLSearchParams(opts.body); formData = convertSearchParamsToFormData(searchParams); } catch (e) { return getInvalidBodyError(); } } let submission = { formMethod, formAction, formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", formData, json: void 0, text: void 0 }; if (isMutationMethod(submission.formMethod)) { return { path, submission }; } let parsedPath = parsePath(path); if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { searchParams.append("index", ""); } parsedPath.search = `?${searchParams}`; return { path: createPath(parsedPath), submission }; } function getMatchesToLoad(request, scopedContext, mapRouteProperties2, manifest, history, state, matches, submission, location, lazyRoutePropertiesToSkip, initialHydration, isRevalidationRequired, cancelledFetcherLoads, fetchersQueuedForDeletion, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, hasPatchRoutesOnNavigation, branches, pendingActionResult, callSiteDefaultShouldRevalidate) { let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0; let currentUrl = history.createURL(state.location); let nextUrl = history.createURL(location); let maxIdx; if (initialHydration && state.errors) { let boundaryId = Object.keys(state.errors)[0]; maxIdx = matches.findIndex((m) => m.route.id === boundaryId); } else if (pendingActionResult && isErrorResult(pendingActionResult[1])) { let boundaryId = pendingActionResult[0]; maxIdx = matches.findIndex((m) => m.route.id === boundaryId) - 1; } let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0; let shouldSkipRevalidation = actionStatus && actionStatus >= 400; let baseShouldRevalidateArgs = { currentUrl, currentParams: state.matches[0]?.params || {}, nextUrl, nextParams: matches[0].params, ...submission, actionResult, actionStatus }; let pattern = getRoutePattern(matches); let dsMatches = matches.map((match, index) => { let { route } = match; let forceShouldLoad = null; if (maxIdx != null && index > maxIdx) { forceShouldLoad = false; } else if (route.lazy) { forceShouldLoad = true; } else if (!routeHasLoaderOrMiddleware(route)) { forceShouldLoad = false; } else if (initialHydration) { let { shouldLoad: shouldLoad2 } = getRouteHydrationStatus( route, state.loaderData, state.errors ); forceShouldLoad = shouldLoad2; } else if (isNewLoader(state.loaderData, state.matches[index], match)) { forceShouldLoad = true; } if (forceShouldLoad !== null) { return getDataStrategyMatch( mapRouteProperties2, manifest, request, location, pattern, match, lazyRoutePropertiesToSkip, scopedContext, forceShouldLoad ); } let defaultShouldRevalidate = false; if (typeof callSiteDefaultShouldRevalidate === "boolean") { defaultShouldRevalidate = callSiteDefaultShouldRevalidate; } else if (shouldSkipRevalidation) { defaultShouldRevalidate = false; } else if (isRevalidationRequired) { defaultShouldRevalidate = true; } else if (currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search) { defaultShouldRevalidate = true; } else if (currentUrl.search !== nextUrl.search) { defaultShouldRevalidate = true; } else if (isNewRouteInstance(state.matches[index], match)) { defaultShouldRevalidate = true; } let shouldRevalidateArgs = { ...baseShouldRevalidateArgs, defaultShouldRevalidate }; let shouldLoad = shouldRevalidateLoader(match, shouldRevalidateArgs); return getDataStrategyMatch( mapRouteProperties2, manifest, request, location, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs, callSiteDefaultShouldRevalidate ); }); let revalidatingFetchers = []; fetchLoadMatches.forEach((f, key) => { if (initialHydration || !matches.some((m) => m.route.id === f.routeId) || fetchersQueuedForDeletion.has(key)) { return; } let fetcher = state.fetchers.get(key); let isMidInitialLoad = fetcher && fetcher.state !== "idle" && fetcher.data === void 0; let fetcherMatches = matchRoutesImpl( routesToUse, f.path, basename ?? "/", false, branches ); if (!fetcherMatches) { if (hasPatchRoutesOnNavigation && isMidInitialLoad) { return; } revalidatingFetchers.push({ key, routeId: f.routeId, path: f.path, matches: null, match: null, request: null, controller: null }); return; } if (fetchRedirectIds.has(key)) { return; } let fetcherMatch = getTargetMatch(fetcherMatches, f.path); let fetchController = new AbortController(); let fetchRequest = createClientSideRequest( history, f.path, fetchController.signal ); let fetcherDsMatches = null; if (cancelledFetcherLoads.has(key)) { cancelledFetcherLoads.delete(key); fetcherDsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext ); } else if (isMidInitialLoad) { if (isRevalidationRequired) { fetcherDsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext ); } } else { let defaultShouldRevalidate; if (typeof callSiteDefaultShouldRevalidate === "boolean") { defaultShouldRevalidate = callSiteDefaultShouldRevalidate; } else if (shouldSkipRevalidation) { defaultShouldRevalidate = false; } else { defaultShouldRevalidate = isRevalidationRequired; } let shouldRevalidateArgs = { ...baseShouldRevalidateArgs, defaultShouldRevalidate }; if (shouldRevalidateLoader(fetcherMatch, shouldRevalidateArgs)) { fetcherDsMatches = getTargetedDataStrategyMatches( mapRouteProperties2, manifest, fetchRequest, f.path, fetcherMatches, fetcherMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs ); } } if (fetcherDsMatches) { revalidatingFetchers.push({ key, routeId: f.routeId, path: f.path, matches: fetcherDsMatches, match: fetcherMatch, request: fetchRequest, controller: fetchController }); } }); return { dsMatches, revalidatingFetchers }; } function routeHasLoaderOrMiddleware(route) { return route.loader != null || route.middleware != null && route.middleware.length > 0; } function getRouteHydrationStatus(route, loaderData, errors) { if (route.lazy) { return { shouldLoad: true, renderFallback: true }; } if (!routeHasLoaderOrMiddleware(route)) { return { shouldLoad: false, renderFallback: false }; } let hasData = loaderData != null && route.id in loaderData; let hasError = errors != null && errors[route.id] !== void 0; if (!hasData && hasError) { return { shouldLoad: false, renderFallback: false }; } if (typeof route.loader === "function" && route.loader.hydrate === true) { return { shouldLoad: true, renderFallback: !hasData }; } let shouldLoad = !hasData && !hasError; return { shouldLoad, renderFallback: shouldLoad }; } function isNewLoader(currentLoaderData, currentMatch, match) { let isNew = ( // [a] -> [a, b] !currentMatch || // [a, b] -> [a, c] match.route.id !== currentMatch.route.id ); let isMissingData = !currentLoaderData.hasOwnProperty(match.route.id); return isNew || isMissingData; } function isNewRouteInstance(currentMatch, match) { let currentPath = currentMatch.route.path; return ( // param change for this match, /users/123 -> /users/456 currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path // e.g. /files/images/avatar.jpg -> files/finances.xls currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] ); } function shouldRevalidateLoader(loaderMatch, arg) { if (loaderMatch.route.shouldRevalidate) { let routeChoice = loaderMatch.route.shouldRevalidate(arg); if (typeof routeChoice === "boolean") { return routeChoice; } } return arg.defaultShouldRevalidate; } function patchRoutesImpl(routeId, children, dataRoutes, manifest, mapRouteProperties2, allowElementMutations) { let childrenToPatch; if (routeId) { let route = manifest[routeId]; invariant( route, `No route found to patch children into: routeId = ${routeId}` ); if (!route.children) { route.children = []; } childrenToPatch = route.children; } else { childrenToPatch = dataRoutes.activeRoutes; } let uniqueChildren = []; let existingChildren = []; children.forEach((newRoute) => { let existingRoute = childrenToPatch.find( (existingRoute2) => isSameRoute(newRoute, existingRoute2) ); if (existingRoute) { existingChildren.push({ existingRoute, newRoute }); } else { uniqueChildren.push(newRoute); } }); if (uniqueChildren.length > 0) { let newRoutes = convertRoutesToDataRoutes( uniqueChildren, mapRouteProperties2, [routeId || "_", "patch", String(childrenToPatch?.length || "0")], manifest ); childrenToPatch.push(...newRoutes); } if (allowElementMutations && existingChildren.length > 0) { for (let i = 0; i < existingChildren.length; i++) { let { existingRoute, newRoute } = existingChildren[i]; let existingRouteTyped = existingRoute; let [newRouteTyped] = convertRoutesToDataRoutes( [newRoute], mapRouteProperties2, [], // Doesn't matter for mutated routes since they already have an id {}, // Don't touch the manifest here since we're updating in place true ); Object.assign(existingRouteTyped, { element: newRouteTyped.element ? newRouteTyped.element : existingRouteTyped.element, errorElement: newRouteTyped.errorElement ? newRouteTyped.errorElement : existingRouteTyped.errorElement, hydrateFallbackElement: newRouteTyped.hydrateFallbackElement ? newRouteTyped.hydrateFallbackElement : existingRouteTyped.hydrateFallbackElement }); } } if (!dataRoutes.hasHMRRoutes) { dataRoutes.setRoutes([...dataRoutes.activeRoutes]); } } function isSameRoute(newRoute, existingRoute) { if ("id" in newRoute && "id" in existingRoute && newRoute.id === existingRoute.id) { return true; } if (!(newRoute.index === existingRoute.index && newRoute.path === existingRoute.path && newRoute.caseSensitive === existingRoute.caseSensitive)) { return false; } if ((!newRoute.children || newRoute.children.length === 0) && (!existingRoute.children || existingRoute.children.length === 0)) { return true; } return newRoute.children?.every( (aChild, i) => existingRoute.children?.some((bChild) => isSameRoute(aChild, bChild)) ) ?? false; } var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap(); var loadLazyRouteProperty = ({ key, route, manifest, mapRouteProperties: mapRouteProperties2 }) => { let routeToUpdate = manifest[route.id]; invariant(routeToUpdate, "No route found in manifest"); if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") { return; } let lazyFn = routeToUpdate.lazy[key]; if (!lazyFn) { return; } let cache = lazyRoutePropertyCache.get(routeToUpdate); if (!cache) { cache = {}; lazyRoutePropertyCache.set(routeToUpdate, cache); } let cachedPromise = cache[key]; if (cachedPromise) { return cachedPromise; } let propertyPromise = (async () => { let isUnsupported = isUnsupportedLazyRouteObjectKey(key); let staticRouteValue = routeToUpdate[key]; let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary"; if (isUnsupported) { warning( !isUnsupported, "Route property " + key + " is not a supported lazy route property. This property will be ignored." ); cache[key] = Promise.resolve(); } else if (isStaticallyDefined) { warning( false, `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.` ); } else { let value = await lazyFn(); if (value != null) { Object.assign(routeToUpdate, { [key]: value }); Object.assign(routeToUpdate, mapRouteProperties2(routeToUpdate)); } } if (typeof routeToUpdate.lazy === "object") { routeToUpdate.lazy[key] = void 0; if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) { routeToUpdate.lazy = void 0; } } })(); cache[key] = propertyPromise; return propertyPromise; }; var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap(); function loadLazyRoute(route, type, manifest, mapRouteProperties2, lazyRoutePropertiesToSkip) { let routeToUpdate = manifest[route.id]; invariant(routeToUpdate, "No route found in manifest"); if (!route.lazy) { return { lazyRoutePromise: void 0, lazyHandlerPromise: void 0 }; } if (typeof route.lazy === "function") { let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate); if (cachedPromise) { return { lazyRoutePromise: cachedPromise, lazyHandlerPromise: cachedPromise }; } let lazyRoutePromise2 = (async () => { invariant( typeof route.lazy === "function", "No lazy route function found" ); let lazyRoute = await route.lazy(); let routeUpdates = {}; for (let lazyRouteProperty in lazyRoute) { let lazyValue = lazyRoute[lazyRouteProperty]; if (lazyValue === void 0) { continue; } let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty); let staticRouteValue = routeToUpdate[lazyRouteProperty]; let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based // on the route updates lazyRouteProperty !== "hasErrorBoundary"; if (isUnsupported) { warning( !isUnsupported, "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored." ); } else if (isStaticallyDefined) { warning( !isStaticallyDefined, `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.` ); } else { routeUpdates[lazyRouteProperty] = lazyValue; } } Object.assign(routeToUpdate, routeUpdates); Object.assign(routeToUpdate, { // To keep things framework agnostic, we use the provided `mapRouteProperties` // function to set the framework-aware properties (`element`/`hasErrorBoundary`) // since the logic will differ between frameworks. ...mapRouteProperties2(routeToUpdate), lazy: void 0 }); })(); lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2); lazyRoutePromise2.catch(() => { }); return { lazyRoutePromise: lazyRoutePromise2, lazyHandlerPromise: lazyRoutePromise2 }; } let lazyKeys = Object.keys(route.lazy); let lazyPropertyPromises = []; let lazyHandlerPromise = void 0; for (let key of lazyKeys) { if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) { continue; } let promise = loadLazyRouteProperty({ key, route, manifest, mapRouteProperties: mapRouteProperties2 }); if (promise) { lazyPropertyPromises.push(promise); if (key === type) { lazyHandlerPromise = promise; } } } let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => { }) : void 0; lazyRoutePromise?.catch(() => { }); lazyHandlerPromise?.catch(() => { }); return { lazyRoutePromise, lazyHandlerPromise }; } function isNonNullable(value) { return value !== void 0; } function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties2) { let promises = matches.map(({ route }) => { if (typeof route.lazy !== "object" || !route.lazy.middleware) { return void 0; } return loadLazyRouteProperty({ key: "middleware", route, manifest, mapRouteProperties: mapRouteProperties2 }); }).filter(isNonNullable); return promises.length > 0 ? Promise.all(promises) : void 0; } async function defaultDataStrategy(args) { let matchesToLoad = args.matches.filter((m) => m.shouldLoad); let keyedResults = {}; let results = await Promise.all(matchesToLoad.map((m) => m.resolve())); results.forEach((result, i) => { keyedResults[matchesToLoad[i].route.id] = result; }); return keyedResults; } async function defaultDataStrategyWithMiddleware(args) { if (!args.matches.some((m) => m.route.middleware)) { return defaultDataStrategy(args); } return runClientMiddlewarePipeline(args, () => defaultDataStrategy(args)); } function runServerMiddlewarePipeline(args, handler, errorHandler) { return runMiddlewarePipeline( args, handler, processResult, isResponse, errorHandler ); function processResult(result) { return isDataWithResponseInit(result) ? dataWithResponseInitToResponse(result) : result; } } function runClientMiddlewarePipeline(args, handler) { return runMiddlewarePipeline( args, handler, (r) => { if (isRedirectResponse(r)) { throw r; } return r; }, isDataStrategyResults, errorHandler ); function errorHandler(error, routeId, nextResult) { if (nextResult) { return Promise.resolve( Object.assign(nextResult.value, { [routeId]: { type: "error", result: error } }) ); } else { let { matches } = args; let maxBoundaryIdx = Math.min( // Throwing route Math.max( matches.findIndex((m) => m.route.id === routeId), 0 ), // or the shallowest route that needs to load data Math.max( matches.findIndex((m) => m.shouldCallHandler()), 0 ) ); let boundaryRouteId = findNearestBoundary( matches, matches[maxBoundaryIdx].route.id ).route.id; return Promise.resolve({ [boundaryRouteId]: { type: "error", result: error } }); } } } async function runMiddlewarePipeline(args, handler, processResult, isResult, errorHandler) { let { matches, ...dataFnArgs } = args; let tuples = matches.flatMap( (m) => m.route.middleware ? m.route.middleware.map((fn) => [m.route.id, fn]) : [] ); let result = await callRouteMiddleware( dataFnArgs, tuples, handler, processResult, isResult, errorHandler ); return result; } async function callRouteMiddleware(args, middlewares, handler, processResult, isResult, errorHandler, idx = 0) { let { request } = args; if (request.signal.aborted) { throw request.signal.reason ?? new Error(`Request aborted: ${request.method} ${request.url}`); } let tuple = middlewares[idx]; if (!tuple) { let result = await handler(); return result; } let [routeId, middleware] = tuple; let nextResult; let next = async () => { if (nextResult) { throw new Error("You may only call `next()` once per middleware"); } try { let result = await callRouteMiddleware( args, middlewares, handler, processResult, isResult, errorHandler, idx + 1 ); nextResult = { value: result }; return nextResult.value; } catch (error) { nextResult = { value: await errorHandler(error, routeId, nextResult) }; return nextResult.value; } }; try { let value = await middleware(args, next); let result = value != null ? processResult(value) : void 0; if (isResult(result)) { return result; } else if (nextResult) { return result ?? nextResult.value; } else { nextResult = { value: await next() }; return nextResult.value; } } catch (error) { let response = await errorHandler(error, routeId, nextResult); return response; } } function getDataStrategyMatchLazyPromises(mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip) { let lazyMiddlewarePromise = loadLazyRouteProperty({ key: "middleware", route: match.route, manifest, mapRouteProperties: mapRouteProperties2 }); let lazyRoutePromises = loadLazyRoute( match.route, isMutationMethod(request.method) ? "action" : "loader", manifest, mapRouteProperties2, lazyRoutePropertiesToSkip ); return { middleware: lazyMiddlewarePromise, route: lazyRoutePromises.lazyRoutePromise, handler: lazyRoutePromises.lazyHandlerPromise }; } function getDataStrategyMatch(mapRouteProperties2, manifest, request, path, pattern, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, shouldRevalidateArgs = null, callSiteDefaultShouldRevalidate) { let isUsingNewApi = false; let _lazyPromises = getDataStrategyMatchLazyPromises( mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip ); return { ...match, _lazyPromises, shouldLoad, shouldRevalidateArgs, shouldCallHandler(defaultShouldRevalidate) { isUsingNewApi = true; if (!shouldRevalidateArgs) { return shouldLoad; } if (typeof callSiteDefaultShouldRevalidate === "boolean") { return shouldRevalidateLoader(match, { ...shouldRevalidateArgs, defaultShouldRevalidate: callSiteDefaultShouldRevalidate }); } if (typeof defaultShouldRevalidate === "boolean") { return shouldRevalidateLoader(match, { ...shouldRevalidateArgs, defaultShouldRevalidate }); } return shouldRevalidateLoader(match, shouldRevalidateArgs); }, resolve(handlerOverride) { let { lazy, loader, middleware } = match.route; let callHandler = isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (lazy || loader); let isMiddlewareOnlyRoute = middleware && middleware.length > 0 && !loader && !lazy; if (callHandler && (isMutationMethod(request.method) || !isMiddlewareOnlyRoute)) { return callLoaderOrAction({ request, path, pattern, match, lazyHandlerPromise: _lazyPromises?.handler, lazyRoutePromise: _lazyPromises?.route, handlerOverride, scopedContext }); } return Promise.resolve({ type: "data" /* data */, result: void 0 }); } }; } function getTargetedDataStrategyMatches(mapRouteProperties2, manifest, request, path, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) { return matches.map((match) => { if (match.route.id !== targetMatch.route.id) { return { ...match, shouldLoad: false, shouldRevalidateArgs, shouldCallHandler: () => false, _lazyPromises: getDataStrategyMatchLazyPromises( mapRouteProperties2, manifest, request, match, lazyRoutePropertiesToSkip ), resolve: () => Promise.resolve({ type: "data", result: void 0 }) }; } return getDataStrategyMatch( mapRouteProperties2, manifest, request, path, getRoutePattern(matches), match, lazyRoutePropertiesToSkip, scopedContext, true, shouldRevalidateArgs ); }); } async function callDataStrategyImpl(dataStrategyImpl, request, path, matches, fetcherKey, scopedContext, isStaticHandler) { if (matches.some((m) => m._lazyPromises?.middleware)) { await Promise.all(matches.map((m) => m._lazyPromises?.middleware)); } let dataStrategyArgs = { request, url: createDataFunctionUrl(request, path), pattern: getRoutePattern(matches), params: matches[0].params, context: scopedContext, matches }; let runClientMiddleware = isStaticHandler ? () => { throw new Error( "You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`" ); } : (cb) => { let typedDataStrategyArgs = dataStrategyArgs; return runClientMiddlewarePipeline(typedDataStrategyArgs, () => { return cb({ ...typedDataStrategyArgs, fetcherKey, runClientMiddleware: () => { throw new Error( "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler" ); } }); }); }; let results = await dataStrategyImpl({ ...dataStrategyArgs, fetcherKey, runClientMiddleware }); try { await Promise.all( matches.flatMap((m) => [ m._lazyPromises?.handler, m._lazyPromises?.route ]) ); } catch (e) { } return results; } async function callLoaderOrAction({ request, path, pattern, match, lazyHandlerPromise, lazyRoutePromise, handlerOverride, scopedContext }) { let result; let onReject; let isAction = isMutationMethod(request.method); let type = isAction ? "action" : "loader"; let runHandler = (handler) => { let reject; let abortPromise = new Promise((_, r) => reject = r); onReject = () => reject(); request.signal.addEventListener("abort", onReject); let actualHandler = (ctx) => { if (typeof handler !== "function") { return Promise.reject( new Error( `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]` ) ); } return handler( { request, url: createDataFunctionUrl(request, path), pattern, params: match.params, context: scopedContext }, ...ctx !== void 0 ? [ctx] : [] ); }; let handlerPromise = (async () => { try { let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler()); return { type: "data", result: val }; } catch (e) { return { type: "error", result: e }; } })(); return Promise.race([handlerPromise, abortPromise]); }; try { let handler = isAction ? match.route.action : match.route.loader; if (lazyHandlerPromise || lazyRoutePromise) { if (handler) { let handlerError; let [value] = await Promise.all([ // If the handler throws, don't let it immediately bubble out, // since we need to let the lazy() execution finish so we know if this // route has a boundary that can handle the error runHandler(handler).catch((e) => { handlerError = e; }), // Ensure all lazy route promises are resolved before continuing lazyHandlerPromise, lazyRoutePromise ]); if (handlerError !== void 0) { throw handlerError; } result = value; } else { await lazyHandlerPromise; let handler2 = isAction ? match.route.action : match.route.loader; if (handler2) { [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]); } else if (type === "action") { let url = new URL(request.url); let pathname = url.pathname + url.search; throw getInternalRouterError(405, { method: request.method, pathname, routeId: match.route.id }); } else { return { type: "data" /* data */, result: void 0 }; } } } else if (!handler) { let url = new URL(request.url); let pathname = url.pathname + url.search; throw getInternalRouterError(404, { pathname }); } else { result = await runHandler(handler); } } catch (e) { return { type: "error" /* error */, result: e }; } finally { if (onReject) { request.signal.removeEventListener("abort", onReject); } } return result; } async function parseResponseBody(response) { let contentType = response.headers.get("Content-Type"); if (contentType && /\bapplication\/json\b/.test(contentType)) { return response.body == null ? null : response.json(); } return response.text(); } async function convertDataStrategyResultToDataResult(dataStrategyResult) { let { result, type } = dataStrategyResult; if (isResponse(result)) { let data2; try { data2 = await parseResponseBody(result); } catch (e) { return { type: "error" /* error */, error: e }; } if (type === "error" /* error */) { return { type: "error" /* error */, error: new ErrorResponseImpl(result.status, result.statusText, data2), statusCode: result.status, headers: result.headers }; } return { type: "data" /* data */, data: data2, statusCode: result.status, headers: result.headers }; } if (type === "error" /* error */) { if (isDataWithResponseInit(result)) { if (result.data instanceof Error) { return { type: "error" /* error */, error: result.data, statusCode: result.init?.status, headers: result.init?.headers ? new Headers(result.init.headers) : void 0 }; } return { type: "error" /* error */, error: dataWithResponseInitToErrorResponse(result), statusCode: isRouteErrorResponse(result) ? result.status : void 0, headers: result.init?.headers ? new Headers(result.init.headers) : void 0 }; } return { type: "error" /* error */, error: result, statusCode: isRouteErrorResponse(result) ? result.status : void 0 }; } if (isDataWithResponseInit(result)) { return { type: "data" /* data */, data: result.data, statusCode: result.init?.status, headers: result.init?.headers ? new Headers(result.init.headers) : void 0 }; } return { type: "data" /* data */, data: result }; } function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) { let location = response.headers.get("Location"); invariant( location, "Redirects returned/thrown from loaders/actions must have a Location header" ); if (!isAbsoluteUrl(location)) { let trimmedMatches = matches.slice( 0, matches.findIndex((m) => m.route.id === routeId) + 1 ); location = normalizeTo( new URL(request.url), trimmedMatches, basename, location ); response.headers.set("Location", location); } return response; } var invalidProtocols = [ "about:", "blob:", "chrome:", "chrome-untrusted:", "content:", "data:", "devtools:", "file:", "filesystem:", // eslint-disable-next-line no-script-url "javascript:" ]; function normalizeRedirectLocation(location, currentUrl, basename, historyInstance) { if (isAbsoluteUrl(location)) { let normalizedLocation = location; let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation); if (invalidProtocols.includes(url.protocol)) { throw new Error("Invalid redirect location"); } let isSameBasename = stripBasename(url.pathname, basename) != null; if (url.origin === currentUrl.origin && isSameBasename) { return removeDoubleSlashes(url.pathname) + url.search + url.hash; } } try { let url = historyInstance.createURL(location); if (invalidProtocols.includes(url.protocol)) { throw new Error("Invalid redirect location"); } } catch (e) { } return location; } function createClientSideRequest(history, location, signal, submission) { let url = history.createURL(stripHashFromPath(location)).toString(); let init = { signal }; if (submission && isMutationMethod(submission.formMethod)) { let { formMethod, formEncType } = submission; init.method = formMethod.toUpperCase(); if (formEncType === "application/json") { init.headers = new Headers({ "Content-Type": formEncType }); init.body = JSON.stringify(submission.json); } else if (formEncType === "text/plain") { init.body = submission.text; } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { init.body = convertFormDataToSearchParams(submission.formData); } else { init.body = submission.formData; } } return new Request(url, init); } function createDataFunctionUrl(request, path) { let url = new URL(request.url); let parsed = typeof path === "string" ? parsePath(path) : path; url.pathname = parsed.pathname || "/"; if (parsed.search) { let searchParams = new URLSearchParams(parsed.search); let indexValues = searchParams.getAll("index"); searchParams.delete("index"); for (let value of indexValues.filter(Boolean)) { searchParams.append("index", value); } url.search = searchParams.size ? `?${searchParams.toString()}` : ""; } else { url.search = ""; } url.hash = parsed.hash || ""; return url; } function convertFormDataToSearchParams(formData) { let searchParams = new URLSearchParams(); for (let [key, value] of formData.entries()) { searchParams.append(key, typeof value === "string" ? value : value.name); } return searchParams; } function convertSearchParamsToFormData(searchParams) { let formData = new FormData(); for (let [key, value] of searchParams.entries()) { formData.append(key, value); } return formData; } function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) { let loaderData = {}; let errors = null; let statusCode; let foundError = false; let loaderHeaders = {}; let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0; matches.forEach((match) => { if (!(match.route.id in results)) { return; } let id = match.route.id; let result = results[id]; invariant( !isRedirectResult(result), "Cannot handle redirect results in processLoaderData" ); if (isErrorResult(result)) { let error = result.error; if (pendingError !== void 0) { error = pendingError; pendingError = void 0; } errors = errors || {}; if (skipLoaderErrorBubbling) { errors[id] = error; } else { let boundaryMatch = findNearestBoundary(matches, id); if (errors[boundaryMatch.route.id] == null) { errors[boundaryMatch.route.id] = error; } } if (!isStaticHandler) { loaderData[id] = ResetLoaderDataSymbol; } if (!foundError) { foundError = true; statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; } if (result.headers) { loaderHeaders[id] = result.headers; } } else { loaderData[id] = result.data; if (result.statusCode && result.statusCode !== 200 && !foundError) { statusCode = result.statusCode; } if (result.headers) { loaderHeaders[id] = result.headers; } } }); if (pendingError !== void 0 && pendingActionResult) { errors = { [pendingActionResult[0]]: pendingError }; if (pendingActionResult[2]) { loaderData[pendingActionResult[2]] = void 0; } } return { loaderData, errors, statusCode: statusCode || 200, loaderHeaders }; } function processLoaderData(state, matches, results, pendingActionResult, revalidatingFetchers, fetcherResults) { let { loaderData, errors } = processRouteLoaderData( matches, results, pendingActionResult ); revalidatingFetchers.filter((f) => !f.matches || f.matches.some((m) => m.shouldLoad)).forEach((rf) => { let { key, match, controller } = rf; if (controller && controller.signal.aborted) { return; } let result = fetcherResults[key]; invariant(result, "Did not find corresponding fetcher result"); if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(state.matches, match?.route.id); if (!(errors && errors[boundaryMatch.route.id])) { errors = { ...errors, [boundaryMatch.route.id]: result.error }; } state.fetchers.delete(key); } else if (isRedirectResult(result)) { invariant(false, "Unhandled fetcher revalidation redirect"); } else { let doneFetcher = getDoneFetcher(result.data); state.fetchers.set(key, doneFetcher); } }); return { loaderData, errors }; } function mergeLoaderData(loaderData, newLoaderData, matches, errors) { let mergedLoaderData = Object.entries(newLoaderData).filter(([, v]) => v !== ResetLoaderDataSymbol).reduce((merged, [k, v]) => { merged[k] = v; return merged; }, {}); for (let match of matches) { let id = match.route.id; if (!newLoaderData.hasOwnProperty(id) && loaderData.hasOwnProperty(id) && match.route.loader) { mergedLoaderData[id] = loaderData[id]; } if (errors && errors.hasOwnProperty(id)) { break; } } return mergedLoaderData; } function getActionDataForCommit(pendingActionResult) { if (!pendingActionResult) { return {}; } return isErrorResult(pendingActionResult[1]) ? { // Clear out prior actionData on errors actionData: {} } : { actionData: { [pendingActionResult[0]]: pendingActionResult[1].data } }; } function findNearestBoundary(matches, routeId) { let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches]; return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0]; } function getShortCircuitMatches(routes) { let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || { id: `__shim-error-route__` }; return { matches: [ { params: {}, pathname: "", pathnameBase: "", route } ], route }; } function getInternalRouterError(status, { pathname, routeId, method, type, message } = {}) { let statusText = "Unknown Server Error"; let errorMessage = "Unknown @remix-run/router error"; if (status === 400) { statusText = "Bad Request"; if (method && pathname && routeId) { errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`; } else if (type === "invalid-body") { errorMessage = "Unable to encode submission body"; } } else if (status === 403) { statusText = "Forbidden"; errorMessage = `Route "${routeId}" does not match URL "${pathname}"`; } else if (status === 404) { statusText = "Not Found"; errorMessage = `No route matches URL "${pathname}"`; } else if (status === 405) { statusText = "Method Not Allowed"; if (method && pathname && routeId) { errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`; } else if (method) { errorMessage = `Invalid request method "${method.toUpperCase()}"`; } } return new ErrorResponseImpl( status || 500, statusText, new Error(errorMessage), true ); } function findRedirect(results) { let entries = Object.entries(results); for (let i = entries.length - 1; i >= 0; i--) { let [key, result] = entries[i]; if (isRedirectResult(result)) { return { key, result }; } } } function stripHashFromPath(path) { let parsedPath = typeof path === "string" ? parsePath(path) : path; return createPath({ ...parsedPath, hash: "" }); } function isHashChangeOnly(a, b) { if (a.pathname !== b.pathname || a.search !== b.search) { return false; } if (a.hash === "") { return b.hash !== ""; } else if (a.hash === b.hash) { return true; } else if (b.hash !== "") { return true; } return false; } function dataWithResponseInitToResponse(data2) { return Response.json(data2.data, data2.init ?? void 0); } function dataWithResponseInitToErrorResponse(data2) { return new ErrorResponseImpl( data2.init?.status ?? 500, data2.init?.statusText ?? "Internal Server Error", data2.data ); } function isDataStrategyResults(result) { return result != null && typeof result === "object" && Object.entries(result).every( ([key, value]) => typeof key === "string" && isDataStrategyResult(value) ); } function isDataStrategyResult(result) { return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */); } function isRedirectDataStrategyResult(result) { return isResponse(result.result) && redirectStatusCodes.has(result.result.status); } function isErrorResult(result) { return result.type === "error" /* error */; } function isRedirectResult(result) { return (result && result.type) === "redirect" /* redirect */; } function isDataWithResponseInit(value) { return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit"; } function isResponse(value) { return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; } function isRedirectStatusCode(statusCode) { return redirectStatusCodes.has(statusCode); } function isRedirectResponse(result) { return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location"); } function isValidMethod(method) { return validRequestMethods.has(method.toUpperCase()); } function isMutationMethod(method) { return validMutationMethods.has(method.toUpperCase()); } function hasNakedIndexQuery(search) { return new URLSearchParams(search).getAll("index").some((v) => v === ""); } function getTargetMatch(matches, location) { let search = typeof location === "string" ? parsePath(location).search : location.search; if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { return matches[matches.length - 1]; } let pathMatches = getPathContributingMatches(matches); return pathMatches[pathMatches.length - 1]; } function getSubmissionFromNavigation(navigation) { let { formMethod, formAction, formEncType, text, formData, json } = navigation; if (!formMethod || !formAction || !formEncType) { return; } if (text != null) { return { formMethod, formAction, formEncType, formData: void 0, json: void 0, text }; } else if (formData != null) { return { formMethod, formAction, formEncType, formData, json: void 0, text: void 0 }; } else if (json !== void 0) { return { formMethod, formAction, formEncType, formData: void 0, json, text: void 0 }; } } function getLoadingNavigation(location, submission) { if (submission) { let navigation = { state: "loading", location, formMethod: submission.formMethod, formAction: submission.formAction, formEncType: submission.formEncType, formData: submission.formData, json: submission.json, text: submission.text }; return navigation; } else { let navigation = { state: "loading", location, formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0 }; return navigation; } } function getSubmittingNavigation(location, submission) { let navigation = { state: "submitting", location, formMethod: submission.formMethod, formAction: submission.formAction, formEncType: submission.formEncType, formData: submission.formData, json: submission.json, text: submission.text }; return navigation; } function getLoadingFetcher(submission, data2) { if (submission) { let fetcher = { state: "loading", formMethod: submission.formMethod, formAction: submission.formAction, formEncType: submission.formEncType, formData: submission.formData, json: submission.json, text: submission.text, data: data2 }; return fetcher; } else { let fetcher = { state: "loading", formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0, data: data2 }; return fetcher; } } function getSubmittingFetcher(submission, existingFetcher) { let fetcher = { state: "submitting", formMethod: submission.formMethod, formAction: submission.formAction, formEncType: submission.formEncType, formData: submission.formData, json: submission.json, text: submission.text, data: existingFetcher ? existingFetcher.data : void 0 }; return fetcher; } function getDoneFetcher(data2) { let fetcher = { state: "idle", formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0, data: data2 }; return fetcher; } function restoreAppliedTransitions(_window, transitions) { try { let sessionPositions = _window.sessionStorage.getItem( TRANSITIONS_STORAGE_KEY ); if (sessionPositions) { let json = JSON.parse(sessionPositions); for (let [k, v] of Object.entries(json || {})) { if (v && Array.isArray(v)) { transitions.set(k, new Set(v || [])); } } } } catch (e) { } } function persistAppliedTransitions(_window, transitions) { if (transitions.size > 0) { let json = {}; for (let [k, v] of transitions) { json[k] = [...v]; } try { _window.sessionStorage.setItem( TRANSITIONS_STORAGE_KEY, JSON.stringify(json) ); } catch (error) { warning( false, `Failed to save applied view transitions in sessionStorage (${error}).` ); } } } function createDeferred() { let resolve; let reject; let promise = new Promise((res, rej) => { resolve = async (val) => { res(val); try { await promise; } catch (e) { } }; reject = async (error) => { rej(error); try { await promise; } catch (e) { } }; }); return { promise, //@ts-ignore resolve, //@ts-ignore reject }; } // lib/context.ts var DataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); DataRouterContext.displayName = "DataRouter"; var DataRouterStateContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); DataRouterStateContext.displayName = "DataRouterState"; var RSCRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(false); function useIsRSCRouterContext() { return react__WEBPACK_IMPORTED_MODULE_0__.useContext(RSCRouterContext); } var ViewTransitionContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext({ isTransitioning: false }); ViewTransitionContext.displayName = "ViewTransition"; var FetchersContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext( /* @__PURE__ */ new Map() ); FetchersContext.displayName = "Fetchers"; var AwaitContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); AwaitContext.displayName = "Await"; var AwaitContextProvider = (props) => react__WEBPACK_IMPORTED_MODULE_0__.createElement(AwaitContext.Provider, props); var NavigationContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext( null ); NavigationContext.displayName = "Navigation"; var LocationContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext( null ); LocationContext.displayName = "Location"; var RouteContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext({ outlet: null, matches: [], isDataRoute: false }); RouteContext.displayName = "Route"; var RouteErrorContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); RouteErrorContext.displayName = "RouteError"; var ENABLE_DEV_WARNINGS = true; // lib/hooks.tsx // lib/errors.ts var ERROR_DIGEST_BASE = "REACT_ROUTER_ERROR"; var ERROR_DIGEST_REDIRECT = "REDIRECT"; var ERROR_DIGEST_ROUTE_ERROR_RESPONSE = "ROUTE_ERROR_RESPONSE"; function decodeRedirectErrorDigest(digest) { if (digest.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`)) { try { let parsed = JSON.parse(digest.slice(28)); if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string" && typeof parsed.location === "string" && typeof parsed.reloadDocument === "boolean" && typeof parsed.replace === "boolean") { return parsed; } } catch { } } } function decodeRouteErrorResponseDigest(digest) { if (digest.startsWith( `${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{` )) { try { let parsed = JSON.parse(digest.slice(40)); if (typeof parsed === "object" && parsed && typeof parsed.status === "number" && typeof parsed.statusText === "string") { return new ErrorResponseImpl( parsed.status, parsed.statusText, parsed.data ); } } catch { } } } // lib/hooks.tsx function useHref(to, { relative } = {}) { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of the // router loaded. We can help them understand how to avoid that. `useHref() may be used only in the context of a component.` ); let { basename, navigator } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext); let { hash, pathname, search } = useResolvedPath(to, { relative }); let joinedPathname = pathname; if (basename !== "/") { joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]); } return navigator.createHref({ pathname: joinedPathname, search, hash }); } function useInRouterContext() { return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LocationContext) != null; } function useLocation() { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of the // router loaded. We can help them understand how to avoid that. `useLocation() may be used only in the context of a component.` ); return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LocationContext).location; } function useNavigationType() { return react__WEBPACK_IMPORTED_MODULE_0__.useContext(LocationContext).navigationType; } function useMatch(pattern) { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of the // router loaded. We can help them understand how to avoid that. `useMatch() may be used only in the context of a component.` ); let { pathname } = useLocation(); return react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => matchPath(pattern, decodePath(pathname)), [pathname, pattern] ); } var navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when your component is first rendered.`; function useIsomorphicLayoutEffect(cb) { let isStatic = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext).static; if (!isStatic) { react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(cb); } } function useNavigate() { let { isDataRoute } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); return isDataRoute ? useNavigateStable() : useNavigateUnstable(); } function useNavigateUnstable() { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of the // router loaded. We can help them understand how to avoid that. `useNavigate() may be used only in the context of a component.` ); let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext); let { basename, navigator } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext); let { matches } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); let { pathname: locationPathname } = useLocation(); let routePathnamesJson = JSON.stringify(getResolveToMatches(matches)); let activeRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(false); useIsomorphicLayoutEffect(() => { activeRef.current = true; }); let navigate = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( (to, options = {}) => { warning(activeRef.current, navigateEffectWarning); if (!activeRef.current) return; if (typeof to === "number") { navigator.go(to); return; } let path = resolveTo( to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path" ); if (dataRouterContext == null && basename !== "/") { path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); } (!!options.replace ? navigator.replace : navigator.push)( path, options.state, options ); }, [ basename, navigator, routePathnamesJson, locationPathname, dataRouterContext ] ); return navigate; } var OutletContext = react__WEBPACK_IMPORTED_MODULE_0__.createContext(null); function useOutletContext() { return react__WEBPACK_IMPORTED_MODULE_0__.useContext(OutletContext); } function useOutlet(context) { let outlet = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext).outlet; return react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => outlet && /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(OutletContext.Provider, { value: context }, outlet), [outlet, context] ); } function useParams() { let { matches } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); let routeMatch = matches[matches.length - 1]; return routeMatch?.params ?? {}; } function useResolvedPath(to, { relative } = {}) { let { matches } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); let { pathname: locationPathname } = useLocation(); let routePathnamesJson = JSON.stringify(getResolveToMatches(matches)); return react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => resolveTo( to, JSON.parse(routePathnamesJson), locationPathname, relative === "path" ), [to, routePathnamesJson, locationPathname, relative] ); } function useRoutes(routes, locationArg) { return useRoutesImpl(routes, locationArg); } function useRoutesImpl(routes, locationArg, dataRouterOpts) { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of the // router loaded. We can help them understand how to avoid that. `useRoutes() may be used only in the context of a component.` ); let { navigator } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext); let { matches: parentMatches } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); let routeMatch = parentMatches[parentMatches.length - 1]; let parentParams = routeMatch ? routeMatch.params : {}; let parentPathname = routeMatch ? routeMatch.pathname : "/"; let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/"; let parentRoute = routeMatch && routeMatch.route; if (ENABLE_DEV_WARNINGS) { let parentPath = parentRoute && parentRoute.path || ""; warningOnce( parentPathname, !parentRoute || parentPath.endsWith("*") || parentPath.endsWith("*?"), `You rendered descendant (or called \`useRoutes()\`) at "${parentPathname}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. Please change the parent to .` ); } let locationFromContext = useLocation(); let location; if (locationArg) { let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; invariant( parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase), `When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${parentPathnameBase}" but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.` ); location = parsedLocationArg; } else { location = locationFromContext; } let pathname = location.pathname || "/"; let remainingPathname = pathname; if (parentPathnameBase !== "/") { let parentSegments = parentPathnameBase.replace(/^\//, "").split("/"); let segments = pathname.replace(/^\//, "").split("/"); remainingPathname = "/" + segments.slice(parentSegments.length).join("/"); } let matches = dataRouterOpts && dataRouterOpts.state.matches.length ? ( // If we're in a data router, use the matches we've already identified but ensure // we have the latest route instances from the manifest in case elements have changed dataRouterOpts.state.matches.map( (m) => Object.assign(m, { route: dataRouterOpts.manifest[m.route.id] || m.route }) ) ) : matchRoutes(routes, { pathname: remainingPathname }); if (ENABLE_DEV_WARNINGS) { warning( parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" ` ); warning( matches == null || matches[matches.length - 1].route.element !== void 0 || matches[matches.length - 1].route.Component !== void 0 || matches[matches.length - 1].route.lazy !== void 0, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.` ); } let renderedMatches = _renderMatches( matches && matches.map( (match) => Object.assign({}, match, { params: Object.assign({}, parentParams, match.params), pathname: joinPaths([ parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes. // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses // `new URL()` internally and we need to prevent it from treating // them as separators navigator.encodeLocation ? navigator.encodeLocation( match.pathname.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23") ).pathname : match.pathname ]), pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([ parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes // Pre-encode `%`, `?` and `#` ahead of `encodeLocation` because it uses // `new URL()` internally and we need to prevent it from treating // them as separators navigator.encodeLocation ? navigator.encodeLocation( match.pathnameBase.replace(/%/g, "%25").replace(/\?/g, "%3F").replace(/#/g, "%23") ).pathname : match.pathnameBase ]) }) ), parentMatches, dataRouterOpts ); if (locationArg && renderedMatches) { return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( LocationContext.Provider, { value: { location: { pathname: "/", search: "", hash: "", state: null, key: "default", mask: void 0, ...location }, navigationType: "POP" /* Pop */ } }, renderedMatches ); } return renderedMatches; } function DefaultErrorComponent() { let error = useRouteError(); let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error); let stack = error instanceof Error ? error.stack : null; let lightgrey = "rgba(200,200,200, 0.5)"; let preStyles = { padding: "0.5rem", backgroundColor: lightgrey }; let codeStyles = { padding: "2px 4px", backgroundColor: lightgrey }; let devInfo = null; if (ENABLE_DEV_WARNINGS) { console.error( "Error handled by React Router default ErrorBoundary:", error ); devInfo = /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("p", null, "\u{1F4BF} Hey developer \u{1F44B}"), /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("code", { style: codeStyles }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("code", { style: codeStyles }, "errorElement"), " prop on your route.")); } return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("h3", { style: { fontStyle: "italic" } }, message), stack ? /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement("pre", { style: preStyles }, stack) : null, devInfo); } var defaultErrorElement = /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(DefaultErrorComponent, null); var RenderErrorBoundary = class extends react__WEBPACK_IMPORTED_MODULE_0__.Component { constructor(props) { super(props); this.state = { location: props.location, revalidation: props.revalidation, error: props.error }; } static getDerivedStateFromError(error) { return { error }; } static getDerivedStateFromProps(props, state) { if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") { return { error: props.error, location: props.location, revalidation: props.revalidation }; } return { error: props.error !== void 0 ? props.error : state.error, location: state.location, revalidation: props.revalidation || state.revalidation }; } componentDidCatch(error, errorInfo) { if (this.props.onError) { this.props.onError(error, errorInfo); } else { console.error( "React Router caught the following error during render", error ); } } render() { let error = this.state.error; if (this.context && typeof error === "object" && error && "digest" in error && typeof error.digest === "string") { const decoded = decodeRouteErrorResponseDigest(error.digest); if (decoded) error = decoded; } let result = error !== void 0 ? /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(RouteContext.Provider, { value: this.props.routeContext }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( RouteErrorContext.Provider, { value: error, children: this.props.component } )) : this.props.children; if (this.context) { return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(RSCErrorHandler, { error }, result); } return result; } }; RenderErrorBoundary.contextType = RSCRouterContext; var errorRedirectHandledMap = /* @__PURE__ */ new WeakMap(); function RSCErrorHandler({ children, error }) { let { basename } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext); if (typeof error === "object" && error && "digest" in error && typeof error.digest === "string") { let redirect2 = decodeRedirectErrorDigest(error.digest); if (redirect2) { let existingRedirect = errorRedirectHandledMap.get(error); if (existingRedirect) throw existingRedirect; let parsed = parseToInfo(redirect2.location, basename); if (isBrowser && !errorRedirectHandledMap.get(error)) { if (parsed.isExternal || redirect2.reloadDocument) { window.location.href = parsed.absoluteURL || parsed.to; } else { const redirectPromise = Promise.resolve().then( () => window.__reactRouterDataRouter.navigate(parsed.to, { replace: redirect2.replace }) ); errorRedirectHandledMap.set(error, redirectPromise); throw redirectPromise; } } return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( "meta", { httpEquiv: "refresh", content: `0;url=${parsed.absoluteURL || parsed.to}` } ); } } return children; } function RenderedRoute({ routeContext, match, children }) { let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext); if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) { dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id; } return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(RouteContext.Provider, { value: routeContext }, children); } function _renderMatches(matches, parentMatches = [], dataRouterOpts) { let dataRouterState = dataRouterOpts?.state; if (matches == null) { if (!dataRouterState) { return null; } if (dataRouterState.errors) { matches = dataRouterState.matches; } else if (parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) { matches = dataRouterState.matches; } else { return null; } } let renderedMatches = matches; let errors = dataRouterState?.errors; if (errors != null) { let errorIndex = renderedMatches.findIndex( (m) => m.route.id && errors?.[m.route.id] !== void 0 ); invariant( errorIndex >= 0, `Could not find a matching route for errors on route IDs: ${Object.keys( errors ).join(",")}` ); renderedMatches = renderedMatches.slice( 0, Math.min(renderedMatches.length, errorIndex + 1) ); } let renderFallback = false; let fallbackIndex = -1; if (dataRouterOpts && dataRouterState) { renderFallback = dataRouterState.renderFallback; for (let i = 0; i < renderedMatches.length; i++) { let match = renderedMatches[i]; if (match.route.HydrateFallback || match.route.hydrateFallbackElement) { fallbackIndex = i; } if (match.route.id) { let { loaderData, errors: errors2 } = dataRouterState; let needsToRunLoader = match.route.loader && !loaderData.hasOwnProperty(match.route.id) && (!errors2 || errors2[match.route.id] === void 0); if (match.route.lazy || needsToRunLoader) { if (dataRouterOpts.isStatic) { renderFallback = true; } if (fallbackIndex >= 0) { renderedMatches = renderedMatches.slice(0, fallbackIndex + 1); } else { renderedMatches = [renderedMatches[0]]; } break; } } } } let onErrorHandler = dataRouterOpts?.onError; let onError = dataRouterState && onErrorHandler ? (error, errorInfo) => { onErrorHandler(error, { location: dataRouterState.location, params: dataRouterState.matches?.[0]?.params ?? {}, pattern: getRoutePattern(dataRouterState.matches), errorInfo }); } : void 0; return renderedMatches.reduceRight( (outlet, match, index) => { let error; let shouldRenderHydrateFallback = false; let errorElement = null; let hydrateFallbackElement = null; if (dataRouterState) { error = errors && match.route.id ? errors[match.route.id] : void 0; errorElement = match.route.errorElement || defaultErrorElement; if (renderFallback) { if (fallbackIndex < 0 && index === 0) { warningOnce( "route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration" ); shouldRenderHydrateFallback = true; hydrateFallbackElement = null; } else if (fallbackIndex === index) { shouldRenderHydrateFallback = true; hydrateFallbackElement = match.route.hydrateFallbackElement || null; } } } let matches2 = parentMatches.concat(renderedMatches.slice(0, index + 1)); let getChildren = () => { let children; if (error) { children = errorElement; } else if (shouldRenderHydrateFallback) { children = hydrateFallbackElement; } else if (match.route.Component) { children = /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(match.route.Component, null); } else if (match.route.element) { children = match.route.element; } else { children = outlet; } return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( RenderedRoute, { match, routeContext: { outlet, matches: matches2, isDataRoute: dataRouterState != null }, children } ); }; return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( RenderErrorBoundary, { location: dataRouterState.location, revalidation: dataRouterState.revalidation, component: errorElement, error, children: getChildren(), routeContext: { outlet: null, matches: matches2, isDataRoute: true }, onError } ) : getChildren(); }, null ); } function getDataRouterConsoleError(hookName) { return `${hookName} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`; } function useDataRouterContext(hookName) { let ctx = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext); invariant(ctx, getDataRouterConsoleError(hookName)); return ctx; } function useDataRouterState(hookName) { let state = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterStateContext); invariant(state, getDataRouterConsoleError(hookName)); return state; } function useRouteContext(hookName) { let route = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); invariant(route, getDataRouterConsoleError(hookName)); return route; } function useCurrentRouteId(hookName) { let route = useRouteContext(hookName); let thisRoute = route.matches[route.matches.length - 1]; invariant( thisRoute.route.id, `${hookName} can only be used on routes that contain a unique "id"` ); return thisRoute.route.id; } function useRouteId() { return useCurrentRouteId("useRouteId" /* UseRouteId */); } function useNavigation() { let state = useDataRouterState("useNavigation" /* UseNavigation */); return state.navigation; } function useRevalidator() { let dataRouterContext = useDataRouterContext("useRevalidator" /* UseRevalidator */); let state = useDataRouterState("useRevalidator" /* UseRevalidator */); let revalidate = react__WEBPACK_IMPORTED_MODULE_0__.useCallback(async () => { await dataRouterContext.router.revalidate(); }, [dataRouterContext.router]); return react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => ({ revalidate, state: state.revalidation }), [revalidate, state.revalidation] ); } function useMatches() { let { matches, loaderData } = useDataRouterState( "useMatches" /* UseMatches */ ); return react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => matches.map((m) => convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData] ); } function useLoaderData() { let state = useDataRouterState("useLoaderData" /* UseLoaderData */); let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */); return state.loaderData[routeId]; } function useRouteLoaderData(routeId) { let state = useDataRouterState("useRouteLoaderData" /* UseRouteLoaderData */); return state.loaderData[routeId]; } function useActionData() { let state = useDataRouterState("useActionData" /* UseActionData */); let routeId = useCurrentRouteId("useLoaderData" /* UseLoaderData */); return state.actionData ? state.actionData[routeId] : void 0; } function useRouteError() { let error = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteErrorContext); let state = useDataRouterState("useRouteError" /* UseRouteError */); let routeId = useCurrentRouteId("useRouteError" /* UseRouteError */); if (error !== void 0) { return error; } return state.errors?.[routeId]; } function useAsyncValue() { let value = react__WEBPACK_IMPORTED_MODULE_0__.useContext(AwaitContext); return value?._data; } function useAsyncError() { let value = react__WEBPACK_IMPORTED_MODULE_0__.useContext(AwaitContext); return value?._error; } var blockerId = 0; function useBlocker(shouldBlock) { let { router, basename } = useDataRouterContext("useBlocker" /* UseBlocker */); let state = useDataRouterState("useBlocker" /* UseBlocker */); let [blockerKey, setBlockerKey] = react__WEBPACK_IMPORTED_MODULE_0__.useState(""); let blockerFunction = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( (arg) => { if (typeof shouldBlock !== "function") { return !!shouldBlock; } if (basename === "/") { return shouldBlock(arg); } let { currentLocation, nextLocation, historyAction } = arg; return shouldBlock({ currentLocation: { ...currentLocation, pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname }, nextLocation: { ...nextLocation, pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname }, historyAction }); }, [basename, shouldBlock] ); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { let key = String(++blockerId); setBlockerKey(key); return () => router.deleteBlocker(key); }, [router]); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { if (blockerKey !== "") { router.getBlocker(blockerKey, blockerFunction); } }, [router, blockerKey, blockerFunction]); return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER; } function useNavigateStable() { let { router } = useDataRouterContext("useNavigate" /* UseNavigateStable */); let id = useCurrentRouteId("useNavigate" /* UseNavigateStable */); let activeRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(false); useIsomorphicLayoutEffect(() => { activeRef.current = true; }); let navigate = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( async (to, options = {}) => { warning(activeRef.current, navigateEffectWarning); if (!activeRef.current) return; if (typeof to === "number") { await router.navigate(to); } else { await router.navigate(to, { fromRouteId: id, ...options }); } }, [router, id] ); return navigate; } var alreadyWarned = {}; function warningOnce(key, cond, message) { if (!cond && !alreadyWarned[key]) { alreadyWarned[key] = true; warning(false, message); } } function useRoute(...args) { const currentRouteId = useCurrentRouteId( "useRoute" /* UseRoute */ ); const id = args[0] ?? currentRouteId; const state = useDataRouterState("useRoute" /* UseRoute */); const route = state.matches.find(({ route: route2 }) => route2.id === id); if (route === void 0) return void 0; return { handle: route.route.handle, loaderData: state.loaderData[id], actionData: state.actionData?.[id] }; } // lib/components.tsx // lib/server-runtime/warnings.ts var alreadyWarned2 = {}; function warnOnce(condition, message) { if (!condition && !alreadyWarned2[message]) { alreadyWarned2[message] = true; console.warn(message); } } // lib/components.tsx var USE_OPTIMISTIC = "useOptimistic"; var useOptimisticImpl = /*#__PURE__*/ (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (react__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(react__WEBPACK_IMPORTED_MODULE_0__, 2)))[USE_OPTIMISTIC]; var stableUseOptimisticSetter = () => void 0; function useOptimisticSafe(val) { if (useOptimisticImpl) { return useOptimisticImpl(val); } else { return [val, stableUseOptimisticSetter]; } } function mapRouteProperties(route) { let updates = { // Note: this check also occurs in createRoutesFromChildren so update // there if you change this -- please and thank you! hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null }; if (route.Component) { if (ENABLE_DEV_WARNINGS) { if (route.element) { warning( false, "You should not include both `Component` and `element` on your route - `Component` will be used." ); } } Object.assign(updates, { element: react__WEBPACK_IMPORTED_MODULE_0__.createElement(route.Component), Component: void 0 }); } if (route.HydrateFallback) { if (ENABLE_DEV_WARNINGS) { if (route.hydrateFallbackElement) { warning( false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used." ); } } Object.assign(updates, { hydrateFallbackElement: react__WEBPACK_IMPORTED_MODULE_0__.createElement(route.HydrateFallback), HydrateFallback: void 0 }); } if (route.ErrorBoundary) { if (ENABLE_DEV_WARNINGS) { if (route.errorElement) { warning( false, "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used." ); } } Object.assign(updates, { errorElement: react__WEBPACK_IMPORTED_MODULE_0__.createElement(route.ErrorBoundary), ErrorBoundary: void 0 }); } return updates; } var hydrationRouteProperties = [ "HydrateFallback", "hydrateFallbackElement" ]; function createMemoryRouter(routes, opts) { return createRouter({ basename: opts?.basename, getContext: opts?.getContext, future: opts?.future, history: createMemoryHistory({ initialEntries: opts?.initialEntries, initialIndex: opts?.initialIndex }), hydrationData: opts?.hydrationData, routes, hydrationRouteProperties, mapRouteProperties, dataStrategy: opts?.dataStrategy, patchRoutesOnNavigation: opts?.patchRoutesOnNavigation, instrumentations: opts?.instrumentations }).initialize(); } var Deferred = class { constructor() { this.status = "pending"; this.promise = new Promise((resolve, reject) => { this.resolve = (value) => { if (this.status === "pending") { this.status = "resolved"; resolve(value); } }; this.reject = (reason) => { if (this.status === "pending") { this.status = "rejected"; reject(reason); } }; }); } }; function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, onError, useTransitions }) { let unstable_rsc = useIsRSCRouterContext(); useTransitions = unstable_rsc || useTransitions; let [_state, setStateImpl] = react__WEBPACK_IMPORTED_MODULE_0__.useState(router.state); let [state, setOptimisticState] = useOptimisticSafe(_state); let [pendingState, setPendingState] = react__WEBPACK_IMPORTED_MODULE_0__.useState(); let [vtContext, setVtContext] = react__WEBPACK_IMPORTED_MODULE_0__.useState({ isTransitioning: false }); let [renderDfd, setRenderDfd] = react__WEBPACK_IMPORTED_MODULE_0__.useState(); let [transition, setTransition] = react__WEBPACK_IMPORTED_MODULE_0__.useState(); let [interruption, setInterruption] = react__WEBPACK_IMPORTED_MODULE_0__.useState(); let fetcherData = react__WEBPACK_IMPORTED_MODULE_0__.useRef(/* @__PURE__ */ new Map()); let setState = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( (newState, { deletedFetchers, newErrors, flushSync, viewTransitionOpts }) => { if (newErrors && onError) { Object.values(newErrors).forEach( (error) => onError(error, { location: newState.location, params: newState.matches[0]?.params ?? {}, pattern: getRoutePattern(newState.matches) }) ); } newState.fetchers.forEach((fetcher, key) => { if (fetcher.data !== void 0) { fetcherData.current.set(key, fetcher.data); } }); deletedFetchers.forEach((key) => fetcherData.current.delete(key)); warnOnce( flushSync === false || reactDomFlushSyncImpl != null, 'You provided the `flushSync` option to a router update, but you are not using the `` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.' ); let isViewTransitionAvailable = router.window != null && router.window.document != null && typeof router.window.document.startViewTransition === "function"; warnOnce( viewTransitionOpts == null || isViewTransitionAvailable, "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available." ); if (!viewTransitionOpts || !isViewTransitionAvailable) { if (reactDomFlushSyncImpl && flushSync) { reactDomFlushSyncImpl(() => setStateImpl(newState)); } else if (useTransitions === false) { setStateImpl(newState); } else { react__WEBPACK_IMPORTED_MODULE_0__.startTransition(() => { if (useTransitions === true) { setOptimisticState((s) => getOptimisticRouterState(s, newState)); } setStateImpl(newState); }); } return; } if (reactDomFlushSyncImpl && flushSync) { reactDomFlushSyncImpl(() => { if (transition) { renderDfd?.resolve(); transition.skipTransition(); } setVtContext({ isTransitioning: true, flushSync: true, currentLocation: viewTransitionOpts.currentLocation, nextLocation: viewTransitionOpts.nextLocation }); }); let t = router.window.document.startViewTransition(() => { reactDomFlushSyncImpl(() => setStateImpl(newState)); }); t.finished.finally(() => { reactDomFlushSyncImpl(() => { setRenderDfd(void 0); setTransition(void 0); setPendingState(void 0); setVtContext({ isTransitioning: false }); }); }); reactDomFlushSyncImpl(() => setTransition(t)); return; } if (transition) { renderDfd?.resolve(); transition.skipTransition(); setInterruption({ state: newState, currentLocation: viewTransitionOpts.currentLocation, nextLocation: viewTransitionOpts.nextLocation }); } else { setPendingState(newState); setVtContext({ isTransitioning: true, flushSync: false, currentLocation: viewTransitionOpts.currentLocation, nextLocation: viewTransitionOpts.nextLocation }); } }, [ router.window, reactDomFlushSyncImpl, transition, renderDfd, useTransitions, setOptimisticState, onError ] ); react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(() => router.subscribe(setState), [router, setState]); let initialized = state.initialized; react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(() => { if (!initialized && router.state.initialized) { setState(router.state, { deletedFetchers: [], flushSync: false, newErrors: null }); } }, [initialized, setState, router.state]); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { if (vtContext.isTransitioning && !vtContext.flushSync) { setRenderDfd(new Deferred()); } }, [vtContext]); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { if (renderDfd && pendingState && router.window) { let newState = pendingState; let renderPromise = renderDfd.promise; let transition2 = router.window.document.startViewTransition(async () => { if (useTransitions === false) { setStateImpl(newState); } else { react__WEBPACK_IMPORTED_MODULE_0__.startTransition(() => { if (useTransitions === true) { setOptimisticState((s) => getOptimisticRouterState(s, newState)); } setStateImpl(newState); }); } await renderPromise; }); transition2.finished.finally(() => { setRenderDfd(void 0); setTransition(void 0); setPendingState(void 0); setVtContext({ isTransitioning: false }); }); setTransition(transition2); } }, [ pendingState, renderDfd, router.window, useTransitions, setOptimisticState ]); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { if (renderDfd && pendingState && state.location.key === pendingState.location.key) { renderDfd.resolve(); } }, [renderDfd, transition, state.location, pendingState]); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { if (!vtContext.isTransitioning && interruption) { setPendingState(interruption.state); setVtContext({ isTransitioning: true, flushSync: false, currentLocation: interruption.currentLocation, nextLocation: interruption.nextLocation }); setInterruption(void 0); } }, [vtContext.isTransitioning, interruption]); let navigator = react__WEBPACK_IMPORTED_MODULE_0__.useMemo(() => { return { createHref: router.createHref, encodeLocation: router.encodeLocation, go: (n) => router.navigate(n), push: (to, state2, opts) => router.navigate(to, { state: state2, preventScrollReset: opts?.preventScrollReset }), replace: (to, state2, opts) => router.navigate(to, { replace: true, state: state2, preventScrollReset: opts?.preventScrollReset }) }; }, [router]); let basename = router.basename || "/"; let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => ({ router, navigator, static: false, basename, onError }), [router, navigator, basename, onError] ); return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(DataRouterContext.Provider, { value: dataRouterContext }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(DataRouterStateContext.Provider, { value: state }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(FetchersContext.Provider, { value: fetcherData.current }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(ViewTransitionContext.Provider, { value: vtContext }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( Router, { basename, location: state.location, navigationType: state.historyAction, navigator, useTransitions }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( MemoizedDataRoutes, { routes: router.routes, manifest: router.manifest, future: router.future, state, isStatic: false, onError } ) ))))), null); } function getOptimisticRouterState(currentState, newState) { return { // Don't surface "current location specific" stuff mid-navigation // (historyAction, location, matches, loaderData, errors, initialized, // restoreScroll, preventScrollReset, blockers, etc.) ...currentState, // Only surface "pending/in-flight stuff" // (navigation, revalidation, actionData, fetchers, ) navigation: newState.navigation.state !== "idle" ? newState.navigation : currentState.navigation, revalidation: newState.revalidation !== "idle" ? newState.revalidation : currentState.revalidation, actionData: newState.navigation.state !== "submitting" ? newState.actionData : currentState.actionData, fetchers: newState.fetchers }; } var MemoizedDataRoutes = react__WEBPACK_IMPORTED_MODULE_0__.memo(DataRoutes2); function DataRoutes2({ routes, manifest, future, state, isStatic, onError }) { return useRoutesImpl(routes, void 0, { manifest, state, isStatic, onError, future }); } function MemoryRouter({ basename, children, initialEntries, initialIndex, useTransitions }) { let historyRef = react__WEBPACK_IMPORTED_MODULE_0__.useRef(); if (historyRef.current == null) { historyRef.current = createMemoryHistory({ initialEntries, initialIndex, v5Compat: true }); } let history = historyRef.current; let [state, setStateImpl] = react__WEBPACK_IMPORTED_MODULE_0__.useState({ action: history.action, location: history.location }); let setState = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( (newState) => { if (useTransitions === false) { setStateImpl(newState); } else { react__WEBPACK_IMPORTED_MODULE_0__.startTransition(() => setStateImpl(newState)); } }, [useTransitions] ); react__WEBPACK_IMPORTED_MODULE_0__.useLayoutEffect(() => history.listen(setState), [history, setState]); return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( Router, { basename, children, location: state.location, navigationType: state.action, navigator: history, useTransitions } ); } function Navigate({ to, replace: replace2, state, relative }) { invariant( useInRouterContext(), // TODO: This error is probably because they somehow have 2 versions of // the router loaded. We can help them understand how to avoid that. ` may be used only in the context of a component.` ); let { static: isStatic } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(NavigationContext); warning( !isStatic, ` must not be used on the initial render in a . This is a no-op, but you should modify your code so the is only ever rendered in response to some user interaction or state change.` ); let { matches } = react__WEBPACK_IMPORTED_MODULE_0__.useContext(RouteContext); let { pathname: locationPathname } = useLocation(); let navigate = useNavigate(); let path = resolveTo( to, getResolveToMatches(matches), locationPathname, relative === "path" ); let jsonPath = JSON.stringify(path); react__WEBPACK_IMPORTED_MODULE_0__.useEffect(() => { navigate(JSON.parse(jsonPath), { replace: replace2, state, relative }); }, [navigate, jsonPath, relative, replace2, state]); return null; } function Outlet(props) { return useOutlet(props.context); } function Route(props) { invariant( false, `A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .` ); } function Router({ basename: basenameProp = "/", children = null, location: locationProp, navigationType = "POP" /* Pop */, navigator, static: staticProp = false, useTransitions }) { invariant( !useInRouterContext(), `You cannot render a inside another . You should never have more than one in your app.` ); let basename = basenameProp.replace(/^\/*/, "/"); let navigationContext = react__WEBPACK_IMPORTED_MODULE_0__.useMemo( () => ({ basename, navigator, static: staticProp, useTransitions, future: {} }), [basename, navigator, staticProp, useTransitions] ); if (typeof locationProp === "string") { locationProp = parsePath(locationProp); } let { pathname = "/", search = "", hash = "", state = null, key = "default", mask } = locationProp; let locationContext = react__WEBPACK_IMPORTED_MODULE_0__.useMemo(() => { let trailingPathname = stripBasename(pathname, basename); if (trailingPathname == null) { return null; } return { location: { pathname: trailingPathname, search, hash, state, key, mask }, navigationType }; }, [basename, pathname, search, hash, state, key, navigationType, mask]); warning( locationContext != null, ` is not able to match the URL "${pathname}${search}${hash}" because it does not start with the basename, so the won't render anything.` ); if (locationContext == null) { return null; } return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(NavigationContext.Provider, { value: navigationContext }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(LocationContext.Provider, { children, value: locationContext })); } function Routes({ children, location }) { return useRoutes(createRoutesFromChildren(children), location); } function Await({ children, errorElement, resolve }) { let dataRouterContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterContext); let dataRouterStateContext = react__WEBPACK_IMPORTED_MODULE_0__.useContext(DataRouterStateContext); let onError = react__WEBPACK_IMPORTED_MODULE_0__.useCallback( (error, errorInfo) => { if (dataRouterContext && dataRouterContext.onError && dataRouterStateContext) { dataRouterContext.onError(error, { location: dataRouterStateContext.location, params: dataRouterStateContext.matches[0]?.params || {}, pattern: getRoutePattern(dataRouterStateContext.matches), errorInfo }); } }, [dataRouterContext, dataRouterStateContext] ); return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement( AwaitErrorBoundary, { resolve, errorElement, onError }, /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(ResolveAwait, null, children) ); } var AwaitErrorBoundary = class extends react__WEBPACK_IMPORTED_MODULE_0__.Component { constructor(props) { super(props); this.state = { error: null }; } static getDerivedStateFromError(error) { return { error }; } componentDidCatch(error, errorInfo) { if (this.props.onError) { this.props.onError(error, errorInfo); } else { console.error( " caught the following error during render", error, errorInfo ); } } render() { let { children, errorElement, resolve } = this.props; let promise = null; let status = 0 /* pending */; if (!(resolve instanceof Promise)) { status = 1 /* success */; promise = Promise.resolve(); Object.defineProperty(promise, "_tracked", { get: () => true }); Object.defineProperty(promise, "_data", { get: () => resolve }); } else if (this.state.error) { status = 2 /* error */; let renderError = this.state.error; promise = Promise.reject().catch(() => { }); Object.defineProperty(promise, "_tracked", { get: () => true }); Object.defineProperty(promise, "_error", { get: () => renderError }); } else if (resolve._tracked) { promise = resolve; status = "_error" in promise ? 2 /* error */ : "_data" in promise ? 1 /* success */ : 0 /* pending */; } else { status = 0 /* pending */; Object.defineProperty(resolve, "_tracked", { get: () => true }); promise = resolve.then( (data2) => Object.defineProperty(resolve, "_data", { get: () => data2 }), (error) => { this.props.onError?.(error); Object.defineProperty(resolve, "_error", { get: () => error }); } ); } if (status === 2 /* error */ && !errorElement) { throw promise._error; } if (status === 2 /* error */) { return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(AwaitContext.Provider, { value: promise, children: errorElement }); } if (status === 1 /* success */) { return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(AwaitContext.Provider, { value: promise, children }); } throw promise; } }; function ResolveAwait({ children }) { let data2 = useAsyncValue(); let toRender = typeof children === "function" ? children(data2) : children; return /* @__PURE__ */ react__WEBPACK_IMPORTED_MODULE_0__.createElement(react__WEBPACK_IMPORTED_MODULE_0__.Fragment, null, toRender); } function createRoutesFromChildren(children, parentPath = []) { let routes = []; react__WEBPACK_IMPORTED_MODULE_0__.Children.forEach(children, (element, index) => { if (!react__WEBPACK_IMPORTED_MODULE_0__.isValidElement(element)) { return; } let treePath = [...parentPath, index]; if (element.type === react__WEBPACK_IMPORTED_MODULE_0__.Fragment) { routes.push.apply( routes, createRoutesFromChildren(element.props.children, treePath) ); return; } invariant( element.type === Route, `[${typeof element.type === "string" ? element.type : element.type.name}] is not a component. All component children of must be a or ` ); invariant( !element.props.index || !element.props.children, "An index route cannot have child routes." ); let route = { id: element.props.id || treePath.join("-"), caseSensitive: element.props.caseSensitive, element: element.props.element, Component: element.props.Component, index: element.props.index, path: element.props.path, middleware: element.props.middleware, loader: element.props.loader, action: element.props.action, hydrateFallbackElement: element.props.hydrateFallbackElement, HydrateFallback: element.props.HydrateFallback, errorElement: element.props.errorElement, ErrorBoundary: element.props.ErrorBoundary, hasErrorBoundary: element.props.hasErrorBoundary === true || element.props.ErrorBoundary != null || element.props.errorElement != null, shouldRevalidate: element.props.shouldRevalidate, handle: element.props.handle, lazy: element.props.lazy }; if (element.props.children) { route.children = createRoutesFromChildren( element.props.children, treePath ); } routes.push(route); }); return routes; } var createRoutesFromElements = createRoutesFromChildren; function renderMatches(matches) { return _renderMatches(matches); } function useRouteComponentProps() { return { params: useParams(), loaderData: useLoaderData(), actionData: useActionData(), matches: useMatches() }; } function WithComponentProps({ children }) { const props = useRouteComponentProps(); return react__WEBPACK_IMPORTED_MODULE_0__.cloneElement(children, props); } function withComponentProps(Component4) { return function WithComponentProps2() { const props = useRouteComponentProps(); return react__WEBPACK_IMPORTED_MODULE_0__.createElement(Component4, props); }; } function useHydrateFallbackProps() { return { params: useParams(), loaderData: useLoaderData(), actionData: useActionData() }; } function WithHydrateFallbackProps({ children }) { const props = useHydrateFallbackProps(); return react__WEBPACK_IMPORTED_MODULE_0__.cloneElement(children, props); } function withHydrateFallbackProps(HydrateFallback) { return function WithHydrateFallbackProps2() { const props = useHydrateFallbackProps(); return react__WEBPACK_IMPORTED_MODULE_0__.createElement(HydrateFallback, props); }; } function useErrorBoundaryProps() { return { params: useParams(), loaderData: useLoaderData(), actionData: useActionData(), error: useRouteError() }; } function WithErrorBoundaryProps({ children }) { const props = useErrorBoundaryProps(); return react__WEBPACK_IMPORTED_MODULE_0__.cloneElement(children, props); } function withErrorBoundaryProps(ErrorBoundary) { return function WithErrorBoundaryProps2() { const props = useErrorBoundaryProps(); return react__WEBPACK_IMPORTED_MODULE_0__.createElement(ErrorBoundary, props); }; } // lib/dom/dom.ts var defaultMethod = "get"; var defaultEncType = "application/x-www-form-urlencoded"; function isHtmlElement(object) { return typeof HTMLElement !== "undefined" && object instanceof HTMLElement; } function isButtonElement(object) { return isHtmlElement(object) && object.tagName.toLowerCase() === "button"; } function isFormElement(object) { return isHtmlElement(object) && object.tagName.toLowerCase() === "form"; } function isInputElement(object) { return isHtmlElement(object) && object.tagName.toLowerCase() === "input"; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } function shouldProcessLinkClick(event, target) { return event.button === 0 && // Ignore everything but left clicks (!target || target === "_self") && // Let browser handle "target=_blank" etc. !isModifiedEvent(event); } function createSearchParams(init = "") { return new URLSearchParams( typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo2, key) => { let value = init[key]; return memo2.concat( Array.isArray(value) ? value.map((v) => [key, v]) : [[key, value]] ); }, []) ); } function getSearchParamsForLocation(locationSearch, defaultSearchParams) { let searchParams = createSearchParams(locationSearch); if (defaultSearchParams) { defaultSearchParams.forEach((_, key) => { if (!searchParams.has(key)) { defaultSearchParams.getAll(key).forEach((value) => { searchParams.append(key, value); }); } }); } return searchParams; } var _formDataSupportsSubmitter = null; function isFormDataSubmitterSupported() { if (_formDataSupportsSubmitter === null) { try { new FormData( document.createElement("form"), // @ts-expect-error if FormData supports the submitter parameter, this will throw 0 ); _formDataSupportsSubmitter = false; } catch (e) { _formDataSupportsSubmitter = true; } } return _formDataSupportsSubmitter; } var supportedFormEncTypes = /* @__PURE__ */ new Set([ "application/x-www-form-urlencoded", "multipart/form-data", "text/plain" ]); function getFormEncType(encType) { if (encType != null && !supportedFormEncTypes.has(encType)) { warning( false, `"${encType}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${defaultEncType}"` ); return null; } return encType; } function getFormSubmissionInfo(target, basename) { let method; let action; let encType; let formData; let body; if (isFormElement(target)) { let attr = target.getAttribute("action"); action = attr ? stripBasename(attr, basename) : null; method = target.getAttribute("method") || defaultMethod; encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType; formData = new FormData(target); } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) { let form = target.form; if (form == null) { throw new Error( `Cannot submit a